1 /*
2 * Copyright 2021 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef FLATBUFFERS_STRING_H_
18 #define FLATBUFFERS_STRING_H_
19
20 #include "flatbuffers/base.h"
21 #include "flatbuffers/vector.h"
22
23 namespace flatbuffers {
24
25 struct String : public Vector<char> {
c_strString26 const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
strString27 std::string str() const { return std::string(c_str(), size()); }
28
29 // clang-format off
30 #ifdef FLATBUFFERS_HAS_STRING_VIEW
string_viewString31 flatbuffers::string_view string_view() const {
32 return flatbuffers::string_view(c_str(), size());
33 }
34
35 /* implicit */
string_viewString36 operator flatbuffers::string_view() const {
37 return flatbuffers::string_view(c_str(), size());
38 }
39 #endif // FLATBUFFERS_HAS_STRING_VIEW
40 // clang-format on
41
42 bool operator<(const String &o) const {
43 return StringLessThan(this->data(), this->size(), o.data(), o.size());
44 }
45 };
46
47 // Convenience function to get std::string from a String returning an empty
48 // string on null pointer.
GetString(const String * str)49 static inline std::string GetString(const String *str) {
50 return str ? str->str() : "";
51 }
52
53 // Convenience function to get char* from a String returning an empty string on
54 // null pointer.
GetCstring(const String * str)55 static inline const char *GetCstring(const String *str) {
56 return str ? str->c_str() : "";
57 }
58
59 #ifdef FLATBUFFERS_HAS_STRING_VIEW
60 // Convenience function to get string_view from a String returning an empty
61 // string_view on null pointer.
GetStringView(const String * str)62 static inline flatbuffers::string_view GetStringView(const String *str) {
63 return str ? str->string_view() : flatbuffers::string_view();
64 }
65 #endif // FLATBUFFERS_HAS_STRING_VIEW
66
67 } // namespace flatbuffers
68
69 #endif // FLATBUFFERS_STRING_H_
70