string.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #ifndef FLATBUFFERS_STRING_H_
  17. #define FLATBUFFERS_STRING_H_
  18. #include "flatbuffers/base.h"
  19. #include "flatbuffers/vector.h"
  20. namespace flatbuffers {
  21. struct String : public Vector<char> {
  22. const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
  23. std::string str() const { return std::string(c_str(), size()); }
  24. // clang-format off
  25. #ifdef FLATBUFFERS_HAS_STRING_VIEW
  26. flatbuffers::string_view string_view() const {
  27. return flatbuffers::string_view(c_str(), size());
  28. }
  29. #endif // FLATBUFFERS_HAS_STRING_VIEW
  30. // clang-format on
  31. bool operator<(const String &o) const {
  32. return StringLessThan(this->data(), this->size(), o.data(), o.size());
  33. }
  34. };
  35. // Convenience function to get std::string from a String returning an empty
  36. // string on null pointer.
  37. static inline std::string GetString(const String *str) {
  38. return str ? str->str() : "";
  39. }
  40. // Convenience function to get char* from a String returning an empty string on
  41. // null pointer.
  42. static inline const char *GetCstring(const String *str) {
  43. return str ? str->c_str() : "";
  44. }
  45. #ifdef FLATBUFFERS_HAS_STRING_VIEW
  46. // Convenience function to get string_view from a String returning an empty
  47. // string_view on null pointer.
  48. static inline flatbuffers::string_view GetStringView(const String *str) {
  49. return str ? str->string_view() : flatbuffers::string_view();
  50. }
  51. #endif // FLATBUFFERS_HAS_STRING_VIEW
  52. } // namespace flatbuffers
  53. #endif // FLATBUFFERS_STRING_H_