Lazar Kovacic | 8273d5d | 2021-08-18 14:52:55 +0200 | [diff] [blame] | 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 "ZclString.h" |
| 19 | |
| 20 | namespace chip { |
| 21 | |
Boris Zbarsky | 071592d | 2021-09-07 10:56:05 -0400 | [diff] [blame] | 22 | // 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. |
| 25 | constexpr size_t kBufferMaximumSize = 254; |
Lazar Kovacic | 8273d5d | 2021-08-18 14:52:55 +0200 | [diff] [blame] | 26 | |
| 27 | CHIP_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 |