blob: 3482cd430323bf384ac7ce21a5a7a647d39b917c [file] [log] [blame]
Lazar Kovacic8273d5d2021-08-18 14:52:55 +02001/*
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 "ZclString.h"
19
20namespace chip {
21
Boris Zbarsky071592d2021-09-07 10:56:05 -040022// ZCL strings are stored as pascal-strings (first byte contains the length of
23// the data), and a length of 255 means "invalid string" so the maximum actually
24// allowed string length is 254.
25constexpr size_t kBufferMaximumSize = 254;
Lazar Kovacic8273d5d2021-08-18 14:52:55 +020026
27CHIP_ERROR MakeZclCharString(MutableByteSpan & buffer, const char * cString)
28{
29 CHIP_ERROR err = CHIP_NO_ERROR;
30
31 if (buffer.size() == 0)
32 {
33 // We can't even put a 0 length in there.
34 return CHIP_ERROR_INBOUND_MESSAGE_TOO_BIG;
35 }
36 size_t len = strlen(cString);
37 size_t availableStorage = min(buffer.size() - 1, kBufferMaximumSize);
38 if (len > availableStorage)
39 {
40 buffer.data()[0] = 0;
41 return CHIP_ERROR_INBOUND_MESSAGE_TOO_BIG;
42 }
43
44 buffer.data()[0] = static_cast<uint8_t>(len);
45 memcpy(&buffer.data()[1], cString, len);
46 return err;
47}
48
49} // namespace chip