Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2026 Project CHIP Authors
4 : * All rights reserved.
5 : *
6 : * Licensed under the Apache License, Version 2.0 (the "License");
7 : * you may not use this file except in compliance with the License.
8 : * You may obtain a copy of the License at
9 : *
10 : * http://www.apache.org/licenses/LICENSE-2.0
11 : *
12 : * Unless required by applicable law or agreed to in writing, software
13 : * distributed under the License is distributed on an "AS IS" BASIS,
14 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 : * See the License for the specific language governing permissions and
16 : * limitations under the License.
17 : */
18 :
19 : #pragma once
20 :
21 : #include <string>
22 :
23 : #include <lib/support/Span.h>
24 :
25 : namespace chip {
26 :
27 : /**
28 : * @brief Convert a CharSpan to an owning std::string.
29 : *
30 : * Handles a default-constructed (`data()==nullptr`, `size()==0`) span without invoking
31 : * `std::string(nullptr, 0)`, which is undefined behavior per the C++ standard. Both default
32 : * spans and spans with `size()==0` but a non-null pointer produce an empty string; non-empty
33 : * spans copy `size()` bytes verbatim.
34 : *
35 : * Lives in its own header so `lib/support/Span.h` can stay free of `<string>` (it is included
36 : * by core SDK headers compiled for embedded targets where `std::string` is undesirable).
37 : * Callers that already pull `<string>` (e.g. controller / app / Darwin code) can include this
38 : * header to deduplicate the otherwise-repeated
39 : * `span.empty() ? std::string() : std::string(span.data(), span.size())` idiom.
40 : */
41 11 : inline std::string CharSpanToStdString(CharSpan span)
42 : {
43 11 : return span.empty() ? std::string() : std::string(span.data(), span.size());
44 : }
45 :
46 : } // namespace chip
|