enum.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "enum.h"
  2. #include "format.h"
  3. namespace NYT {
  4. ////////////////////////////////////////////////////////////////////////////////
  5. template <bool failOnError>
  6. std::optional<TString> DecodeEnumValueImpl(TStringBuf value)
  7. {
  8. auto camelValue = UnderscoreCaseToCamelCase(value);
  9. auto underscoreValue = CamelCaseToUnderscoreCase(camelValue);
  10. if (value != underscoreValue) {
  11. if constexpr (failOnError) {
  12. throw TSimpleException(Format("Enum value %Qv is not in a proper underscore case; did you mean %Qv?",
  13. value,
  14. underscoreValue));
  15. } else {
  16. return std::nullopt;
  17. }
  18. }
  19. return camelValue;
  20. }
  21. std::optional<TString> TryDecodeEnumValue(TStringBuf value)
  22. {
  23. return DecodeEnumValueImpl<false>(value);
  24. }
  25. TString DecodeEnumValue(TStringBuf value)
  26. {
  27. auto decodedValue = DecodeEnumValueImpl<true>(value);
  28. YT_VERIFY(decodedValue);
  29. return *decodedValue;
  30. }
  31. TString EncodeEnumValue(TStringBuf value)
  32. {
  33. return CamelCaseToUnderscoreCase(value);
  34. }
  35. namespace NDetail {
  36. void ThrowMalformedEnumValueException(TStringBuf typeName, TStringBuf value)
  37. {
  38. throw TSimpleException(Format("Error parsing %v value %Qv",
  39. typeName,
  40. value));
  41. }
  42. void FormatUnknownEnumValue(TStringBuilderBase* builder, TStringBuf name, i64 value)
  43. {
  44. builder->AppendFormat("%v(%v)", name, value);
  45. }
  46. } // namespace NDetail
  47. ////////////////////////////////////////////////////////////////////////////////
  48. } // namespace NYT