github stephenberry/glaze v5.4.0

latest releases: v8.3.0, v8.2.0, v8.1.0...
15 months ago

New Glaze Documentation Page

Glaze now hosts documentation for easier browsing: https://stephenberry.github.io/glaze/
This documentation organizes what was already in the glaze/docs directory. More documentation has been added in this release.

Compile Time rename_key Utility

Glaze metadata now supports an easy approach to rename specific keys at compile time for reflected structs:

struct renamed_t
{
   std::string first_name{};
   std::string last_name{};
   int age{};
};

template <>
struct glz::meta<renamed_t>
{
   static constexpr std::string_view rename_key(const std::string_view key) {
      if (key == "first_name") {
         return "firstName";
      }
      else if (key == "last_name") {
         return "lastName";
      }
      return key;
   }
};

Even more powerful is the ability to use std::string at compile time for dynamic key transformations:

struct suffixed_keys_t
{
   std::string first{};
   std::string last{};
};

template <>
struct glz::meta<suffixed_keys_t>
{
   static constexpr std::string rename_key(const auto key) {
      return std::string(key) + "_name";
   }
};

Error handling for glz::custom

Developers can always throw errors within glz::custom, but this update adds support for handling the glz::context for errors when working with glz::custom. This allows complex error handling with glz::custom even on platforms with exceptions disabled.

Example:

struct age_custom_error_obj
{
   int age{};
};

template <>
struct glz::meta<age_custom_error_obj>
{
   using T = age_custom_error_obj;
   static constexpr auto read_x = [](T& s, int age, glz::context& ctx) {
      if (age < 21) {
         ctx.error = glz::error_code::constraint_violated;
         ctx.custom_error_message = "age too young";
      }
      else {
         s.age = age;
      }
   };
   static constexpr auto value = object("age", glz::custom<read_x, &T::age>);
};

In use:

age_custom_error_obj obj{};
std::string s = R"({"age":18})";
auto ec = glz::read_json(obj, s);
auto err_msg = glz::format_error(ec, s);
std::cout << err_msg << '\n';

Output:

1:10: constraint_violated
   {"age":18}
            ^ age too young

Breaking Change

Removed the compile time option: use_hash_comparison. The impact of this option has long been diminished due to Glaze's newer hashing approach. Removing this option only breaks code that explicitly set this option to false (defaulted to true). Remove references to this code and everything should work fine.

Improvements

Fixes

New Contributors

Full Changelog: v5.3.1...v5.4.0

Don't miss a new glaze release

NewReleases is sending notifications on new releases.