Line data Source code
1 : /* 2 : * 3 : * Copyright (c) 2021 Project CHIP Authors 4 : * 5 : * Licensed under the Apache License, Version 2.0 (the "License"); 6 : * you may not use this file except in compliance with the License. 7 : * You may obtain a copy of the License at 8 : * 9 : * http://www.apache.org/licenses/LICENSE-2.0 10 : * 11 : * Unless required by applicable law or agreed to in writing, software 12 : * distributed under the License is distributed on an "AS IS" BASIS, 13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 : * See the License for the specific language governing permissions and 15 : * limitations under the License. 16 : */ 17 : 18 : #include "BufferWriter.h" 19 : 20 : namespace chip { 21 : namespace Encoding { 22 : 23 4497 : BufferWriter & BufferWriter::Put(const char * s) 24 : { 25 : static_assert(CHAR_BIT == 8, "We're assuming char and uint8_t are the same size"); 26 4497 : return Put(s, strlen(s)); 27 : } 28 : 29 7565 : BufferWriter & BufferWriter::Put(const void * buf, size_t len) 30 : { 31 7565 : size_t available = Available(); 32 : 33 7565 : if (available > 0) 34 : { 35 7183 : memmove(mBuf + mNeeded, buf, available < len ? available : len); 36 : } 37 : 38 7565 : mNeeded += len; 39 7565 : return *this; 40 : } 41 : 42 271638 : BufferWriter & BufferWriter::Put(uint8_t c) 43 : { 44 271638 : if (mNeeded < mSize) 45 : { 46 270597 : mBuf[mNeeded] = c; 47 : } 48 271638 : ++mNeeded; 49 271638 : return *this; 50 : } 51 : 52 38117 : LittleEndian::BufferWriter & LittleEndian::BufferWriter::EndianPut(uint64_t x, size_t size) 53 : { 54 266106 : while (size > 0) 55 : { 56 227989 : Put(static_cast<uint8_t>(x & 0xff)); 57 227989 : x >>= 8; 58 227989 : size--; 59 : } 60 38117 : return *this; 61 : } 62 : 63 34 : LittleEndian::BufferWriter & LittleEndian::BufferWriter::EndianPutSigned(int64_t x, size_t size) 64 : { 65 170 : while (size > 0) 66 : { 67 136 : Put(static_cast<uint8_t>(x & 0xff)); 68 136 : x >>= 8; 69 136 : size--; 70 : } 71 34 : return *this; 72 : } 73 : 74 6563 : BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPut(uint64_t x, size_t size) 75 : { 76 21532 : while (size-- > 0) 77 : { 78 14969 : Put(static_cast<uint8_t>((x >> (size * 8)) & 0xff)); 79 : } 80 6563 : return *this; 81 : } 82 : 83 6 : BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPutSigned(int64_t x, size_t size) 84 : { 85 37 : while (size-- > 0) 86 : { 87 31 : Put(static_cast<uint8_t>((x >> (size * 8)) & 0xff)); 88 : } 89 6 : return *this; 90 : } 91 : 92 : } // namespace Encoding 93 : } // namespace chip