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 4249 : 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 4249 : return Put(s, strlen(s));
27 : }
28 :
29 7682 : BufferWriter & BufferWriter::Put(const void * buf, size_t len)
30 : {
31 7682 : size_t available = Available();
32 :
33 7682 : if (available > 0)
34 : {
35 7283 : memmove(mBuf + mNeeded, buf, available < len ? available : len);
36 : }
37 :
38 7682 : mNeeded += len;
39 7682 : return *this;
40 : }
41 :
42 1114454 : BufferWriter & BufferWriter::Put(uint8_t c)
43 : {
44 1114454 : if (mNeeded < mSize)
45 : {
46 1113430 : mBuf[mNeeded] = c;
47 : }
48 1114454 : ++mNeeded;
49 1114454 : return *this;
50 : }
51 :
52 193240 : LittleEndian::BufferWriter & LittleEndian::BufferWriter::EndianPut(uint64_t x, size_t size)
53 : {
54 705017 : while (size > 0)
55 : {
56 511777 : Put(static_cast<uint8_t>(x & 0xff));
57 511777 : x >>= 8;
58 511777 : size--;
59 : }
60 193240 : return *this;
61 : }
62 :
63 144 : LittleEndian::BufferWriter & LittleEndian::BufferWriter::EndianPutSigned(int64_t x, size_t size)
64 : {
65 728 : while (size > 0)
66 : {
67 584 : Put(static_cast<uint8_t>(x & 0xff));
68 584 : x >>= 8;
69 584 : size--;
70 : }
71 144 : return *this;
72 : }
73 :
74 6171 : BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPut(uint64_t x, size_t size)
75 : {
76 20244 : while (size > 0)
77 : {
78 14073 : size--;
79 14073 : Put(static_cast<uint8_t>((x >> (size * 8)) & 0xff));
80 : }
81 6171 : return *this;
82 : }
83 :
84 6 : BigEndian::BufferWriter & BigEndian::BufferWriter::EndianPutSigned(int64_t x, size_t size)
85 : {
86 37 : while (size > 0)
87 : {
88 31 : size--;
89 31 : Put(static_cast<uint8_t>((x >> (size * 8)) & 0xff));
90 : }
91 6 : return *this;
92 : }
93 :
94 : } // namespace Encoding
95 : } // namespace chip
|