thomastrapp / recursive-variant

A serializable recursive variant for JSON-like data

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Serializable Boost Recursive Variant

A Boost.Variant for JSON-like data with serialization support for cereal.

This project is released under the terms of the MIT license.

Dependencies

  • Boost.Variant, Boost.MPL
  • cereal
  • Testing: cmake, catch

Types

Alias Type
Value::Value Int|String|Vector|Map
Value::Int int32_t
Value::String std::string
Value::Vector std::vector<Value::Value>
Value::Map std::unordered_map<std::string, Value::Value>

The gist

using Int = std::int32_t;
using String = std::string;
using Value = boost::make_recursive_variant<
    Int
  , String
  , std::vector<boost::recursive_variant_>
  , std::unordered_map<String, boost::recursive_variant_>
>::type;
using Vector = boost::mpl::at<Value::types, boost::mpl::int_<2>>::type;
using Map = boost::mpl::at<Value::types, boost::mpl::int_<3>>::type;

Defined in Value.h.

Helpers

template<typename Type>
inline bool Is(const Value& value) { return value.which() == TypeIndex<Type>; }

template<typename Type>
inline Type& Get(Value& value) { return boost::get<Type>(value); }

template<typename Type>
inline const Type& Get(const Value& value) { return boost::get<Type>(value); }

Defined in Helper.h.

Serialization

Powered by cereal.

Value::Map val({{"beep","boop"}, {"whoop", Value::Vector({1,2,3,"whoop"})}});
std::string payload = Value::Pack(val);

Value::Value unpacked = Value::Unpack(payload);
assert(Value::Is<Value::Map>(unpacked));

Defined in Serialization.h.

Switching by type

namespace V = Value;
switch( value.which() )
{
case V::TypeIndex<V::Int>:    /* ... */ break;
case V::TypeIndex<V::String>: /* ... */ break;
case V::TypeIndex<V::Vector>: /* ... */ break;
case V::TypeIndex<V::Map>:    /* ... */ break;
default: break;
}

Defined in TypeIndex.h.

Printing

Value::Print(Value::Map({{"beep","boop"}, {"whoop", Value::Vector({1,2,3,"whoop"})}}), std::cout);
// {"whoop":[1, 2, 3, "whoop"], "beep":"boop"}

Defined in Print.h.

About

A serializable recursive variant for JSON-like data

License:MIT License


Languages

Language:C++ 80.9%Language:CMake 17.6%Language:C 1.5%