Overview / Data & formats

serialization

Two formats: a portable, versioned binary stream with a sticky error, and strict RFC 8259 JSON read and written with no DOM and no allocation, whole or in chunks.

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

serialization_inc.hpp

#include <ethereal/cpp/serialization/serialization_inc.hpp>

Aggregate entry point of the Serialization module.

Writes and reads values in a portable binary stream, with a fixed byte order, a schema version in the header and reads that fail instead of returning garbage.

The format is written out in serializer.hpp, not left to be deduced from the code, for the same reason as the INI dialect of the Config module: a format already written to disk cannot change without breaking whoever wrote with it.

Where this module is not the answer:

  • Ethereal::CBitStream : when what matters is the bit, and the size of each field is chosen by hand. The serializer works in bytes.
  • Ethereal::Encoding : when the bytes must become text (hex, Base64) to fit a place that only takes text.
  • Ethereal::Config : when a human will edit the file.

Including this header brings the whole module.

json.hpp

#include <ethereal/cpp/serialization/json.hpp>

JSON (RFC 8259): a pull reader and a writer into caller space.

The reader hands out one event at a time, at the caller's pace: the start and the end of objects and arrays, keys, strings, numbers, true, false, null and the end of the document. It copies nothing. A string without escapes is a view into the input, and a string with escapes says so, so the caller decodes it into its own buffer with UnescapeString. A number is its raw text, converted only when the caller asks, into the type the caller wants (NumberToInt64, NumberToUInt64, NumberToDouble).

The reader is strict by default, RFC 8259 in full:

  • the root may be any value, not only an object;
  • numbers follow the grammar exactly: no '+', no leading zero, no '.5', no '1.', no '1.2.3', no hexadecimal, and the conversion does not depend on the locale;
  • strings are UTF-8 checked, raw control characters (below 0x20) are refused, '\u' escapes take exactly four hex digits and surrogates must come in pairs;
  • only space, tab, line feed and carriage return are white space, and nothing but white space may follow the root.

A repeated key is not an error of the reader. Detecting it needs memory that grows with the object, and the reader allocates nothing. The consumer (a schema, the Config) knows its fields and decides.

Every event and every error carries its position: the byte offset, the line and the column (in bytes, both from 1).

Limits with safe defaults bound depth, string, key, number and document size, so a hostile input cannot make the reader do more than the caller allowed. The nesting stack lives inside the reader, so a document read whole allocates nothing at all.

The reader also takes the document in pieces of any size, as they arrive from a socket or a model that streams its output, and gives the same events, errors and positions as with the whole document. Only a token that a piece cuts in two is copied, into a buffer that the reader keeps for the next documents.

CJsonPointer builds the RFC 6901 path of where a walk is, for error messages, in a buffer of the caller.

The writer writes into a span of the caller and never allocates. When the span runs out it stops writing, keeps counting, and says how many bytes the whole document needs. An empty span measures without writing. It escapes what JSON requires, refuses invalid UTF-8 instead of replacing it, writes integers exactly and doubles in the shortest form that reads back to the same value, and checks the nesting: closing what was not opened, or a value where a key is due, is an error.

Not here: a DOM (whoever wants a tree builds it on top of the reader), JSON5, comments, JSON Schema.

Both classes are for the exclusive use of one thread.

enum

EJsonStatus

Ethereal::Serialization::Json#
C++
enum class   EJsonStatus : std::uint8_t
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  A character that does not fit the grammar where it is.
    eSyntax,

    /// @brief  The input ended in the middle of a value, or before any value.
    eUnexpectedEnd,

    /// @brief  Something other than white space after the root value.
    eTrailingContent,

    /// @brief  A number outside the RFC 8259 grammar ('+1', '01', '.5', '1.', '1e').
    eInvalidNumber,

    /// @brief  An escape that JSON does not have ('\x', '\u12', '\U0041').
    eInvalidEscape,

    /// @brief  A surrogate escape without its pair ('\uD800' alone, '\uDC00' first).
    eLoneSurrogate,

    /// @brief  A raw control character (below 0x20) inside a string.
    eControlCharacter,

    /// @brief  A string, a key or a value to write that is not valid UTF-8.
    eInvalidUtf8,

    /// @brief  Nesting deeper than SJsonReaderOptions::uMaxDepth (or the writer's).
    eDepthLimit,

    /// @brief  A string longer than SJsonReaderOptions::uMaxStringBytes.
    eStringLimit,

    /// @brief  A key longer than SJsonReaderOptions::uMaxKeyBytes.
    eKeyLimit,

    /// @brief  A number longer than SJsonReaderOptions::uMaxNumberBytes.
    eNumberLimit,

    /// @brief  A document larger than SJsonReaderOptions::uMaxDocumentBytes.
    eDocumentLimit,

    /// @brief  A number that does not fit the requested type, or has a fraction
    ///             where an integer was requested.
    eNumberRange,

    /// @brief  The output buffer is too small. The writer still counts what it needs.
    eBufferTooSmall,

    /// @brief  A call out of order on the writer (a value where a key is due,
    ///             closing what was not opened, writing after the root).
    eWriterState,

    /// @brief  An invalid argument (NaN or infinity to write, an event of another
    ///             type, an option out of range).
    eInvalidArgument,

    /// @brief  The reader has no document open.
    eNotOpen,

    /// @brief  Not an error: a stream waits for the next piece (SkipValue).
    eNeedMore,

    /// @brief  The allocator of the token buffer returned null.
    eOutOfMemory,

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

Result of the JSON calls.

function

StatusName

Ethereal::Serialization::Json#
const char * StatusName( EJsonStatus e ) noexcept;

Name of a status, for logs.

e
The status.
A static string.
enum

EJsonEvent

Ethereal::Serialization::Json#
C++
enum class   EJsonEvent : std::uint8_t
{
    /// @brief  No event yet.
    eNone = 0,

    /// @brief  '{'.
    eBeginObject,

    /// @brief  '}'.
    eEndObject,

    /// @brief  '['.
    eBeginArray,

    /// @brief  ']'.
    eEndArray,

    /// @brief  A key of an object. Text is its content, without the quotes.
    eKey,

    /// @brief  A string value. Text is its content, without the quotes.
    eString,

    /// @brief  A number. Text is its raw text, exactly as in the input.
    eNumber,

    /// @brief  'true'.
    eTrue,

    /// @brief  'false'.
    eFalse,

    /// @brief  'null'.
    eNull,

    /// @brief  The root value ended and only white space followed. Repeats.
    eEnd,

    /// @brief  The input given so far ended in the middle of something. Reserved for
    ///             the incremental reader, never returned by a document opened whole.
    eNeedMore,

    /// @brief  An error. CJsonReader::Error tells what and where. Repeats.
    eError,
};

What the reader found.

function

EventName

Ethereal::Serialization::Json#
const char * EventName( EJsonEvent e ) noexcept;

Name of an event, for logs.

e
The event.
A static string.
function

ScanPath

Ethereal::Serialization::Json#
Ethereal::Cpu::ESimdLevel ScanPath( void ) noexcept;

Instruction set of the reader's scans (the run of a string, the white space) for a document opened now.

A test against the scalar path does not prove that the vector path ran. This does. AVX2, SSE2 or NEON, or Scalar under a SIMD ceiling below them (Cpu::SetSimdCeiling). The reader takes it at OpenStream.

Avx2, Sse2, Neon or Scalar.
struct

SJsonPosition

Ethereal::Serialization::Json#
C++
struct   SJsonPosition
{
    /// @brief  Byte offset, from 0.
    std::size_t        uOffset = 0;

    /// @brief  Line, from 1. Lines are counted at '\n', the only place a line break
    ///             may appear outside a string.
    std::size_t        uLine = 1;

    /// @brief  Column in bytes, from 1. A tab counts as one byte.
    std::size_t        uColumn = 1;
};

A position in the input.

const

kJsonHasEscape

Ethereal::Serialization::Json#
inline constexpr std::uint8_t kJsonHasEscape = 0x01u;

The string or key has at least one escape. Text holds it raw: decode it with UnescapeString.

const

kJsonIntegerSyntax

Ethereal::Serialization::Json#
inline constexpr std::uint8_t kJsonIntegerSyntax = 0x02u;

The number has no fraction and no exponent.

const

kJsonNegative

Ethereal::Serialization::Json#
inline constexpr std::uint8_t kJsonNegative = 0x04u;

The number starts with '-'.

struct

SJsonEvent

Ethereal::Serialization::Json#
C++
struct   SJsonEvent
{
    /// @brief  The event.
    EJsonEvent            eType = EJsonEvent::eNone;

    /// @brief  kJsonHasEscape, kJsonIntegerSyntax, kJsonNegative.
    std::uint8_t        uFlags = 0;

    /// @brief  Depth after the event. The root container opens depth 1. A key and
    ///             the value after it have the depth of their object.
    std::uint32_t        uDepth = 0;

    /// @brief  The text of a key, string or number. Empty for the others.
    std::string_view    Text;

    /// @brief  Where the event starts in the input.
    SJsonPosition        Pos;
};

One event of the reader.

Text points into the input (or, in the incremental reader, into its token buffer) and stays valid until the next call to the reader that changes the input. For keys and strings it is the content between the quotes, escapes included. For numbers it is the raw text.

struct

SJsonError

Ethereal::Serialization::Json#
C++
struct   SJsonError
{
    /// @brief  The status. eOk when there is no error.
    EJsonStatus            eStatus = EJsonStatus::eOk;

    /// @brief  Where the error is. For a bad character, the character itself.
    SJsonPosition        Pos;

    /// @brief  Static message, in English.
    const char *        pMessage = "";
};

An error of the reader.

const

kJsonMaxDepthLimit

Ethereal::Serialization::Json#
inline constexpr std::uint32_t kJsonMaxDepthLimit = 1024u;

Highest depth the reader and the writer can track. Their nesting stack is a bit set of this many bits inside the object.

struct

SJsonReaderOptions

Ethereal::Serialization::Json#
C++
struct   SJsonReaderOptions
{
    /// @brief  Maximum nesting, up to kJsonMaxDepthLimit. Going over it is eDepthLimit.
    std::uint32_t        uMaxDepth = 512u;

    /// @brief  Maximum string value, in raw bytes between the quotes.
    std::size_t            uMaxStringBytes = std::size_t( 64u ) << 20;

    /// @brief  Maximum key, in raw bytes between the quotes.
    std::size_t            uMaxKeyBytes = std::size_t( 64u ) << 10;

    /// @brief  Maximum number, in bytes of text.
    std::size_t            uMaxNumberBytes = 4096u;

    /// @brief  Maximum document, in bytes (the sum of every piece, when streaming).
    std::size_t            uMaxDocumentBytes = std::size_t( 1u ) << 30;

    /// @brief  Allocator of the token buffer of the stream reader. Null is
    ///             Memory::DefaultAllocator. A document opened whole never allocates.
    Memory::IAllocator *    pAllocator = nullptr;

    /// @brief  Skips a UTF-8 byte order mark at the start. RFC 8259 forbids sending
    ///             one and allows ignoring it, so the strict default refuses it.
    bool                bSkipBom = false;
};

Reader options. The defaults are safe for input from the network.

enum

EJsonPending

Ethereal::Serialization::Json#
C++
enum class   EJsonPending : std::uint8_t
{
    eNone = 0,        /// No token is cut.
    eString,        /// A string value.
    eKey,            /// A key.
    eValue,            /// A number or a word ('true', 'false', 'null').
};

The kind of a token cut in two by the end of a piece.

struct

SJsonPendingToken

Ethereal::Serialization::Json#
C++
struct   SJsonPendingToken
{
    /// @brief  The kind. eNone when no token is cut.
    EJsonPending        eKind = EJsonPending::eNone;

    /// @brief  kJsonHasEscape when Text may hold an escape.
    std::uint8_t        uFlags = 0;

    /// @brief  For a key or a string, the raw text after the opening quote up to the
    ///             last point the reader checked: whole escapes and whole UTF-8 sequences
    ///             only, so it always decodes, and the rest of the token only extends it.
    ///             For a number or a word, the bytes so far, not checked yet.
    std::string_view    Text;

    /// @brief  Absolute offset of the token in the document: the opening quote, or the
    ///             first byte. The same as SJsonEvent::Pos.uOffset of its event.
    std::size_t            uOffset = 0;
};

A token cut by the end of a piece, as far as it arrived (CJsonReader::PendingToken).

class

CJsonReader

Ethereal::Serialization::Json#

Pull reader of one JSON document, whole or in pieces.

class CJsonReader

Whole: Open the document, then call Next until eEnd or eError. The views of the events point into the document, which must stay alive and unchanged while the reader uses it. Nothing is allocated.

In pieces: OpenStream, then Feed each piece as it arrives, of any size, one byte included. Next returns eNeedMore when the piece given runs out, and the caller feeds the next one. The last piece goes with bLast set (it may be empty). The events are the same as with the whole document, errors and positions included.

A token that a piece cuts in two (a string, a number, a word) is copied into a token buffer of the reader, and its event points there. That is the only allocation, through SJsonReaderOptions::pAllocator, and the buffer is kept for the next documents. A view, into a piece or into the token buffer, stays valid until Next returns eNeedMore: until then the caller keeps the piece alive and unchanged.

For the exclusive use of one thread.
constructor

CJsonReader

#
CJsonReader() noexcept = default;

Builds a reader with the default options and no document.

constructor

CJsonReader

#
explicit CJsonReader( const SJsonReaderOptions & Options ) noexcept;

Builds a reader with these options and no document.

constructor

CJsonReader

#
CJsonReader( CJsonReader && o ) noexcept;

Takes the state and the token buffer of o, which is left closed.

operator

operator=

#
CJsonReader & operator=( CJsonReader && o ) noexcept;

Frees this token buffer and takes the state of o, which is left closed.

function

Open

#
EJsonStatus Open( std::string_view sDocument ) noexcept;

Starts reading a whole document.

The same as OpenStream followed by Feed( sDocument, true ). A uMaxDepth above kJsonMaxDepthLimit is eInvalidArgument. A document over uMaxDocumentBytes is eDocumentLimit. Either way, Next then returns eError.

sDocument
The whole document, UTF-8.
eOk, or the error status. eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

OpenStream

#
EJsonStatus OpenStream( void ) noexcept;

Starts reading a document in pieces. Feed gives them.

eOk, eInvalidArgument (uMaxDepth) or eNotLicensed.
function

Feed

#
EJsonStatus Feed( std::string_view sPiece, bool bLast = false ) noexcept;

Gives the next piece of a document opened with OpenStream.

Called after OpenStream, or after Next returned eNeedMore. Feeding while the previous piece still has bytes to read, or after the last piece, is eInvalidArgument and changes nothing.

sPiece
The piece. May be empty.
bLast
Whether it is the last piece.
eOk, eInvalidArgument, eNotOpen, eDocumentLimit (the pieces passed uMaxDocumentBytes, and Next returns eError), or the error already found.
function

Next

#
EJsonEvent Next( SJsonEvent & Out ) noexcept;

Reads the next event.

Out
Receives the event. On eError and eNeedMore only eType, uDepth and Pos are set.
The type of the event, the same as Out.eType.
function

SkipValue

#
EJsonStatus SkipValue( void ) noexcept;

Skips the rest of the container just opened, or nothing.

Called right after eBeginObject or eBeginArray, reads up to the matching end, checking everything as Next would. After any other event it does nothing: a scalar was already read whole. Useful to ignore an unknown key's value.

With a stream, eNeedMore may stop it midway: Feed the next piece and call SkipValue again, it goes on from where it stopped.

eOk, eNeedMore (a stream waits for the next piece: Feed it and call SkipValue again), or the status of the error found.
function

Error

#
const SJsonError & Error( void ) const noexcept

The error, after Next returned eError.

function

Depth

#
std::uint32_t Depth( void ) const noexcept

Current depth.

function

Options

#
const SJsonReaderOptions & Options( void ) const noexcept

The options in use.

function

BytesFed

#
std::size_t BytesFed( void ) const noexcept

Bytes given so far (the whole document, or the sum of the pieces).

function

PendingToken

#
SJsonPendingToken PendingToken( void ) const noexcept;

The token the end of the last piece cut in two, as far as it arrived.

Meaningful after Next or SkipValue returned eNeedMore. Lets a caller look at a value before it is complete: its type is known from the first byte, and a string only grows. The view points into the token buffer and stays valid until the next Feed.

The token, with eKind eNone when no token is cut.
function

UnescapeString

Ethereal::Serialization::Json#
EJsonStatus UnescapeString( std::string_view sRaw, std::span< char > Out, std::size_t & uOutBytes ) noexcept;

Decodes the raw text of a key or string into the caller's buffer.

The result is never longer than the raw text, so a buffer of sRaw.size() bytes is always enough. Text the reader accepted always decodes, and the result is valid UTF-8. Raw text from elsewhere is checked: a bad escape or a lone surrogate is an error.

sRaw
The raw text (SJsonEvent::Text), without the quotes.
Out
Destination.
uOutBytes
Receives the decoded size. On eBufferTooSmall, the size needed.
eOk, eBufferTooSmall, eInvalidEscape or eLoneSurrogate.
function

NumberToInt64

Ethereal::Serialization::Json#
EJsonStatus NumberToInt64( std::string_view sNumber, ETL_INT64 & iOut ) noexcept;

Converts the raw text of a number to a signed 64 bit integer, exactly.

The text must be an integer in the JSON grammar. A fraction or an exponent is eNumberRange even when the value is whole ('1.0', '1e2'): integers in JSON are written as integers.

sNumber
The raw text (SJsonEvent::Text).
iOut
Receives the value.
eOk, eNumberRange (fraction, exponent, or out of range) or eInvalidNumber (not a JSON number).
function

NumberToUInt64

Ethereal::Serialization::Json#
EJsonStatus NumberToUInt64( std::string_view sNumber, ETL_UINT64 & uOut ) noexcept;

Converts the raw text of a number to an unsigned 64 bit integer, exactly.

As NumberToInt64. A negative number is eNumberRange, '-0' included.

sNumber
The raw text (SJsonEvent::Text).
uOut
Receives the value.
eOk, eNumberRange or eInvalidNumber.
function

NumberToDouble

Ethereal::Serialization::Json#
EJsonStatus NumberToDouble( std::string_view sNumber, ETL_DOUBLE & dOut ) noexcept;

Converts the raw text of a number to the nearest double, without locale.

Correctly rounded. A value too small for a double becomes zero with its sign (that is the correct rounding). A value too large is eNumberRange, never infinity.

sNumber
The raw text (SJsonEvent::Text).
dOut
Receives the value.
eOk, eNumberRange or eInvalidNumber.
function

IsValidNumber

Ethereal::Serialization::Json#
bool IsValidNumber( std::string_view sNumber ) noexcept;

Tells whether a text is exactly one number in the RFC 8259 grammar.

sNumber
The text.
true when it is.
struct

SJsonWriterOptions

Ethereal::Serialization::Json#
C++
struct   SJsonWriterOptions
{
    /// @brief  Spaces per level. 0 writes compact, on one line.
    std::uint32_t        uIndent = 0;

    /// @brief  Maximum nesting, up to kJsonMaxDepthLimit.
    std::uint32_t        uMaxDepth = kJsonMaxDepthLimit;

    /// @brief  Writes every character outside ASCII as '\uXXXX' (with surrogate
    ///             pairs). For a channel that only takes ASCII.
    bool                bAsciiOnly = false;

    /// @brief  Writes U+2028 and U+2029 as '
' and '
'. They are valid
    ///             JSON but end a line in JavaScript source, which breaks JSON embedded
    ///             in a script.
    bool                bEscapeLineSeparators = false;
};

Writer options.

class

CJsonWriter

Ethereal::Serialization::Json#

Writes one JSON document into a buffer of the caller, without allocating.

class CJsonWriter

The first error is kept and every later call does nothing. On eBufferTooSmall the writer keeps going without writing, so Size tells the size of the whole document. An empty span measures.

Finish checks that the document is complete (one root value, every container closed). The output is the first Size() bytes of the span, without a terminator.

For the exclusive use of one thread.
constructor

CJsonWriter

#
explicit CJsonWriter( std::span< char > Out, const SJsonWriterOptions & Options = {} ) noexcept;

Starts a document in Out.

Out
Destination. May be empty, to measure.
Options
Options. A uMaxDepth above kJsonMaxDepthLimit is eInvalidArgument.
Status is eNotLicensed when the library is not licensed (see Bundle::UnlockBundle), and nothing is written.
function

BeginObject

#
CJsonWriter & BeginObject( void ) noexcept;

'{'.

function

EndObject

#
CJsonWriter & EndObject( void ) noexcept;

'}'.

function

BeginArray

#
CJsonWriter & BeginArray( void ) noexcept;

'['.

function

EndArray

#
CJsonWriter & EndArray( void ) noexcept;

']'.

function

Key

#
CJsonWriter & Key( std::string_view sKey ) noexcept;

A key, inside an object, before each value. UTF-8, escaped here.

function

String

#
CJsonWriter & String( std::string_view sValue ) noexcept;

A string value. UTF-8, escaped here.

function

Int64

#
CJsonWriter & Int64( ETL_INT64 iValue ) noexcept;

A signed integer, exactly.

function

UInt64

#
CJsonWriter & UInt64( ETL_UINT64 uValue ) noexcept;

An unsigned integer, exactly.

function

Double

#
CJsonWriter & Double( ETL_DOUBLE dValue ) noexcept;

A double in the shortest form that reads back the same. NaN and infinity have no JSON form and are eInvalidArgument.

function

Bool

#
CJsonWriter & Bool( bool bValue ) noexcept;

'true' or 'false'.

function

Null

#
CJsonWriter & Null( void ) noexcept;

'null'.

function

RawNumber

#
CJsonWriter & RawNumber( std::string_view sNumber ) noexcept;

A number given as text (for example one read by CJsonReader), checked against the grammar and written unchanged.

function

RawValue

#
CJsonWriter & RawValue( std::string_view sJson, bool bCheck = true ) noexcept;

A complete JSON value given as text (an object, an array or a scalar, for example a schema or a tool input read elsewhere), written as given.

Whitespace around the value is dropped and the rest is copied byte for byte, so the value keeps its own layout even when the writer indents.

With bCheck (the default) the value is read first by CJsonReader, without allocating: text that is not exactly one JSON value fails with the status of the reader (eSyntax, eTrailingContent and so on), and a value nested deeper than what is left of uMaxDepth fails with eDepthLimit. Without the check the caller vouches for the text, and only an empty value is refused.

With bAsciiOnly a byte outside ASCII is eInvalidArgument, and with bEscapeLineSeparators so is U+2028 or U+2029: the text is not rewritten, so it cannot be made to follow those options.

sJson
The value.
bCheck
Reads the value before writing it.
function

Finish

#
EJsonStatus Finish( void ) noexcept;

Ends the document.

eOk, the first error, or eWriterState when the document is not complete.
function

Status

#
EJsonStatus Status( void ) const noexcept

The first error, or eOk.

function

Size

#
std::size_t Size( void ) const noexcept

Bytes of the document so far, written or not (after eBufferTooSmall, the size the whole document needs).

function

View

#
std::string_view View( void ) const noexcept

The document written, valid when Status is eOk.

class

CJsonPointer

Ethereal::Serialization::Json#

Builds a JSON Pointer ("/a/0/b~1c") in a buffer of the caller, one segment per level, without allocating.

class CJsonPointer

Whoever walks a document pushes a segment when it enters a value (the key of an object, the index in an array) and pops it when it leaves. View is the pointer of where the walk is, for an error message or a path.

Keys are given decoded (after UnescapeString). '~' is written as "~0" and '/' as "~1", as RFC 6901 requires.

A segment that does not fit is not written, and Truncated says so. The count stays right, so the pushes and pops still match, and the view goes back to complete once the walk leaves the segments that did not fit.

For the exclusive use of one thread.
constructor

CJsonPointer

#
explicit CJsonPointer( std::span< char > Buffer ) noexcept;

Starts the root pointer (empty) in Buffer.

function

PushKey

#
bool PushKey( std::string_view sKey ) noexcept;

Enters the value of the key sKey (decoded UTF-8). False when it did not fit.

function

PushIndex

#
bool PushIndex( ETL_UINT64 uIndex ) noexcept;

Enters the item uIndex of an array. False when it did not fit.

function

Pop

#
void Pop( void ) noexcept;

Leaves the last segment. Nothing at the root.

function

Clear

#
void Clear( void ) noexcept;

Back to the root.

function

View

#
std::string_view View( void ) const noexcept

The pointer so far. Empty at the root.

function

Depth

#
std::uint32_t Depth( void ) const noexcept

How many segments were pushed and not popped.

function

Truncated

#
bool Truncated( void ) const noexcept

Whether a segment of the current path is missing from View.

serializer.hpp

#include <ethereal/cpp/serialization/serializer.hpp>

Portable binary stream: CWriter and CReader.

A wire format, once written to disk or sent over the network, cannot change without breaking whoever already wrote data with it. That is why it is described here in full, not left to be deduced from the code.

Header, 9 bytes: 0..3 Signature, the characters 'E' 'T' 'L' 'S'. 4 Format version, currently 1. Identifies the structure of the envelope, and changes only when the envelope itself changes. 5..8 User schema version, 4 bytes little-endian. The writer provides it, the reader checks it with CReader::UserVersion and decides how to interpret what comes next.

Body: Fixed size integers are written little-endian, two's complement for the signed ones. The conversion uses shifts, not a copy of the value's memory, so the result does not depend on the native byte order of the writing machine.

float and double are written as their 32 or 64 bits, in the same order.

bool takes one byte, 0 or 1.

Lengths use a variable size integer, seven bits per byte, the high bit flagging continuation (unsigned LEB128). A short text spends one length byte instead of eight.

Text and binary blocks are the variable length followed by the raw bytes. Text gets no null terminator and may contain zero in the middle.

What this module does not do: describe its own content. There are no field names or type tags in the stream, and reading out of the order of writing produces silent garbage. That is the price of a compact format. Whoever needs reading by name wants a self describing format.

const

FORMAT_VERSION

Ethereal::Serialization#
constexpr std::uint8_t FORMAT_VERSION = 1;

Envelope version written and accepted by this implementation.

const

HEADER_SIZE

Ethereal::Serialization#
constexpr std::size_t HEADER_SIZE = 9;

Header size, in bytes.

class

CWriter

Ethereal::Serialization#

Builds a binary stream in the format described at the top of this file.

class CWriter final

The header is written at construction. From then on each call appends to the end. Writing does not fail: the buffer grows as needed.

Not guaranteed to be thread safe.
constructor

CWriter

#
explicit CWriter( const ETL_UINT32 uUserVersion = 1 );

Opens a new stream.

uUserVersion
Schema version of the writer. Reaches CReader::UserVersion unchanged.
function

WriteBool

#
void WriteBool( const bool bValue );

Writes a bool, one byte, 0 or 1.

function

WriteInt8

#
void WriteInt8( const ETL_INT8 iValue );

Write fixed size signed integers, little-endian.

function

WriteInt16

#
void WriteInt16( const ETL_INT16 iValue );
function

WriteInt32

#
void WriteInt32( const ETL_INT32 iValue );
function

WriteInt64

#
void WriteInt64( const ETL_INT64 iValue );
function

WriteUInt8

#
void WriteUInt8( const ETL_UINT8 uValue );

Write fixed size unsigned integers, little-endian.

function

WriteUInt16

#
void WriteUInt16( const ETL_UINT16 uValue );
function

WriteUInt32

#
void WriteUInt32( const ETL_UINT32 uValue );
function

WriteUInt64

#
void WriteUInt64( const ETL_UINT64 uValue );
function

WriteFloat

#
void WriteFloat( const ETL_FLOAT fValue );

Write a float or a double as their raw bits, little-endian.

function

WriteDouble

#
void WriteDouble( const ETL_DOUBLE dValue );
function

WriteVarUInt

#
void WriteVarUInt( const ETL_UINT64 uValue );

Writes a variable size integer, seven bits per byte.

Worth it for values that are almost always small: counts, indices, lengths. For a value that usually takes the full width, fixed size is smaller and faster.

function

WriteString

#
void WriteString( std::string_view Text );

Writes a text: variable length followed by the bytes.

The null terminator is not written, and the text may contain zero in the middle.

function

WriteBytes

#
void WriteBytes( std::span< const std::uint8_t > Data );

Writes a binary block: variable length followed by the bytes.

function

Bytes

#
std::span< const std::uint8_t > Bytes() const noexcept;

Access to the stream built so far, header included.

function

Size

#
std::size_t Size() const noexcept;

Total size of the stream, in bytes.

function

Take

#
std::vector< std::uint8_t > Take();

Hands over the stream and returns the writer to its initial state, with the same header.

class

CReader

Ethereal::Serialization#
class CReader final
constructor

CReader

#
explicit CReader( std::span< const std::uint8_t > Data ) noexcept;

Opens a stream for reading and validates the header.

An invalid header already leaves the reader failed, and no read happens. Check IsValid before going on.

Data
Whole stream, header included.
function

IsValid

#
bool IsValid() const noexcept;

Tells that the header is valid and that no read has failed so far.

function

HasError

#
bool HasError() const noexcept;

Tells that some read failed, or that the header is invalid.

function

UserVersion

#
ETL_UINT32 UserVersion() const noexcept;

Schema version given by the writer.

The versioning hook: read this version first and decide how to interpret the rest. Zero when the header is invalid.

function

Remaining

#
std::size_t Remaining() const noexcept;

Number of bytes not read yet.

function

ReadBool

#
bool ReadBool( bool & bOutValue ) noexcept;

Reads a bool.

function

ReadInt8

#
bool ReadInt8( ETL_INT8 & iOutValue ) noexcept;

Read fixed size signed integers.

function

ReadInt16

#
bool ReadInt16( ETL_INT16 & iOutValue ) noexcept;
function

ReadInt32

#
bool ReadInt32( ETL_INT32 & iOutValue ) noexcept;
function

ReadInt64

#
bool ReadInt64( ETL_INT64 & iOutValue ) noexcept;
function

ReadUInt8

#
bool ReadUInt8( ETL_UINT8 & uOutValue ) noexcept;

Read fixed size unsigned integers.

function

ReadUInt16

#
bool ReadUInt16( ETL_UINT16 & uOutValue ) noexcept;
function

ReadUInt32

#
bool ReadUInt32( ETL_UINT32 & uOutValue ) noexcept;
function

ReadUInt64

#
bool ReadUInt64( ETL_UINT64 & uOutValue ) noexcept;
function

ReadFloat

#
bool ReadFloat( ETL_FLOAT & fOutValue ) noexcept;

Read a float or a double.

function

ReadDouble

#
bool ReadDouble( ETL_DOUBLE & dOutValue ) noexcept;
function

ReadVarUInt

#
bool ReadVarUInt( ETL_UINT64 & uOutValue ) noexcept;

Reads a variable size integer.

Fails when the sequence goes past ten bytes or when the value does not fit in 64 bits, which reveals a corrupt stream instead of returning a truncated number.

function

ReadString

#
bool ReadString( std::string & OutText );

Reads a text.

Fails when the announced length is larger than what is left in the stream. That is the defence that matters: a corrupt length is the shortest path to a huge allocation or an out of bounds read.

function

ReadBytes

#
bool ReadBytes( std::vector< std::uint8_t > & OutData );

Reads a binary block.