Skip to content

Add objects, arrays & formatter #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
May 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .clang-format
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Language: Cpp
BasedOnStyle: LLVM
AlwaysBreakTemplateDeclarations: Yes
BreakBeforeBraces: Attach
BreakBeforeBraces: Allman
ColumnLimit: 160
SpaceAfterTemplateKeyword: true
Standard: c++20
Expand All @@ -29,3 +29,4 @@ IncludeCategories:
Priority: 30
PointerAlignment: Left
QualifierAlignment: Left
NamespaceIndentation: All
29 changes: 28 additions & 1 deletion Test/Test.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,30 @@
#include <cppjson/cppjson.hpp>
#include <print>

int main() { cppjson::hello_world(); }
int main()
{
cppjson::Object object{};
std::println("{}", object);
object["test1"] = "Hello World";
object["test2"] = 123.0;
object["sub"]["veryNested"] = 6.0;
cppjson::Array& array = object["array"];
array[] = 2;
array[] = 6.0;
array[0] = 1;
array[] = "Stirng";
array.EmplaceBack(nullptr);
try
{
array[2] = true;
}
catch (const std::logic_error& error)
{
std::println("Error = {}", error.what());
}

std::println("{}", object);
std::println("object[\"test1\"] = {}", object["test1"]);
const std::string test = object["test1"];
std::println("test = {}", test);
}
7 changes: 3 additions & 4 deletions cppjson/include/cppjson/cppjson.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#pragma once
#pragma once

namespace cppjson {
void hello_world();
} // namespace cppjson
#include "formatter.hpp"
#include "object.hpp"
125 changes: 125 additions & 0 deletions cppjson/include/cppjson/formatter.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
#include <format>
#include "object.hpp"

template <>
struct std::formatter<cppjson::JsonObject>
{
constexpr auto parse(std::format_parse_context& context) { return context.begin(); }

auto format(const cppjson::JsonObject& object, std::format_context& context) const
{
switch (object._dataType)
{
case cppjson::JsonType::Null: return std::format_to(context.out(), "null");
case cppjson::JsonType::Bool: return std::format_to(context.out(), "{}", object.DangerousAs<bool>());
case cppjson::JsonType::Number: return std::format_to(context.out(), "{}", object.DangerousAs<double>());
case cppjson::JsonType::String: return std::format_to(context.out(), "\"{}\"", object.DangerousAs<std::string>());
case cppjson::JsonType::Object:
{
const auto& node = object.DangerousAs<cppjson::Object>();

std::string built = "{ ";
for (const auto& [key, value] : node._nodes) built += std::format("\"{}\": {}, ", key, value);

if (!node._nodes.empty()) // remove trailing commas
{
built.pop_back();
built.pop_back();
built += " }";
}
else
built += "}";

return std::format_to(context.out(), "{}", built);
}
case cppjson::JsonType::Array:
{
const auto& array = object.DangerousAs<cppjson::Array>();

std::string built = "[ ";
for (const auto& element : array._objects) built += std::format("{}, ", element);

if (!array._objects.empty()) // remove trailing commas
{
built.pop_back();
built.pop_back();
built += " ]";
}
else
built += "]";

return std::format_to(context.out(), "{}", built);
}
}

throw std::logic_error("Unknown type");
}
};

template <>
struct std::formatter<cppjson::Object>
{
constexpr auto parse(std::format_parse_context& context) { return context.begin(); }

auto format(const cppjson::Object& object, std::format_context& context) const
{
std::string built = "{ ";
for (const auto& [key, value] : object._nodes) built += std::format("\"{}\": {}, ", key, value);

if (!object._nodes.empty()) // remove trailing commas
{
built.pop_back();
built.pop_back();
built += " }";
}
else
built += "}";

return std::format_to(context.out(), "{}", built);
}
};

template <>
struct std::formatter<cppjson::Array>
{
constexpr auto parse(std::format_parse_context& context) { return context.begin(); }

auto format(const cppjson::Array& array, std::format_context& context) const
{
std::string built = "[ ";
for (const auto& element : array._objects) built += std::format("{}, ", element);

if (!array._objects.empty()) // remove trailing commas
{
built.pop_back();
built.pop_back();
built += " ]";
}
else
built += "]";

return std::format_to(context.out(), "{}", built);
}
};

template <>
struct std::formatter<cppjson::Object::ObjectProxy>
{
constexpr auto parse(std::format_parse_context& context) { return context.begin(); }

auto format(const cppjson::Object::ObjectProxy& object, std::format_context& context) const
{
return std::format_to(context.out(), "{}", object._object.get());
}
};

template <>
struct std::formatter<cppjson::Object::ConstObjectProxy>
{
constexpr auto parse(std::format_parse_context& context) { return context.begin(); }

auto format(const cppjson::Object::ConstObjectProxy& object, std::format_context& context) const
{
return std::format_to(context.out(), "{}", object._object.get());
}
};
187 changes: 187 additions & 0 deletions cppjson/include/cppjson/object.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
#pragma once

#include <algorithm>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <format>
#include <functional>
#include <string>
#include <unordered_map>
#include <vector>

namespace cppjson
{
enum struct JsonType
{
Null,
String,
Object,
Number,
Bool,
Array
};

class JsonObject
{
public:
explicit JsonObject();
JsonObject(const JsonObject& other);
JsonObject(JsonObject&& other) noexcept;
JsonObject& operator=(const JsonObject& other);
JsonObject& operator=(JsonObject&& other) noexcept;
~JsonObject();

template <typename T>
T& As() noexcept(false);

template <typename T>
const T& As() const noexcept(false);

private:
JsonType _dataType{};
std::byte* _dataStorage{};

void Destroy();
template <typename T>
T& DangerousAs() noexcept
{
return *std::launder(reinterpret_cast<T*>(this->_dataStorage));
}
template <typename T>
const T& DangerousAs() const noexcept
{
return *std::launder(reinterpret_cast<T*>(this->_dataStorage));
}

friend struct std::formatter<cppjson::JsonObject>;
};

class Object
{
public:
explicit Object() = default;
Object(const Object&) = default;
Object(Object&&) = default;
Object& operator=(const Object&) = default;
Object& operator=(Object&&) = default;
~Object() = default;

class ObjectProxy
{
public:
explicit ObjectProxy(JsonObject& object) : _object(std::ref(object)) {}

template <typename T>
requires(!std::same_as<std::remove_cvref_t<T>, JsonObject>)
explicit(false) operator T&()
{
return this->_object.get().As<T>();
}

template <typename T>
requires(!std::same_as<std::remove_cvref_t<T>, JsonObject>)
explicit(false) operator const T&() const
{
return this->_object.get().As<T>();
}

template <typename T>
std::conditional_t<std::integral<T> && !std::same_as<T, bool>, void, T&> operator=(T&& assignment)
{
if constexpr (std::integral<T> && !std::same_as<T, bool>) static_cast<double&>(*this) = static_cast<double>(assignment);
else
return static_cast<T&>(*this) = std::forward<T>(assignment);
}

template <std::size_t N>
std::string& operator=(const char (&str)[N])
{
return static_cast<std::string&>(*this) = std::string{str};
}

ObjectProxy operator[](const std::string& key);
template <std::size_t N>
ObjectProxy operator[](const char (&key)[N])
{
return (*this)[std::string{key}];
}

private:
std::reference_wrapper<JsonObject> _object;

friend struct std::formatter<cppjson::Object::ObjectProxy>;
};

class ConstObjectProxy
{
public:
explicit ConstObjectProxy(const JsonObject& object) : _object(std::ref(object)) {}
template <typename T>
explicit(false) operator const T&() const
{
return this->_object.get().As<T>();
}

ConstObjectProxy operator[](const std::string& key) const;

private:
std::reference_wrapper<const JsonObject> _object;

friend struct std::formatter<cppjson::Object::ConstObjectProxy>;
};

ObjectProxy operator[](const std::string& key) { return ObjectProxy{this->_nodes[key]}; }

ConstObjectProxy operator[](const std::string& key) const
{
if (!this->_nodes.contains(key)) throw std::logic_error("Invalid key" + key);

return ConstObjectProxy{this->_nodes.at(key)};
}

private:
std::unordered_map<std::string, JsonObject> _nodes{};

friend struct std::formatter<cppjson::JsonObject>;
friend struct std::formatter<cppjson::Object>;
};

class Array
{
public:
explicit Array() = default;
~Array() = default;

Object::ObjectProxy operator[]() { return Object::ObjectProxy{this->_objects.emplace_back()}; }

Object::ObjectProxy EmplaceBack(const auto& object)
{
if constexpr (std::same_as<decltype(object), std::nullptr_t>) return Object::ObjectProxy{this->_objects.emplace_back()};
else
{
auto& emplaced = this->_objects.emplace_back();
emplaced.As<std::remove_cvref_t<decltype(object)>>() = object;
return Object::ObjectProxy{emplaced};
}
}

Object::ObjectProxy operator[](const std::size_t index)
{
if (index >= this->_objects.size()) throw std::logic_error("Out of bound");
return Object::ObjectProxy{this->_objects.at(index)};
}

Object::ConstObjectProxy operator[](const std::size_t index) const
{
if (index >= this->_objects.size()) throw std::logic_error("Out of bound");
return Object::ConstObjectProxy{this->_objects.at(index)};
}

private:
std::vector<JsonObject> _objects{};

friend struct std::formatter<cppjson::JsonObject>;
friend struct std::formatter<cppjson::Array>;
};
} // namespace cppjson
4 changes: 0 additions & 4 deletions cppjson/src/cppjson.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +0,0 @@
#include <cppjson/cppjson.hpp>
#include <print>

void cppjson::hello_world() { std::println("Hewwo wowld"); }
Loading