Overview / Data & formats

config

Loads configuration from many sources (TOML v1.0.0, INI, strict and lenient JSON, environment, command line), merges them in layers once, and then reads without searching.

Always compiled: part of the core build.Include #include <ethereal/cpp/config/config_inc.hpp>C layer

config_inc.hpp

#include <ethereal/cpp/config/config_inc.hpp>

bind.hpp

#include <ethereal/cpp/config/bind.hpp>

Binding of a configuration to a struct.

This is the recommended access path, and the only one with zero cost. The spec: bind to a struct once at load, then read plain struct fields with zero lookup cost, and make that the path of least resistance in the documentation and examples.

Everything else in the module (the handle, the binary search, the arena) exists to make dynamic reads bearable. Binding makes them unnecessary: after it, a reader reads a struct field, with no lookup and no hash.

struct SServerConfig { ETL_UINT16 uPort; std::string_view sAddress; Time::SDuration Timeout; bool bTls; };

ETL_CONFIG_BIND( SServerConfig, ETL_FIELD( uPort, "server.port", ETL_UINT16, 8080 ), ETL_FIELD_TEXT( sAddress, "server.bind", std::string_view, "0.0.0.0" ), ETL_FIELD_TEXT( Timeout, "server.timeout", Time::SDuration, "30s" ), ETL_FIELD( bTls, "server.tls", bool, false ) );

SServerConfig Cfg; Conf.Bind( &Cfg ); // once, at load ... Cfg.uPort ... // from here on, only fields

The table is static and binding is a linear walk over it. There is no code generation and no registration at startup, and the macro hides nothing that cannot be written by hand. It saves the repeated 'offsetof' and the chance of a wrong field type.

struct

SBindField

Ethereal::Config#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SBindField   final
{
    /// @brief  Key path in the document.
    const char *    pPath = nullptr;

    /// @brief  Offset of the field in the struct.
    std::size_t        uOffset = 0u;

    /// @brief  Type expected in the document.
    EValueType        eType = EValueType::eNone;

    /// @brief  Size of the field, in bytes. It is what stops a `uint16_t` from taking 70000.
    ETL_UINT8        uByteSize = 0u;

    /// @brief  The field is signed. Only counts for integers.
    bool            bSigned = false;

    /// @brief  The field is required: without it the binding fails instead of using the default.
    bool            bRequired = false;

    /// @brief  The field has a default.
    bool            bDefault = false;

    /// @brief  Integer or boolean default.
    ETL_INT64        iDefault = 0;

    /// @brief  Real default.
    ETL_DOUBLE        dDefault = 0.0;

    /// @brief  Default for text, and for a duration, which is read from this text.
    const char *    pDefault = nullptr;
};

A bound field: where it is in the struct, and where its value comes from.

struct

SBindTable

Ethereal::Config#
C++
ETL_END_INTENDED_PADDING


/// @brief  The binding table of a struct.
///
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SBindTable   final
{
    /// @brief  The fields.
    const SBindField *    pFields = nullptr;

    /// @brief  Number of fields.
    std::size_t            uCount = 0u;

    /// @brief  Name of the struct, for messages.
    const char *        pStructName = nullptr;
};
struct

SFieldType

Ethereal::Config#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Factories used by the macros
///=============================================================================


/// @brief  Finds the EValueType of a field type, at compile time.
///
template< typename T >
struct   SFieldType
{
    static_assert( std::is_integral< T >::value || std::is_enum< T >::value,
                   "A bound field must be an integer, a boolean, a real, "
                   "std::string_view or Time::SDuration." );

    /// @brief  Integers and enums are read as eInt.
    static constexpr EValueType    kType = EValueType::eInt;
};
struct

SFieldType

Ethereal::Config#
C++
template<> struct SFieldType< bool >                { static constexpr EValueType kType = EValueType::eBool; };
struct

SFieldType

Ethereal::Config#
C++
template<> struct SFieldType< float >                { static constexpr EValueType kType = EValueType::eDouble; };
struct

SFieldType

Ethereal::Config#
C++
template<> struct SFieldType< double >            { static constexpr EValueType kType = EValueType::eDouble; };
struct

SFieldType

Ethereal::Config#
C++
template<> struct SFieldType< std::string_view >    { static constexpr EValueType kType = EValueType::eString; };
struct

SFieldType

Ethereal::Config#
C++
template<> struct SFieldType< Time::SDuration >    { static constexpr EValueType kType = EValueType::eString; };

A duration is read from a text ("30s"), so its type in the document is text.

function

FieldOf

Ethereal::Config#
template< typename T > inline SBindField FieldOf( const char * const pPath, const std::size_t uOffset, const ETL_INT64 iDefault ) noexcept

An integer or boolean field.

pPath
Key path.
uOffset
Offset of the field in the struct.
iDefault
Default value. Zero means no default.
The field description.
function

RealFieldOf

Ethereal::Config#
template< typename T > inline SBindField RealFieldOf( const char * const pPath, const std::size_t uOffset, const ETL_DOUBLE dDefault ) noexcept

A real field.

function

TextFieldOf

Ethereal::Config#
template< typename T > inline SBindField TextFieldOf( const char * const pPath, const std::size_t uOffset, const char * const pDefault ) noexcept

A text field, or a duration read from text.

struct

SBindReport

Ethereal::Config#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SBindReport   final
{
    /// @brief  All problems found.
    std::vector< SConfigError >        Problems;

    /// @brief  Fields filled from the document.
    std::size_t        uBound = 0u;

    /// @brief  Fields filled with their default.
    std::size_t        uDefaulted = 0u;


    /// @brief  true when there were no problems.
    ///
    ETL_API_NOIGN    bool Ok() const ETL_NOEXCEPT    { return Problems.empty(); }
};

Result of a binding. Lists every problem, not only the first.

function

Require

Ethereal::Config#
inline SBindField Require( SBindField F ) noexcept

Returns F marked as required. Used by ETL_REQUIRED.

config.hpp

#include <ethereal/cpp/config/config.hpp>

Layered configuration with atomic hot reload.

Layers of TOML, INI, JSON, environment and command line are merged once into a flat resolved document. Reads never walk the layers, and a reload swaps the whole document through an atomic pointer.

Merge rule, by type, with no hidden exceptions. The spec asks for it to be stated, since array merge ambiguity is the most common source of config surprise:

  • Scalars replace. The layer with the highest priority wins, whole.
  • Tables merge, key by key, recursively. A layer that only sets 'server.port' does not erase the 'server.bind' of the layer below.
  • Arrays replace by default. An array is a list someone wrote whole, and appending by default would make removing an element in an upper layer impossible. Appending is turned on per layer, where it shows in the code. When the types do not match, the highest priority wins. The origin of the winning value is recorded and Origin reports it.

A snapshot is what keeps a document alive under its readers. The spec: snapshot handles keep the old document alive for readers in flight. One thread is in the middle of a loop reading handles, another just reloaded and wants to discard the old document. Discarding it would make the first read dead memory. A lock on the reader side is forbidden by the spec ("no reader-side lock"): it would put every thread on the same cache line. So a reader in a loop takes a snapshot, the snapshot holds a reference, and the old document dies with its last snapshot.

class

CConfigSnapshot

Ethereal::Config#

A document held by a reference count. While it exists, the document lives.

class CConfigSnapshot final

Copying a snapshot copies a shared_ptr, which is cheap and thread safe. Reading through a snapshot never touches the atomic pointer of CConfig, so a read loop pays nothing for it.

constructor

CConfigSnapshot

#
CConfigSnapshot() = default;

Empty snapshot.

constructor

CConfigSnapshot

#
explicit CConfigSnapshot( std::shared_ptr< const CDocument > spDoc ) noexcept : m_spDoc( std::move( spDoc ) )

Snapshot of spDoc.

function

IsValid

#
bool IsValid() const noexcept

true when the snapshot holds a document.

function

Doc

#
const CDocument * Doc() const noexcept

The held document.

function

Resolve

#
SConfigHandle Resolve( std::string_view sPath ) const noexcept;

Resolves a path into a handle of this snapshot.

function

GetBool

#
EStatus GetBool( SConfigHandle H, bool * pOut ) const noexcept;

Reads a boolean through a handle.

function

GetInt64

#
EStatus GetInt64( SConfigHandle H, ETL_INT64 * pOut ) const noexcept;

Reads an integer through a handle.

function

GetDouble

#
EStatus GetDouble( SConfigHandle H, ETL_DOUBLE * pOut ) const noexcept;

Reads a real through a handle. An integer is accepted.

function

GetString

#
EStatus GetString( SConfigHandle H, std::string_view * pOut ) const noexcept;

Reads a text through a handle. The view points into the document.

class

CConfig

Ethereal::Config#
class CConfig final
constructor

CConfig

#
CConfig() noexcept;

Constructor. Call Init before use.

function

Init

#
EStatus Init( const SConfigParams & Params ) noexcept;

Sets the parameters and empties the object. eNotLicensed when the library is not licensed.

function

AddLayer

#
EStatus AddLayer( EFormat eFormat, const void * pData, std::size_t uBytes, std::string_view sOrigin, ETL_UINT32 uPriority, SConfigError * pError = nullptr );

A layer from text already in memory.

The text is copied once into the layer, and never again. The spec wants zero copy parsing, and from there on it is: every name and every value is a view over this copy. Copying on entry lets the caller discard its buffer right away.

eFormat
Format of the text.
pData
The text.
uBytes
Size of the text.
sOrigin
Name shown by Origin.
uPriority
Priority of the layer.
pError
Receives the failure. May be null.
eOk or the failure status.
function

AddFileLayer

#
EStatus AddFileLayer( std::string_view sPath, EFormat eFormat, ETL_UINT32 uPriority, bool bRequired, SConfigError * pError = nullptr );

A layer from a file.

Only file layers are reloadable, and they are what the watch watches.

sPath
File path.
eFormat
Format of the file.
uPriority
Priority of the layer.
bRequired
false lets a missing file pass.
pError
Receives the failure. May be null.
eOk or the failure status.
function

AddEnvLayer

#
EStatus AddEnvLayer( std::string_view sPrefix, ETL_UINT32 uPriority, SConfigError * pError = nullptr );

A layer of environment variables.

The name rule, documented here because the spec asks for it: the prefix is removed, the rest goes to lowercase, a _ becomes . and a __ becomes a literal _. With the prefix ETL_, ETL_SERVER_PORT gives server.port and ETL_LOG__FILE gives log_file.

sPrefix
Prefix of the variables.
uPriority
Priority of the layer.
pError
Receives the failure. May be null.
eOk or the failure status.
function

AddDirectoryLayer

#
EStatus AddDirectoryLayer( std::string_view sFolder, std::string_view sPattern, EFormat eFormat, ETL_UINT32 uPriority, SConfigError * pError = nullptr );

One layer per file of a directory that matches sPattern.

Files are added in alphabetical order of their names, each with the given priority plus its position. That makes a conf.d with 10-base.toml and 20-local.toml behave as everyone expects, without depending on the order the file system returned them.

sFolder
Directory.
sPattern
Name pattern, with *.
eFormat
Format of the files.
uPriority
Base priority.
pError
Receives the failure. May be null.
eOk or the failure status.
function

AddCommandLineLayer

#
EStatus AddCommandLineLayer( int iArgc, const char * const * pArgv, std::string_view sPrefix, ETL_UINT32 uPriority, SConfigError * pError = nullptr );

A layer from the command line.

Accepts --key.path=value, --key.path value and --flag (which gives true). A lone -- stops the reading.

The spec says "through the Console arg parser". Not here: section 2 of the conventions forbids a module from including the header of another to get functionality, and Config declares no link time dependency. Whoever wants the full semantics of CArgParser builds the layer with AddLayer from what it produced.

iArgc
Argument count.
pArgv
Arguments.
sPrefix
Prefix of the options to take.
uPriority
Priority of the layer.
pError
Receives the failure. May be null.
eOk or the failure status.
function

AppendArraysOnLastLayer

#
EStatus AppendArraysOnLastLayer() noexcept;

Makes the last layer append its arrays instead of replacing them.

Applies to the last layer added. Explicit on purpose, see the merge rule at the top of the file.

function

Resolve

#
EStatus Resolve( SConfigError * pError = nullptr );

Merges everything, interpolates, validates and publishes the document.

All the work happens here, and only once. After this a read does not merge, interpolate or validate anything.

If it fails, the document that was live stays live. See Reload: same discipline, the one the spec requires.

pError
Receives the first failure. May be null.
eOk or the failure status.
function

SetSchema

#
EStatus SetSchema( const CSchema * pSchema ) noexcept;

Sets the schema. Must be called before Resolve.

The CSchema is not copied: it must outlive this object.

function

Problems

#
std::vector< SConfigError > Problems() const

Problems found by the last Resolve or Reload. All of them, not only the first.

Returns a copy, taken under the build lock. Until 11-10-2026 it returned a reference to the list, and the watch thread clears and refills that list on every reload: a caller walking it could read a list being destroyed.

function

Resolve

#
SConfigHandle Resolve( std::string_view sPath ) const noexcept;

Resolves a path into a handle of the live document.

function

Has

#
bool Has( std::string_view sPath ) const noexcept;

true when the path exists.

function

GetBool

#
EStatus GetBool( std::string_view sPath, bool * pOut ) const noexcept;

Reads a boolean.

function

GetInt64

#
EStatus GetInt64( std::string_view sPath, ETL_INT64 * pOut ) const noexcept;

Reads an integer.

function

GetDouble

#
EStatus GetDouble( std::string_view sPath, ETL_DOUBLE * pOut ) const noexcept;

Reads a real. An integer is accepted.

function

GetString

#
EStatus GetString( std::string_view sPath, std::string_view * pOut ) const noexcept;

Reads a text. The view points into the document.

function

GetDuration

#
EStatus GetDuration( std::string_view sPath, Time::SDuration * pOut ) const noexcept;

Reads a duration written as text, like "30s".

function

GetBytes

#
EStatus GetBytes( std::string_view sPath, ETL_UINT64 * pOut ) const noexcept;

Reads a size, written as text ("512MB") or as an integer.

function

GetArray

#
EStatus GetArray( std::string_view sPath, SConfigArray * pOut ) const noexcept;

A view over an array.

function

GetTable

#
EStatus GetTable( std::string_view sPath, SConfigTable * pOut ) const noexcept;

A view over a table.

function

GetBoolOrDefault

#
bool GetBoolOrDefault( std::string_view sPath, bool bDefault ) const noexcept;

Reads a boolean, or returns bDefault.

function

GetInt64OrDefault

#
ETL_INT64 GetInt64OrDefault( std::string_view sPath, ETL_INT64 iDefault ) const noexcept;

Reads an integer, or returns iDefault.

function

GetDoubleOrDefault

#
ETL_DOUBLE GetDoubleOrDefault( std::string_view sPath, ETL_DOUBLE dDefault ) const noexcept;

Reads a real, or returns dDefault.

function

GetStringOrDefault

#
std::string_view GetStringOrDefault( std::string_view sPath, std::string_view sDefault ) const noexcept;

Reads a text, or returns sDefault.

function

GetDurationOrDefault

#
Time::SDuration GetDurationOrDefault( std::string_view sPath, Time::SDuration Default ) const noexcept;

Reads a duration, or returns Default.

function

GetBytesOrDefault

#
ETL_UINT64 GetBytesOrDefault( std::string_view sPath, ETL_UINT64 uDefault ) const noexcept;

Reads a size, or returns uDefault.

function

GetBool

#
EStatus GetBool( SConfigHandle H, bool * pOut ) const noexcept;

Reads a boolean through a handle.

function

GetInt64

#
EStatus GetInt64( SConfigHandle H, ETL_INT64 * pOut ) const noexcept;

Reads an integer through a handle.

function

GetDouble

#
EStatus GetDouble( SConfigHandle H, ETL_DOUBLE * pOut ) const noexcept;

Reads a real through a handle. An integer is accepted.

function

GetString

#
EStatus GetString( SConfigHandle H, std::string_view * pOut ) const noexcept;

Reads a text through a handle.

function

Origin

#
EStatus Origin( std::string_view sPath, SOrigin * pOut ) const noexcept;

Layer, file, line and column that gave the winning value.

function

Snapshot

#
CConfigSnapshot Snapshot() const noexcept;

A snapshot of the live document. This is how to read in a loop.

function

Reload

#
EStatus Reload( SConfigError * pError = nullptr );

Reads the file layers again and swaps the document if all goes well.

The spec: reload is atomic or it does not happen. Parse and validate the new document completely, and only then swap. A failed reload keeps the old document live and reports the error. Never leave the application with a half applied configuration.

That is exactly what this does, and the bench runs the bad case: a broken file in the middle of ten thousand reloads with readers reading.

It can be called from several threads, and while the watch runs. Reloads, Resolve and the calls that add layers run one at a time.

pError
Receives the failure. May be null.
eOk, or eReloadFailed with the old document still live.
function

EnableWatch

#
EStatus EnableWatch( void * pCtx, void ( * pOnChange )( void * pCtx, const CConfig & ) );

Starts watching the files of the layers.

The debounce window is SConfigParams::uDebounceMs. It exists because an editor saves a file in several operations.

pCtx
Context passed to the callback.
pOnChange
Called after the swap, with the new document already live.
eOk, eNotInitialized, eUnsupported when no layer came from a file, or eNotLicensed.
Whoever bound a struct binds it again here. A std::string_view field bound before the reload points to the old document. See bind.hpp.
function

DisableWatch

#
void DisableWatch() noexcept;

Stops the file watch and waits for its thread.

function

IsWatching

#
bool IsWatching() const noexcept;

true while the file watch is running.

function

Dump

#
std::string Dump( EFormat eFormat = EFormat::eToml, bool bMaskSecrets = true ) const;

Writes the resolved view as TOML or INI.

Keys marked as secret by the schema come out as a fixed marker. The default is to mask because "a config dump that leaks a database password into a log file is a security incident", and the default is what happens to whoever did not read this.

eFormat
eToml or eIni.
bMaskSecrets
true by default, on purpose.
The text.
function

DumpLayer

#
std::string DumpLayer( std::size_t uLayer, bool bMaskSecrets = true ) const;

Writes a single layer as it is, in its own format.

The source text comes out unchanged, which keeps comments and key order for free.

Secrets are not masked: the raw text has no value marks, and bMaskSecrets is ignored. A raw layer does not go into a log.
function

SaveToFile

#
EStatus SaveToFile( std::string_view sPath, EFormat eFormat = EFormat::eToml, bool bMaskSecrets = true ) const;

Writes the resolved view to a file. See Dump.

function

Bind

#
template< typename T > EStatus Bind( T * const pOut, SBindReport * const pReport = nullptr ) const

Fills pOut from the binding table of T.

After this, read fields. See the notes in bind.hpp.

function

BindRaw

#
EStatus BindRaw( const SBindTable & Table, void * pOut, SBindReport * pReport ) const;

Fills pOut from an explicit binding table.

function

Stats

#
SConfigStats Stats() const noexcept;

Counters of the live document and of the reloads.

function

LayerCount

#
std::size_t LayerCount() const noexcept

Number of layers added.

Read under the writer side lock: AddLayer, called from another thread, may be growing the list.

function

Clear

#
void Clear() noexcept;

Drops the layers and the document. The object is as Init left it.

config_types.hpp

#include <ethereal/cpp/config/config_types.hpp>

Shared vocabulary of the Config module.

Status codes, formats, value types, the origin of a value, the error given to whoever wrote the file, the read handle, the array and table views, the start parameters and the counters.

The spec rule that shapes the whole module: a config library that does a string hash lookup per read gets worked around. So the design answers each line of the performance mandate:

  • Values live in a flat array, not in a tree of nodes allocated one by one. The tree is in the indices: each node knows where its children start and how many there are, so walking a table is moving forward in a vector.
  • Keys live in a separate sorted index, built once at the end of Resolve. A lookup is a binary search by hash, not a walk through nested maps.
  • A reader in a loop does not look anything up. It resolves the path once into a handle, and a read through the handle is an index into a vector.
  • All text lives in one arena, the document's. A text value is an offset and a length inside it, so reading does not allocate.
  • The resolved document is immutable. That is what makes a hot reload a pointer swap instead of a lock on the read path.
enum

EStatus

Ethereal::Config#
C++
enum class   EStatus : ETL_UINT8
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  Init has not run, or Resolve has not run yet.
    eNotInitialized,

    /// @brief  An allocation failed.
    eOutOfMemory,

    /// @brief  A parameter is invalid.
    eInvalidArgument,

    /// @brief  The key does not exist. Distinct from eTypeMismatch on purpose.
    ///
    /// @details  The spec asks for it. A missing key is a mistake of whoever
    ///            wrote the configuration. A wrong type is a mistake made somewhere
    ///            else, and the message given to that person is not the same.
    eMissingKey,

    /// @brief  The key exists with another type. The error names both.
    eTypeMismatch,

    /// @brief  The text is not in the format it was said to be.
    eParseError,

    /// @brief  The file did not open, and the layer was required.
    eFileNotFound,

    /// @brief  The value did not pass the schema.
    eValidationFailed,

    /// @brief  `${a}` refers to `${b}`, which refers to `${a}`.
    eInterpolationCycle,

    /// @brief  A key the schema does not know, in strict mode.
    eUnknownKey,

    /// @brief  Nothing more fits in what was reserved at start.
    eOverflow,

    /// @brief  File watching is not available on this platform.
    eUnsupported,

    /// @brief  The reload failed and the old document is still live.
    eReloadFailed,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///          has ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed,

    /// @brief  Old British spelling of eNotInitialized, same value. Will be removed.
    eNotInitialised [[deprecated( "use EStatus::eNotInitialized" )]] = eNotInitialized
};

Result of a Config operation.

function

StatusName

Ethereal::Config#
const char * StatusName( EStatus eStatus ) noexcept;

Name of a status, for messages. Never returns null.

enum

EFormat

Ethereal::Config#
C++
enum class   EFormat : ETL_UINT8
{
    /// @brief  TOML v1.0.0, the primary format.
    eToml = 0,

    /// @brief  INI with sections, for compatibility.
    eIni,

    /// @brief  Strict JSON: no comments, no trailing comma.
    eJsonStrict,

    /// @brief  Lenient JSON: accepts `//`, `/* */` and a trailing comma.
    eJsonLenient,

    /// @brief  Environment variables. The source is the variable list, not text.
    eEnv,

    /// @brief  Command line. The source is `argv`.
    eCommandLine
};

Format of a layer.

function

FormatFromExtension

Ethereal::Config#
bool FormatFromExtension( std::string_view sPath, EFormat * pOut ) noexcept;

Guesses the format from the file extension.

A convenience, not the normal path. The spec selects the format explicitly: whoever calls AddFileLayer passes it. This exists for a caller that has a path and nothing else.

sPath
File path.
pOut
Receives the format.
true when recognized: .toml, .ini, .cfg, .conf and .json.
enum

EValueType

Ethereal::Config#
C++
enum class   EValueType : ETL_UINT8
{
    /// @brief  No value.
    eNone = 0,

    /// @brief  Boolean.
    eBool,

    /// @brief  64 bit signed integer.
    eInt,

    /// @brief  Double.
    eDouble,

    /// @brief  Text.
    eString,

    /// @brief  TOML date and time, kept as the original text.
    ///
    /// @details  The TOML forms (with offset, local, date only, time only) do
    ///            not all fit a numeric type without inventing an offset the file
    ///            did not give. The text is kept as is, validated in shape, and a
    ///            caller that wants an instant converts it with the Time module.
    eDateTime,

    /// @brief  Array.
    eArray,

    /// @brief  Table.
    eTable
};

Type of a value in the document.

function

TypeName

Ethereal::Config#
const char * TypeName( EValueType eType ) noexcept;

Name of a value type, for error messages. Never returns null.

struct

SOrigin

Ethereal::Config#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SOrigin   final
{
    /// @brief  Name given to the layer: the file path, or `"env"`.
    std::string_view    sOrigin;

    /// @brief  Priority of the winning layer.
    ETL_UINT32            uPriority = 0u;

    /// @brief  Line, starting at 1. Zero when the source has no lines (environment).
    ETL_UINT32            uLine = 0u;

    /// @brief  Column, starting at 1. Zero when it does not apply.
    ETL_UINT32            uColumn = 0u;
};

Layer, file, line and column that gave the winning value.

Meant for a person who is confused. A configuration with four layers has four possible places for each key, and "why is this 8080 if I wrote 9090" is the question people ask. Without this, the answer is reading the four files by hand.

Cheap to keep: four numbers per value, and the origin text is shared by all values of the same layer.

struct

SConfigError

Ethereal::Config#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Errors
///=============================================================================


/// @brief  A failure with a location. The line matters more than the message.
///
/// @details  The spec asks for file, line, column, the offending value and the
///            expected shape. A config file is edited by hand, so mistakes in it
///            are routine, and an error that does not say where makes the person
///            hunt for the problem.
///
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SConfigError   final
{
    /// @brief  What went wrong.
    EStatus            eStatus = EStatus::eOk;

    /// @brief  The file, or the name given to the layer.
    std::string        sFile;

    /// @brief  Line, starting at 1. Zero when the failure is not about content.
    std::size_t        uLine = 0u;

    /// @brief  Column, starting at 1.
    std::size_t        uColumn = 0u;

    /// @brief  Key path, when the failure is about a key.
    std::string        sPath;

    /// @brief  The offending value, as written.
    std::string        sValue;

    /// @brief  What was expected. For a wrong type, names both types.
    std::string        sMessage;


    /// @brief  One line of text with everything, ready to print.
    ///
    ETL_API_NOIGN    ETL_API        std::string ToString() const;
};
struct

SConfigHandle

Ethereal::Config#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Handle, the fast read path
///=============================================================================


/// @brief  A resolved path. Reading through it does not look anything up.
///
/// @details  The spec: where dynamic lookup is needed, resolve the key path to
///            an opaque handle once, then read through the handle.
///
///            Inside it is the index of the value in the flat array, plus one.
///            Zero is reserved for "not resolved", so an uninitialized handle
///            does not point to the first value of the document. That was a
///            real defect in another module of this tree.
///
/// @warning  A handle belongs to the document that gave it. After a hot reload
///            it points to the old document, which is why a reader in a loop
///            takes a CConfigSnapshot and resolves the handles against it.
///
/// The padding of this type is intended (alignment). See ETL_BEGIN_INTENDED_PADDING.
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SConfigHandle   final
{
    /// @brief  Index of the value plus one. Zero is no handle.
    ETL_UINT32    uIndex = 0u;


    /// @brief  true when the handle points to a value.
    ///
    ETL_API_NOIGN    bool IsValid() const ETL_NOEXCEPT        { return uIndex != 0u; }

    /// @brief  The invalid handle.
    ///
    ETL_API_NOIGN    static SConfigHandle Invalid() ETL_NOEXCEPT    { return SConfigHandle{}; }
};
struct

SConfigArray

Ethereal::Config#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SConfigArray   final
{
    /// @brief  Document that owns the array.
    const CDocument *    pDoc = nullptr;

    /// @brief  Index of the first element in the flat array.
    ETL_UINT32            uFirst = 0u;

    /// @brief  Number of elements.
    ETL_UINT32            uCount = 0u;


    /// @brief  Number of elements.
    ///
    ETL_API_NOIGN    std::size_t Size() const ETL_NOEXCEPT    { return uCount; }

    /// @brief  true when the array has no elements.
    ///
    ETL_API_NOIGN    bool Empty() const ETL_NOEXCEPT            { return uCount == 0u; }

    /// @brief  Element @p i, as a handle. Out of range gives an invalid handle.
    ///
    ETL_API_NOIGN    ETL_API        SConfigHandle At( std::size_t i ) const ETL_NOEXCEPT;
};

A view over an array of the document. Copies nothing.

struct

SConfigTable

Ethereal::Config#
C++
ETL_END_INTENDED_PADDING


/// @brief  A view over a table of the document. Copies nothing.
///
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SConfigTable   final
{
    /// @brief  Document that owns the table.
    const CDocument *    pDoc = nullptr;

    /// @brief  Index of the first key in the flat array.
    ETL_UINT32            uFirst = 0u;

    /// @brief  Number of keys.
    ETL_UINT32            uCount = 0u;


    /// @brief  Number of keys.
    ///
    ETL_API_NOIGN    std::size_t Size() const ETL_NOEXCEPT    { return uCount; }

    /// @brief  true when the table has no keys.
    ///
    ETL_API_NOIGN    bool Empty() const ETL_NOEXCEPT            { return uCount == 0u; }

    /// @brief  Name of key @p i, without the full path.
    ///
    ETL_API_NOIGN    ETL_API        std::string_view KeyAt( std::size_t i ) const ETL_NOEXCEPT;

    /// @brief  Value of key @p i, as a handle.
    ///
    ETL_API_NOIGN    ETL_API        SConfigHandle At( std::size_t i ) const ETL_NOEXCEPT;
};
struct

SConfigParams

Ethereal::Config#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Start parameters
///=============================================================================


/// @brief  What is reserved and which rules apply. Everything has a default.
///
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SConfigParams   final
{
    /// @brief  Size of this structure, for versioning.
    ETL_UINT32        uStructSize = static_cast< ETL_UINT32 >( sizeof( SConfigParams ) );

    /// @brief  Values that fit before the document grows.
    std::size_t        uInitialValues = 256u;

    /// @brief  Text bytes that fit in the arena before it grows.
    std::size_t        uInitialTextBytes = 8192u;

    /// @brief  Strict mode: a key the schema does not know is an error.
    ///
    /// @details  The spec turns it on by default in strict mode: a typo in a
    ///            config key that silently does nothing is the worst failure
    ///            mode this module can have.
    ///
    ///            Only has effect with a schema. Without one there is no way to
    ///            know what is unknown.
    bool            bStrict = true;

    /// @brief  Keeps comments and spacing, to write back without losing them.
    ///
    /// @details  The spec makes trivia retention an opt-in parse flag, since it
    ///            costs memory and is not needed for read only use.
    bool            bKeepTrivia = false;

    /// @brief  Resolves `${...}` during Resolve. See CConfig::Resolve.
    bool            bInterpolate = true;

    /// @brief  Debounce window of the file watch, in milliseconds.
    ///
    /// @details  An editor saves a file in several operations. Without this
    ///            window one Vim save gives three reloads, one of them over a
    ///            truncated file.
    ETL_UINT32        uDebounceMs = 50u;
};
struct

SConfigStats

Ethereal::Config#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Counters
///=============================================================================


/// @brief  What is counted, so it can be checked.
///
struct   ETL_STRUCT_ALIGN   SConfigStats   final
{
    /// @brief  Allocations made while parsing. The spec asks for the count.
    ///
    /// @details  The spec: allocations during parse are bounded, one arena,
    ///            count reported.
    ETL_UINT64        uParseAllocations = 0;

    /// @brief  Bytes in the document arena.
    ETL_UINT64        uArenaBytes = 0;

    /// @brief  Values in the document.
    ETL_UINT64        uValues = 0;

    /// @brief  Keys in the path index.
    ETL_UINT64        uIndexedKeys = 0;

    /// @brief  Layers merged.
    ETL_UINT64        uLayers = 0;

    /// @brief  Times the document was swapped by a successful reload.
    ETL_UINT64        uReloads = 0;

    /// @brief  Reloads that failed and left the old document live.
    ETL_UINT64        uFailedReloads = 0;

    /// @brief  Old documents still alive because of snapshots.
    ETL_UINT64        uRetainedDocuments = 0;
};

document.hpp

#include <ethereal/cpp/config/document.hpp>

The flat, immutable document of the Config module.

A value is sixteen bytes and none of them is a pointer. A document made of nodes allocated one by one cannot be copied, cannot be swapped through an atomic, and walking one of its tables chases pointers over unrelated cache lines.

With indices the whole document is three vectors (values, keys and text), which gives three things the spec asks for:

  • Walking a table is moving forward in a vector.
  • The resolved document is immutable and copyable, which makes the hot reload a pointer swap.
  • A text value is an offset in the arena, so reading does not allocate.

Key lookup is a binary search over the index sorted by hash, about log2(N) reads of eight contiguous bytes, followed by a comparison of the path text. Two keys with the same hash are rare but unavoidable, and returning the wrong value on a collision is worse than being slow.

A perfect hash, the first alternative in the spec, was not used. Building it costs time in Resolve and one more table in memory, and the binary search over a few hundred keys is well inside the 100 ns target. It is noted as a possible improvement, with the measurement beside it.

struct

SValue

Ethereal::Config#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SValue   final
{
    /// @brief  Type of the value.
    EValueType    eType = EValueType::eNone;

    /// @brief  Index in the origin table of the document.
    ETL_UINT8    uOrigin = 0u;

    /// @brief  Marked as secret by the schema. See CConfig::Dump.
    bool        bSecret = false;

    /// @brief  Reserved.
    ETL_UINT8    uReserved = 0u;

    /// @brief  Payload, by type.
    ///
    /// @details  A text, a date and a time are an (offset, length) pair in the
    ///            arena. An array and a table are a (first child, count) pair in
    ///            the value vector. All of them fit the same eight bytes, so they
    ///            share them.
    union
    {
        bool        bBool;
        ETL_INT64    iInt;
        ETL_DOUBLE    dDouble;

        struct { ETL_UINT32 uOffset, uSize; }        Text;

        struct { ETL_UINT32 uFirst, uCount; }    Children;
    };

    /// @brief  Name of this key inside its parent. Empty at the root and in array elements.
    ETL_UINT32    uNameOffset = 0u;

    /// @brief  Length of the name.
    ETL_UINT32    uNameSize = 0u;


    /// @brief  Default constructor. Zeroes the payload.
    ///
    SValue() ETL_NOEXCEPT : iInt( 0 ) {}
};

A value in the flat array. Sixteen bytes, the tree is in the indices.

struct

SKeyIndex

Ethereal::Config#
C++
ETL_END_INTENDED_PADDING


/// @brief  An entry of the path index. Twelve bytes, kept sorted.
///
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SKeyIndex   final
{
    /// @brief  Hash of the full path. The binary search runs on it.
    ETL_UINT64    uHash = 0u;

    /// @brief  Offset of the path text in the arena.
    ETL_UINT32    uPathOffset = 0u;

    /// @brief  Length of the path text.
    ETL_UINT32    uPathSize = 0u;

    /// @brief  Index of the value in the flat array.
    ETL_UINT32    uValue = 0u;
};
class

CDocument

Ethereal::Config#
class CDocument final
constructor

CDocument

#
CDocument() = default;

Default constructor. The builder fills the document.

function

Find

#
SConfigHandle Find( std::string_view sPath ) const noexcept;

Resolves a path into a handle. Once, then read through the handle.

Binary search by hash, plus one path comparison. This is the slow path of the spec (100 ns target), measured in the README.

sPath
Full key path.
The handle, or an invalid handle when the key does not exist.
function

Get

#
const SValue * Get( const SConfigHandle H ) const noexcept

The value of a handle. Null when the handle is not valid.

function

Text

#
std::string_view Text( const ETL_UINT32 uOffset, const ETL_UINT32 uSize ) const noexcept

A text of the arena. Returns a view, not a copy.

function

Origin

#
SOrigin Origin( SConfigHandle H ) const noexcept;

Where the value came from.

function

Path

#
std::string_view Path( SConfigHandle H ) const noexcept;

Full path of a value, as stored in the index.

function

ValueCount

#
std::size_t ValueCount() const noexcept

Number of values in the flat array.

function

KeyCount

#
std::size_t KeyCount() const noexcept

Number of keys in the path index.

function

Root

#
SConfigHandle Root() const noexcept

The root, always a table. Valid even in an empty document.

function

IndexedPath

#
std::string_view IndexedPath( std::size_t i ) const noexcept;

Path of indexed key i, for a caller that walks everything.

function

IndexedValue

#
SConfigHandle IndexedValue( std::size_t i ) const noexcept;

Value of indexed key i, as a handle.

function

Stats

#
const SConfigStats & Stats() const noexcept

Counters of the document.

function

Hash

#
static ETL_UINT64 Hash( std::string_view s ) noexcept;

Hash of a path. Must be the same at build time and at lookup.

function

MarkSecret

#
void MarkSecret( const SConfigHandle H ) noexcept

Marks a value as secret. Only used before the document is published.

The document is immutable for its readers. This is the only change made to it, between the flattening and the publication, while no one holds it yet. After that it never changes again.

inifile.hpp

#include <ethereal/cpp/config/inifile.hpp>

Mutable INI file: read, change and write back.

This class was called 'CConfig' until spec 12 was closed.

It changed name, not behavior. Spec 12 wants 'CConfig' to be the layered document: immutable once resolved, swapped through an atomic pointer on hot reload, read without allocating. This class is something else: a mutable INI file that is read, changed and written again, with the order kept so the output is stable.

Both are useful and they are not the same. A settings file that a program changes and saves wants this one. A configuration loaded from four places and read in a loop wants the other. So it stayed, with a name that says what it is.

Code that used 'Config::CConfig' to read INI switches to 'Config::CIniFile'. That is the only change, and the 'smoke' bench was switched with it.

struct

SIniError

Ethereal::Config#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SIniError   final
{
    /// @brief  Line of the failure, starting at 1. Zero when the failure is not
    ///             about content, like a file that did not open.
    std::size_t uLine = 0;

    /// @brief  What is wrong.
    std::string sMessage;
};

Description of a failure while parsing an INI file.

The line matters more than the message. A configuration file is edited by hand, so mistakes in it are routine, and an error that does not say where makes the person hunt for the problem.

class

CIniFile

Ethereal::Config#
class CIniFile final
constructor

CIniFile

#
CIniFile() noexcept;

Constructor. Empty file.

function

ParseString

#
bool ParseString( std::string_view Text, SIniError * pOutError = nullptr );

Parses the configuration from text.

Text
Content in INI format.
pOutError
Optional. Receives the failure description.
true on success. On failure the previous content is discarded and the object is left empty, so no one works on a half loaded configuration. false also when the library is not licensed.
function

LoadFromFile

#
bool LoadFromFile( const char * sPath, SIniError * pOutError = nullptr );

Loads the configuration from a file.

sPath
File path, in UTF-8.
pOutError
Optional. Receives the failure description.
true on success. false on failure, also when the library is not licensed.
function

SaveToFile

#
bool SaveToFile( const char * sPath ) const;

Writes the configuration to a file, in the canonical format.

sPath
File path, in UTF-8. The file is overwritten.
true on success.
function

ToString

#
std::string ToString() const;

Returns the configuration in the canonical format, as text.

function

GetString

#
std::string GetString( std::string_view Section, std::string_view Key, std::string_view sDefault = {} ) const;

Reads a text.

Returns sDefault when the key does not exist. Use Has to tell a missing key from a value that is really empty.

function

GetInt

#
ETL_INT64 GetInt( std::string_view Section, std::string_view Key, const ETL_INT64 iDefault = 0 ) const;

Reads an integer.

Returns iDefault when the key does not exist or when the value is not a whole, valid integer. When that difference matters, use TryGetInt.

function

GetFloat

#
ETL_DOUBLE GetFloat( std::string_view Section, std::string_view Key, const ETL_DOUBLE dDefault = 0.0 ) const;

Reads a floating point number.

Same rule as GetInt for a malformed value.

function

GetBool

#
bool GetBool( std::string_view Section, std::string_view Key, const bool bDefault = false ) const;

Reads a boolean.

Accepts true, false, yes, no, on, off, 1 and 0, in any case. Anything else is malformed and returns the default.

function

TryGetStringView

#
bool TryGetStringView( std::string_view Section, std::string_view Key, std::string_view & OutValue ) const noexcept;

Reads a text, telling whether the key existed.

Returns a view over what is already stored, not a copy. This is where the spec 12 audit measured one allocation per read: TryGetInt built a std::string only to pass it to the converter, when the value was already stored as a std::string inside.

function

TryGetString

#
bool TryGetString( std::string_view Section, std::string_view Key, std::string & OutValue ) const;

Reads a text into a std::string. See TryGetStringView.

function

TryGetInt

#
bool TryGetInt( std::string_view Section, std::string_view Key, ETL_INT64 & OutValue ) const noexcept;

Reads an integer, telling whether the key existed and the value was valid.

function

TryGetFloat

#
bool TryGetFloat( std::string_view Section, std::string_view Key, ETL_DOUBLE & OutValue ) const noexcept;

Reads a floating point number, telling whether the key existed and the value was valid.

function

TryGetBool

#
bool TryGetBool( std::string_view Section, std::string_view Key, bool & OutValue ) const noexcept;

Reads a boolean, telling whether the key existed and the value was valid.

function

SetString

#
void SetString( std::string_view Section, std::string_view Key, std::string_view Value );

Sets a text. Creates the section and the key when missing.

function

SetInt

#
void SetInt( std::string_view Section, std::string_view Key, const ETL_INT64 iValue );

Sets an integer.

function

SetFloat

#
void SetFloat( std::string_view Section, std::string_view Key, const ETL_DOUBLE dValue );

Sets a floating point number.

function

SetBool

#
void SetBool( std::string_view Section, std::string_view Key, const bool bValue );

Sets a boolean, written as true or false.

function

Has

#
bool Has( std::string_view Section, std::string_view Key ) const noexcept;

true when the key exists in the section.

function

HasSection

#
bool HasSection( std::string_view Section ) const noexcept;

true when the section exists, even if empty.

function

Remove

#
bool Remove( std::string_view Section, std::string_view Key );

Removes a key.

true when the key existed.
function

RemoveSection

#
bool RemoveSection( std::string_view Section );

Removes a whole section, with all its keys.

true when the section existed.
function

Clear

#
void Clear() noexcept;

Discards everything.

function

SectionCount

#
std::size_t SectionCount() const noexcept;

Number of sections, counting the unnamed one when it has keys.

function

SectionNames

#
std::vector< std::string > SectionNames() const;

Section names, in the order they appear.

function

KeyNames

#
std::vector< std::string > KeyNames( std::string_view Section ) const;

Key names of a section, in the order they appear.

parser.hpp

#include <ethereal/cpp/config/parser.hpp>

Parsers of the Config module and the tree they produce.

The spec: parsing is zero copy. The parser holds the source buffer and every string value is a view into it. Values are materialized only when an escape sequence forces it, and those go into a single arena allocated once.

That has two consequences. First, the layer owns the source text. It keeps it whole and only drops it after Resolve, because until then every name and every value is a view over it. A layer that dropped the text would leave the tree full of dead views.

Second, the arena cannot move. If it were a growing 'std::vector<char>', the first reallocation would invalidate every view already handed out, and the symptom would be swapped text in values that had escapes, months later. So it is a chain of fixed size blocks, and a block never moves after it is created.

class

CArena

Ethereal::Config#

An arena of blocks. A block never moves after it is created.

class CArena final
constructor

CArena

#
CArena() = default;

Default constructor. No block is reserved until the first request.

function

Store

#
std::string_view Store( std::string_view s );

Stores s and returns a view over the copy, which lives as long as the arena.

function

Allocate

#
char * Allocate( std::size_t uBytes );

Reserves uBytes contiguous bytes and returns where. Null when out of memory.

function

Allocations

#
ETL_UINT64 Allocations() const noexcept

Number of blocks allocated.

function

Bytes

#
ETL_UINT64 Bytes() const noexcept

Bytes allocated in all blocks.

const

kNoNode

Ethereal::Config#
inline constexpr ETL_UINT32 kNoNode = 0xFFFFFFFFu;
struct

SNode

Ethereal::Config#
C++
struct   ETL_STRUCT_ALIGN   SNode   final
{
    /// @brief  Type of the value.
    EValueType    eType = EValueType::eNone;

    /// @brief  Index of the layer the node came from.
    ETL_UINT8    uOrigin = 0u;

    /// @brief  Boolean value.
    bool        bBool = false;

    /// @brief  Integer value.
    ETL_INT64    iInt = 0;

    /// @brief  Real value.
    ETL_DOUBLE    dDouble = 0.0;

    /// @brief  View over the source text, or over the arena when there were escapes.
    ///            A JSON number also keeps its source text here.
    std::string_view    sText;

    /// @brief  Name of this key inside its parent.
    std::string_view    sName;

    /// @brief  First child, or kNoNode.
    ETL_UINT32    uFirstChild = kNoNode;

    /// @brief  Last child, kept for constant time appends.
    ETL_UINT32    uLastChild = kNoNode;

    /// @brief  Next sibling, or kNoNode.
    ETL_UINT32    uNextSibling = kNoNode;

    /// @brief  Parent, so the lookup index knows whom this node belongs to.
    ETL_UINT32    uParent = kNoNode;

    /// @brief  Next node in the same bucket of the index. See CNodePool.
    ETL_UINT32    uNextInBucket = kNoNode;

    /// @brief  Number of children.
    ETL_UINT32    uChildCount = 0u;

    /// @brief  Line in the source, starting at 1.
    ETL_UINT32    uLine = 0u;

    /// @brief  Column in the source, starting at 1.
    ETL_UINT32    uColumn = 0u;

    /// @brief  Closed because `[a]` already appeared: redefining it is a TOML error.
    bool        bClosed = false;

    /// @brief  Born from an inline table `{ }`, which TOML forbids extending.
    bool        bInline = false;
};

A node of the intermediate tree.

class

CNodePool

Ethereal::Config#

The node pool of a parse. It grows, and nodes are referred to by index.

class CNodePool final
constructor

CNodePool

#
CNodePool() = default;

Default constructor.

function

NewNode

#
ETL_UINT32 NewNode( EValueType eType );

A new node. Returns its index.

operator

operator[]

#
SNode & operator[]( const ETL_UINT32 u ) noexcept

Node u.

operator

operator[]

#
const SNode & operator[]( const ETL_UINT32 u ) const noexcept

Node u, read only.

function

Size

#
std::size_t Size() const noexcept

Number of nodes.

function

Append

#
void Append( ETL_UINT32 uParent, ETL_UINT32 uChild );

Appends a child to the end of the children of a parent. Constant time.

uParent
Parent node.
uChild
Child node.
function

Find

#
ETL_UINT32 Find( ETL_UINT32 uParent, std::string_view sName ) const noexcept;

Finds a child by name. Constant time, see the index note below.

uParent
Parent node.
sName
Name of the child.
The child, or kNoNode.
function

DropChildren

#
void DropChildren( ETL_UINT32 uParent ) noexcept;

Drops the children of uParent, also taking them out of the index.

Taking them out of the index is required, not a cleanup. The merge replaces a value by dropping its children and adding others with the same names. If the old ones stayed in the index, the next lookup would return the old child, which is no longer in anyone's list.

function

Arena

#
CArena & Arena() noexcept

Arena for the texts materialized by the parse.

struct

SLayer

Ethereal::Config#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Layer
///=============================================================================


/// @brief  A source, its priority, and the tree parsed from it.
///
/// @details  The layer owns the source text, so it has to live until the end of
///            Resolve. See the note at the top of the file.
///
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SLayer   final
{
    /// @brief  Format of the source.
    EFormat        eFormat = EFormat::eToml;

    /// @brief  Priority. The highest wins.
    ETL_UINT32    uPriority = 0u;

    /// @brief  Name shown by Origin: the file path, or `"env"`.
    std::string        sOrigin;

    /// @brief  The text all views of the tree depend on.
    std::vector< char >        Source;

    /// @brief  Root of the tree of this layer, always a table.
    ETL_UINT32    uRoot = kNoNode;

    /// @brief  The arrays of this layer are appended to what is there, instead of replacing.
    ///
    /// @details  The spec: arrays replace by default with an opt-in append mode.
    ///            Array merge ambiguity is the most common source of config surprise,
    ///            so it must be stated and testable.
    bool        bAppendArrays = false;

    /// @brief  Reloadable: came from a file and can be read again.
    bool        bFromFile = false;

    /// @brief  A missing file is an error.
    bool        bRequired = true;
};
function

ParseToml

Ethereal::Config#
EStatus ParseToml( std::string_view sText, CNodePool & Pool, ETL_UINT8 uOrigin, ETL_UINT32 * pRootOut, SConfigError * pError );
function

ParseIni

Ethereal::Config#
EStatus ParseIni( std::string_view sText, CNodePool & Pool, ETL_UINT8 uOrigin, ETL_UINT32 * pRootOut, SConfigError * pError );

INI with sections. The dialect is documented in the .cpp.

const

kJsonDefaultMaxDepth

Ethereal::Config#
inline constexpr ETL_UINT32 kJsonDefaultMaxDepth = 128u;

Default nesting limit of ParseJson, in objects and arrays. The one of serde_json, so any document the Rust tools accept also passes here.

struct

SJsonOptions

Ethereal::Config#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SJsonOptions   final
{
    /// @brief  Most nodes this parse may create. Zero is no limit.
    ETL_UINT64        uMaxNodes = 0u;

    /// @brief  Most bytes this parse may create: the nodes (sizeof( SNode ) each)
    ///             plus the texts materialized because of escapes, counted as requested.
    ///             The growth slack of the pool is not counted. Zero is no limit.
    ETL_UINT64        uMaxBytes = 0u;

    /// @brief  Deepest nesting of objects and arrays. The root object is depth 1.
    ///             Zero is taken as the default, never as no limit.
    ETL_UINT32        uMaxDepth = kJsonDefaultMaxDepth;

    /// @brief  Accepts comments and a trailing comma.
    bool            bLenient = false;
};

Options and limits of ParseJson.

The text can come from anywhere (a downloaded tokenizer, a network reply), so every resource it can consume has a limit. The parser is recursive: the depth limit is what keeps a document of nested '[' from overflowing the stack.

function

ParseJson

Ethereal::Config#
EStatus ParseJson( std::string_view sText, const SJsonOptions & Options, CNodePool & Pool, ETL_UINT8 uOrigin, ETL_UINT32 * pRootOut, SConfigError * pError );
function

ParseJson

Ethereal::Config#
EStatus ParseJson( std::string_view sText, bool bLenient, CNodePool & Pool, ETL_UINT8 uOrigin, ETL_UINT32 * pRootOut, SConfigError * pError );

JSON. bLenient accepts comments and a trailing comma. The other limits are the defaults of SJsonOptions (depth kJsonDefaultMaxDepth). It calls the overload above, so it also returns eOutOfMemory instead of throwing.

function

ParseEnv

Ethereal::Config#
EStatus ParseEnv( std::string_view sPrefix, const char * const * pVariables, CNodePool & Pool, ETL_UINT8 uOrigin, ETL_UINT32 * pRootOut, SConfigError * pError );

Environment variables with a prefix. The name rule is in the .cpp.

sPrefix
Prefix of the variables to take.
pVariables
List of NAME=value, or null to read the process ones.
Pool
Node pool that receives the tree.
uOrigin
Index of the layer.
pRootOut
Receives the root.
pError
Receives the failure. May be null.
eOk or the failure status.
function

ParseArgs

Ethereal::Config#
EStatus ParseArgs( int iArgc, const char * const * pArgv, std::string_view sPrefix, CNodePool & Pool, ETL_UINT8 uOrigin, ETL_UINT32 * pRootOut, SConfigError * pError );

Command line: --key.path=value, --key value, --flag.

function

ParseDuration

Ethereal::Config#
bool ParseDuration( std::string_view s, Time::SDuration * pOut ) noexcept;

Reads a duration: "30s", "5m", "1h30m", "250ms".

The spec makes duration and byte size parsing first class, because everyone needs them and everyone reimplements them badly.

Accepts a sequence of number and unit pairs. Units are ns, us, ms, s, m, h and d. A number without a unit is rejected on purpose: timeout = 30 does not say if it is seconds or milliseconds, and guessing is how bugs nobody finds get written.

function

ParseBytes

Ethereal::Config#
bool ParseBytes( std::string_view s, ETL_UINT64 * pOut ) noexcept;

Reads a size: "512MB", "4GiB", "1024".

kB is 1000 and KiB is 1024, as the IEC standard says, and a number without a unit is bytes. The difference is written down because it is exactly the one everyone mixes up.

schema.hpp

#include <ethereal/cpp/config/schema.hpp>

Schema and validation of the Config module.

The spec: unknown key detection is on by default in strict mode. A typo in a config key that silently does nothing is the worst failure mode this module can have.

The reason is not obvious. A wrong value gives wrong behavior, and someone notices. A wrong key gives nothing: the program runs with the default, looks fine, and whoever wrote 'server.tiemout = 60' believes the timeout is sixty seconds. So strict mode is the default, and turning it off is an explicit choice.

Errors are reported all at once. The spec: binding reports every problem, not the first one, so a user fixes the config in one pass. This applies to validation and to binding. A validator that stops at the first error forces one fix-build-run cycle per error, and a freshly written file has several.

struct

SSchemaEntry

Ethereal::Config#
C++
ETL_BEGIN_INTENDED_PADDING
struct   ETL_STRUCT_ALIGN   SSchemaEntry   final
{
    /// @brief  Full path, as in `"server.port"`.
    std::string_view    sPath;

    /// @brief  Expected type.
    EValueType            eType = EValueType::eNone;

    /// @brief  The key must exist.
    bool                bRequired = false;

    /// @brief  Marks the key as secret: Dump replaces it with a fixed marker.
    ///
    /// @details  The spec: a config dump that leaks a database password into a
    ///            log file is a security incident, and the API must make masking
    ///            the default for marked keys.
    bool                bSecret = false;

    /// @brief  Range, for `eInt`. Equal values turn the check off.
    ETL_INT64            iMin = 0;

    /// @brief  Upper end of the integer range.
    ETL_INT64            iMax = 0;

    /// @brief  Range, for `eDouble`. Equal values turn the check off.
    ETL_DOUBLE            dMin = 0.0;

    /// @brief  Upper end of the real range.
    ETL_DOUBLE            dMax = 0.0;

    /// @brief  Accepted values, for `eString`. Empty turns the check off.
    const std::string_view *    pAcceptedValues = nullptr;

    /// @brief  Number of accepted values.
    std::size_t            uAcceptedCount = 0u;

    /// @brief  A custom check. Returns false to reject.
    bool    ( * pValidate )( void * pCtx, const CDocument & Doc,
                           SConfigHandle H ) ETL_NOEXCEPT = nullptr;

    /// @brief  Context passed to pValidate.
    void *    pCtx = nullptr;

    /// @brief  Shown by Dump as a comment, and in error messages.
    std::string_view    sDescription;
};

A rule about one key.

class

CSchema

Ethereal::Config#
class CSchema final
constructor

CSchema

#
CSchema() = default;

Default constructor. Empty schema.

function

Add

#
EStatus Add( const SSchemaEntry & Rule );

Adds a rule.

function

AddMany

#
EStatus AddMany( const SSchemaEntry * pRules, std::size_t uCount );

Adds several rules at once.

function

Size

#
std::size_t Size() const noexcept

Number of rules.

function

At

#
const SSchemaEntry & At( const std::size_t i ) const noexcept

Rule i, in insertion order.

function

Find

#
const SSchemaEntry * Find( std::string_view sPath ) const noexcept;

Finds the rule of a path. Null when there is none.

function

Validate

#
EStatus Validate( const CDocument & Doc, bool bStrict, std::vector< SConfigError > * pErrors ) const;

Checks the whole document in one pass and gathers all errors.

A key is unknown when it has no rule and no rule is a prefix of it. The prefix is needed because a rule on servers covers servers.0.port: whoever declares a whole table does not declare each leaf of it.

Doc
Resolved document.
bStrict
Turns on unknown key detection.
pErrors
Receives every problem, not only the first one.
eOk, or the status of the first problem.