event.h 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #pragma once
  2. #include "cyson_enums.h"
  3. #include "scalar.h"
  4. #include <util/generic/strbuf.h>
  5. #include <util/system/types.h>
  6. #include <util/system/yassert.h>
  7. namespace NYsonPull {
  8. //! A well-formed decoded YSON stream can be described by the following grammar:
  9. //!
  10. //! STREAM[node] ::= begin_stream VALUE end_stream
  11. //! STREAM[list_fragment] ::= begin_stream LIST_FRAGMENT end_stream
  12. //! STREAM[map_fragment] ::= begin_stream MAP_FRAGMENT end_stream
  13. //! LIST_FRAGMENT ::= { VALUE; }
  14. //! MAP_FRAGMENT ::= { KEY VALUE; }
  15. //! KEY ::= key(String)
  16. //! VALUE ::= VALUE_NOATTR | ATTRIBUTES VALUE_NOATTR
  17. //! ATTRIBUTES ::= begin_attributes MAP_FRAGMENT end_attributes
  18. //! VALUE_NOATTR ::= scalar(Scalar) | LIST | MAP
  19. //! LIST ::= begin_list LIST_FRAGMENT end_list
  20. //! MAP ::= begin_map MAP_FRAGMENT end_map
  21. //! \brief YSON event type tag. Corresponds to YSON grammar.
  22. enum class EEventType {
  23. BeginStream = YSON_EVENT_BEGIN_STREAM,
  24. EndStream = YSON_EVENT_END_STREAM,
  25. BeginList = YSON_EVENT_BEGIN_LIST,
  26. EndList = YSON_EVENT_END_LIST,
  27. BeginMap = YSON_EVENT_BEGIN_MAP,
  28. EndMap = YSON_EVENT_END_MAP,
  29. BeginAttributes = YSON_EVENT_BEGIN_ATTRIBUTES,
  30. EndAttributes = YSON_EVENT_END_ATTRIBUTES,
  31. Key = YSON_EVENT_KEY,
  32. Scalar = YSON_EVENT_SCALAR,
  33. };
  34. //! \brief YSON event variant type.
  35. class TEvent {
  36. EEventType Type_;
  37. TScalar Value_;
  38. public:
  39. //! \brief Construct a tag-only event.
  40. explicit constexpr TEvent(EEventType type = EEventType::BeginStream)
  41. : Type_{type} {
  42. }
  43. //! \brief Construct a tag+value event.
  44. //!
  45. //! Only \p EEventType::key is meaningful.
  46. constexpr TEvent(EEventType type, const TScalar& value)
  47. : Type_{type}
  48. , Value_{value} {
  49. }
  50. //! \brief Construct a \p EEventType::scalar event.
  51. explicit constexpr TEvent(const TScalar& value)
  52. : Type_{EEventType::Scalar}
  53. , Value_{value} {
  54. }
  55. EEventType Type() const {
  56. return Type_;
  57. }
  58. //! \brief Get TScalar value.
  59. //!
  60. //! Undefined behaviour when event type is not \p EEventType::scalar.
  61. const TScalar& AsScalar() const {
  62. Y_ASSERT(Type_ == EEventType::Scalar || Type_ == EEventType::Key);
  63. return Value_;
  64. }
  65. //! \brief Get string value.
  66. //!
  67. //! Undefined behaviour when event type is not \p EEventType::key.
  68. TStringBuf AsString() const {
  69. Y_ASSERT(Type_ == EEventType::Key || (Type_ == EEventType::Scalar && Value_.Type() == EScalarType::String));
  70. return Value_.AsString();
  71. }
  72. };
  73. }