cppfig 0.1.0
Modern C++20 compile-time type-safe configuration library
Loading...
Searching...
No Matches
serializer.h
Go to the documentation of this file.
1#pragma once
2
3#include <concepts>
4#include <fstream>
5#include <istream>
6#include <string>
7
8#include "cppfig/status.h"
9#include "cppfig/value.h"
10
11namespace cppfig {
12
18template <typename S>
19concept Serializer = requires(const Value& data, std::istream& is) {
20 typename S::data_type;
21 { S::Parse(is) } -> std::same_as<StatusOr<Value>>;
22 { S::Stringify(data) } -> std::convertible_to<std::string>;
23};
24
26template <Serializer S>
27auto ReadFile(const std::string& path) -> StatusOr<Value>
28{
29 std::ifstream file(path);
30 if (!file.is_open()) {
31 return NotFoundError("Could not open file: " + path);
32 }
33 return S::Parse(file);
34}
35
37template <Serializer S>
38auto WriteFile(const std::string& path, const Value& data) -> Status
39{
40 std::ofstream file(path);
41 if (!file.is_open()) {
42 return InternalError("Could not write to file: " + path);
43 }
44 file << S::Stringify(data);
45 if (file.fail()) {
46 return InternalError("Failed to write to file: " + path);
47 }
48 return OkStatus();
49}
50
51} // namespace cppfig
A value-or-error type, similar to std::expected (C++23).
Definition status.h:100
A lightweight status object carrying an error code and message.
Definition status.h:23
A self-contained, recursive value type for configuration data.
Definition value.h:26
Concept for serializer types.
Definition serializer.h:19
C++20 compile-time type-safe configuration library.
Definition conf.h:13
auto NotFoundError(std::string message) -> Status
Returns a NotFound error status.
Definition status.h:55
auto ReadFile(const std::string &path) -> StatusOr< Value >
Helper to read a file into a Value tree via a serializer.
Definition serializer.h:27
auto InternalError(std::string message) -> Status
Returns an Internal error status.
Definition status.h:67
auto OkStatus() -> Status
Returns an OK status.
Definition status.h:52
auto WriteFile(const std::string &path, const Value &data) -> Status
Helper to write a Value tree to a file via a serializer.
Definition serializer.h:38