json_pointer.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2011-present Facebook, Inc.
  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. #pragma once
  17. #include <string>
  18. #include <vector>
  19. #include <folly/Expected.h>
  20. #include <folly/Range.h>
  21. namespace folly {
  22. /*
  23. * json_pointer
  24. *
  25. * As described in RFC 6901 "JSON Pointer".
  26. *
  27. * Implements parsing. Traversal using the pointer over data structures must be
  28. * implemented separately.
  29. */
  30. class json_pointer {
  31. public:
  32. enum class parse_error {
  33. invalid_first_character,
  34. invalid_escape_sequence,
  35. };
  36. class parse_exception : public std::runtime_error {
  37. using std::runtime_error::runtime_error;
  38. };
  39. json_pointer() = default;
  40. ~json_pointer() = default;
  41. /*
  42. * Parse string into vector of unescaped tokens.
  43. * Non-throwing and throwing versions.
  44. */
  45. static Expected<json_pointer, parse_error> try_parse(StringPiece const str);
  46. static json_pointer parse(StringPiece const str);
  47. /*
  48. * Return true if this pointer is proper to prefix to another pointer
  49. */
  50. bool is_prefix_of(json_pointer const& other) const noexcept;
  51. /*
  52. * Get access to the parsed tokens for applications that want to traverse
  53. * the pointer.
  54. */
  55. std::vector<std::string> const& tokens() const;
  56. friend bool operator==(json_pointer const& lhs, json_pointer const& rhs) {
  57. return lhs.tokens_ == rhs.tokens_;
  58. }
  59. friend bool operator!=(json_pointer const& lhs, json_pointer const& rhs) {
  60. return lhs.tokens_ != rhs.tokens_;
  61. }
  62. private:
  63. explicit json_pointer(std::vector<std::string>) noexcept;
  64. /*
  65. * Unescape the specified escape sequences, returns false if incorrect
  66. */
  67. static bool unescape(std::string&);
  68. std::vector<std::string> tokens_;
  69. };
  70. } // namespace folly