James Kuszmaul | 8e62b02 | 2022-03-22 09:33:25 -0700 | [diff] [blame] | 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> { |
| 26 | const char *c_str() const { return reinterpret_cast<const char *>(Data()); } |
| 27 | std::string str() const { return std::string(c_str(), size()); } |
| 28 | |
| 29 | // clang-format off |
| 30 | #ifdef FLATBUFFERS_HAS_STRING_VIEW |
| 31 | flatbuffers::string_view string_view() const { |
| 32 | return flatbuffers::string_view(c_str(), size()); |
| 33 | } |
| 34 | #endif // FLATBUFFERS_HAS_STRING_VIEW |
| 35 | // clang-format on |
| 36 | |
| 37 | bool operator<(const String &o) const { |
| 38 | return StringLessThan(this->data(), this->size(), o.data(), o.size()); |
| 39 | } |
| 40 | }; |
| 41 | |
| 42 | // Convenience function to get std::string from a String returning an empty |
| 43 | // string on null pointer. |
| 44 | static inline std::string GetString(const String *str) { |
| 45 | return str ? str->str() : ""; |
| 46 | } |
| 47 | |
| 48 | // Convenience function to get char* from a String returning an empty string on |
| 49 | // null pointer. |
| 50 | static inline const char *GetCstring(const String *str) { |
| 51 | return str ? str->c_str() : ""; |
| 52 | } |
| 53 | |
| 54 | #ifdef FLATBUFFERS_HAS_STRING_VIEW |
| 55 | // Convenience function to get string_view from a String returning an empty |
| 56 | // string_view on null pointer. |
| 57 | static inline flatbuffers::string_view GetStringView(const String *str) { |
| 58 | return str ? str->string_view() : flatbuffers::string_view(); |
| 59 | } |
| 60 | #endif // FLATBUFFERS_HAS_STRING_VIEW |
| 61 | |
| 62 | } // namespace flatbuffers |
| 63 | |
| 64 | #endif // FLATBUFFERS_STRING_H_ |