Type System

The dross type system provides dynamic typing with strong value semantics. The core types use the Pimpl idiom for ABI stability and provide consistent interfaces; error wraps a std::error_code directly, and timestamp and timezone hold their values directly.

Core Types

value

class value

Polymorphic value type that can hold any supported dross type.

The value class provides a type-safe polymorphic container that can hold any of the core dross types (boolean, number, string, array, dictionary, timestamp, data). It uses std::variant internally for type safety and performance, and provides convenient construction and conversion methods.

Key features:

  • Type-safe polymorphic storage using std::variant

  • Value semantics (copyable and assignable)

  • Convenient construction from any supported type

  • Template-based type checking and casting

  • Thread-safe for read operations

Supported types:

  • boolean: True/false values with logical operations

  • number: Arbitrary precision arithmetic

  • string: UTF-8 text held as bytes

  • array: Dynamic arrays of values

  • dictionary: Key-value mappings

  • timestamp: Date and time values with timezone support

  • data: Binary data with encoding and I/O capabilities

  • Arithmetic types (automatically converted to number)

  • String types (automatically converted to string)

Performance characteristics:

  • Construction: O(1) for simple types, O(n) for complex types

  • Type checking: O(1) compile-time and runtime checks

  • Casting with as<T>() or value_cast: O(n), a copy of what is held

  • Reading with get_if<T>(): O(1), without copying

  • Memory usage: Size of largest possible type plus small overhead

Thread safety:

  • Const operations are thread-safe

  • Non-const operations require external synchronization

// Basic usage with different types
dross::value bool_val = dross::boolean{true};
dross::value num = dross::number{42};
dross::value str = dross::string{"hello"};
dross::value arr = dross::array{dross::value{1}, dross::value{2}, dross::value{3}};

// Automatic type conversion
dross::value int_val = 123;      // Creates number
dross::value flag = true;        // Creates boolean
dross::value str_val = "text";   // Creates string

// Type checking and casting
if (num.is<dross::number>()) {
dross::number n = dross::value_cast<dross::number>(num);
}

// Braces hold the value they enclose; a list is built as an array
dross::value one = dross::value{dross::number{42}};
dross::value list_val = dross::array{dross::value{1}, dross::value{"two"}, dross::value{3.0}};

Public Functions

value()

Default constructor creating a null value.

value(const value &other)

Copy constructor.

Parameters:

other – The value to copy from

value(value &&other) noexcept

Move constructor.

Parameters:

other – The value to move from

value(const boolean &bool_val)

Construct from a boolean.

Parameters:

bool_val – The boolean to store

value(const number &num)

Construct from a number.

Parameters:

num – The number to store

value(const string &str)

Construct from a string.

Parameters:

str – The string to store

value(string &&str)

Construct from a string, taking its contents.

Parameters:

str – The string to move from

value(const array &arr)

Construct from an array.

Parameters:

arr – The array to store

value(array &&arr)

Construct from an array, taking its contents.

Parameters:

arr – The array to move from

value(const dictionary &dict)

Construct from a dictionary.

Parameters:

dict – The dictionary to store

value(dictionary &&dict)

Construct from a dictionary, taking its contents.

Parameters:

dict – The dictionary to move from

value(const timestamp &ts)

Construct from a timestamp.

Parameters:

ts – The timestamp to store

value(const data &d)

Construct from data.

Parameters:

d – The data to store

value(data &&d)

Construct from data, taking its contents.

Parameters:

d – The data to move from

~value()

Destructor.

template<value_number_type T>
inline value(const T n)

Construct from an arithmetic type other than bool or a character.

Automatically converts arithmetic types to number for convenient usage. A character is not accepted: name number or string instead.

Parameters:

n – The arithmetic value to convert to number

template<std::same_as<bool> B>
inline value(const B b)

Construct from bool, holding a boolean.

Only bool itself is accepted, so an integer is held as a number.

Parameters:

b – The bool to hold

template<character_type T>
value(T) = delete

Refuses a character: name number or string instead.

template<string_type T>
inline value(const T s)

Construct from any string-like type.

Automatically converts string types to string for convenient usage.

Parameters:

s – The string value to convert to string

bool equals(const value &other) const

Test equality with another value.

Performs deep comparison considering both type and content.

Parameters:

other – The value to compare with

Returns:

true if both values contain the same type and data

bool operator==(const value &other) const

Equality comparison operator.

Parameters:

other – The value to compare with

Returns:

true if values are equal

bool operator!=(const value &other) const

Inequality comparison operator.

Parameters:

other – The value to compare with

Returns:

true if values are not equal

explicit operator bool() const

Test whether the value holds anything.

This is a null test, not the truth of what is held: a value holding boolean(false), number(0) or an empty string, array or dictionary is true. Ask the held type for its own value or emptiness.

Returns:

false if the value is null, true otherwise

value &operator=(const std::nullptr_t)

Assignment from nullptr (creates null value).

Returns:

Reference to this value

value &operator=(const value &other)

Copy assignment operator.

Parameters:

other – The value to assign from

Returns:

Reference to this value

value &operator=(value &&other) noexcept

Move assignment operator.

Parameters:

other – The value to move from

Returns:

Reference to this value

value &operator=(const boolean &bool_val)

Assignment from boolean.

Parameters:

bool_val – The boolean to assign

Returns:

Reference to this value

value &operator=(const number &num)

Assignment from number.

Parameters:

num – The number to assign

Returns:

Reference to this value

value &operator=(const string &str)

Assignment from string.

Parameters:

str – The string to assign

Returns:

Reference to this value

value &operator=(string &&str)

Assignment from string, taking its contents.

Parameters:

str – The string to move from

Returns:

Reference to this value

value &operator=(const array &arr)

Assignment from array.

Parameters:

arr – The array to assign

Returns:

Reference to this value

value &operator=(array &&arr)

Assignment from array, taking its contents.

Parameters:

arr – The array to move from

Returns:

Reference to this value

value &operator=(const dictionary &dict)

Assignment from dictionary.

Parameters:

dict – The dictionary to assign

Returns:

Reference to this value

value &operator=(dictionary &&dict)

Assignment from dictionary, taking its contents.

Parameters:

dict – The dictionary to move from

Returns:

Reference to this value

value &operator=(const timestamp &ts)

Assign a timestamp to this value.

Parameters:

ts – The timestamp to assign

Returns:

Reference to this value

value &operator=(const data &d)

Assign data to this value.

Parameters:

d – The data to assign

Returns:

Reference to this value

value &operator=(data &&d)

Assignment from data, taking its contents.

Parameters:

d – The data to move from

Returns:

Reference to this value

template<value_number_type T>
inline value &operator=(const T n)

Assignment from an arithmetic type other than bool or a character.

Parameters:

n – The arithmetic value to assign as a number

Returns:

Reference to this value

template<std::same_as<bool> B>
inline value &operator=(const B b)

Assignment from bool, holding a boolean.

Parameters:

b – The bool to assign

Returns:

Reference to this value

template<character_type T>
value &operator=(T) = delete

Refuses a character: name number or string instead.

template<string_type T>
inline value &operator=(const T s)

Assignment from any string-like type.

Parameters:

s – The string value to assign

Returns:

Reference to this value

template<class T>
bool is() const noexcept

Check if the value contains a specific type.

Use this before casting: as<T>() hands back a default-constructed T when the value holds something else. Supports checking for boolean, number, string, array, dictionary, timestamp, and data types.

Template Parameters:

T – The type to check for

Returns:

true if the value contains type T, false otherwise

template<class T>
T as() const noexcept

Cast the value to a specific type.

This is a convenience method that delegates to value_cast, and it copies what is held: use get_if<T>() to read without copying. When the value holds another type this returns a default-constructed T rather than the contained object, so call is<T>() first. It does not throw.

Template Parameters:

T – The type to cast to

Returns:

The value as the specified type

template<class T>
const T *get_if() const & noexcept

Read the held object without copying it.

The pointer stays valid until this value is assigned to or destroyed. A temporary value is refused, as the pointer would outlive it.

dross::value val = dross::array{ 1, 2 };
if (const auto* items = val.get_if<dross::array>()) {
    std::size_t count = items->length();
}
Template Parameters:

T – The type to read

Returns:

A pointer to the held object, or nullptr when the value holds another type

template<class T>
const T *get_if() const && = delete
class storage

Public Functions

storage() = default
inline storage(const storage &s)

Public Members

std::variant<std::monostate, dross::boolean, dross::number, dross::string, dross::array, dross::dictionary, dross::timestamp, dross::data> value

The value class is the central polymorphic type that can hold any supported type:

#include <iostream>

#include <dross/type/array.h>
#include <dross/type/timezone.h>
#include <dross/type/value.h>

dross::value v1 = 42;                       // Holds a number
dross::value v2 = "hello";                  // Holds a string
dross::value v3 = dross::array{};           // Holds an array
dross::value v4 = dross::boolean{true};     // Holds a boolean
dross::value v5 = dross::timestamp{2024, 1, 21, 15, 30, 0,
                                   dross::timezone::offset(9)};  // Holds a timestamp

// A bare `true` would select the arithmetic constructor and end up as a
// number, so the boolean above is wrapped explicitly.

// Ask is<T>() first: when the value holds another type, as<T>() hands
// back a default-constructed T instead of the contained object
if (v1.is<dross::number>()) {
    auto num = v1.as<dross::number>();
    std::cout << num << std::endl;  // number has operator<<
}

if (v5.is<dross::timestamp>()) {
    auto ts = v5.as<dross::timestamp>();
    std::cout << "Meeting time: " << ts << std::endl;
}

boolean

class boolean

Boolean type with value semantics and type safety.

The boolean class provides a type-safe boolean value with explicit conversions and full integration with the dross type system. Unlike native bool, this class provides consistent behavior across the type system and enables features like null/undefined distinction when used with std::optional.

Key features:

  • Type-safe boolean operations

  • Seamless string conversion (“true”/”false”)

  • Integration with dross type system

  • Value semantics (copyable and assignable)

  • Three-way comparison support

  • Safe conversions from various types

  • Thread-safe for read operations

Performance characteristics:

  • Construction: O(1)

  • Comparison: O(1)

  • String conversion: O(1) (returns constant strings)

  • Memory usage: Minimal (single boolean value + Pimpl overhead)

Thread safety:

  • Const operations are thread-safe

  • Non-const operations require external synchronization

// Basic usage
dross::boolean flag{true};
dross::boolean enabled{"true"};  // From string
dross::boolean disabled{0};      // From integer (0 = false, non-zero = true)

// Boolean operations
if (flag) {
// Handle true case
}

// Logical operations
dross::boolean a{true};
dross::boolean b{false};
dross::boolean result = a && b;  // false

// String conversion (multiple approaches)
std::string str1 = flag;                    // Implicit conversion
std::string str2 = dross::to_string(flag);  // STL-style explicit conversion

// Comparison
if (flag == true) {
// Direct comparison with bool
}

Public Functions

boolean()

Default constructor creating a boolean with value false.

boolean(const boolean &other)

Copy constructor.

Parameters:

other – The boolean to copy from

boolean(boolean &&other) noexcept

Move constructor.

Parameters:

other – The boolean to move from

boolean(bool value)

Construct from native bool.

Parameters:

value – The boolean value

boolean(int value)

Construct from integer.

Follows C++ convention where 0 is false and any non-zero value is true.

Parameters:

value – The integer value (0 = false, non-zero = true)

boolean(const std::string &str)

Construct from string.

Accepts “true”, “false”, “TRUE”, “FALSE”, “True”, “False”. Also accepts “1” for true and “0” for false. Any other string value results in false.

Parameters:

str – String representation (“true” or “false”, case-insensitive)

boolean(const char *str)

Construct from C-style string.

Same parsing rules as std::string constructor.

Parameters:

str – C-style string representation

template<non_string_pointer_type P>
boolean(P) = delete

Refuses a pointer other than a C string.

template<std::same_as<std::nullptr_t> N>
boolean(N) = delete

Refuses nullptr, which would otherwise be read as a null C string.

~boolean()

Destructor.

bool value() const

Get the boolean value.

Returns:

The underlying boolean value

bool equals(const boolean &other) const

Test equality with another boolean.

Parameters:

other – The boolean to compare with

Returns:

true if both booleans have the same value

bool equals(bool value) const

Test equality with a native bool.

Parameters:

value – The bool to compare with

Returns:

true if this boolean equals the bool value

template<pointer_type P>
bool equals(P) const = delete

Refuses a pointer, including a C string, which would otherwise compare as “not null”.

template<std::same_as<std::nullptr_t> N>
bool equals(N) const = delete
bool operator==(const boolean &other) const

Equality comparison operator.

Parameters:

other – The boolean to compare with

Returns:

true if both booleans are equal

bool operator!=(const boolean &other) const

Inequality comparison operator.

Parameters:

other – The boolean to compare with

Returns:

true if booleans are not equal

bool operator==(bool value) const

Equality comparison with native bool.

Parameters:

value – The bool to compare with

Returns:

true if this boolean equals the bool value

bool operator!=(bool value) const

Inequality comparison with native bool.

Parameters:

value – The bool to compare with

Returns:

true if this boolean does not equal the bool value

template<pointer_type P>
bool operator==(P) const = delete

Refuses a pointer, including a C string, which would otherwise compare as “not null”.

template<pointer_type P>
bool operator!=(P) const = delete
template<std::same_as<std::nullptr_t> N>
bool operator==(N) const = delete

Refuses nullptr, which would otherwise be read as a null C string.

template<std::same_as<std::nullptr_t> N>
bool operator!=(N) const = delete
std::strong_ordering operator<=>(const boolean &other) const noexcept

Three-way comparison operator (spaceship operator).

Defines a total ordering where false < true, consistent with the standard boolean ordering in C++.

Parameters:

other – The boolean to compare with

Returns:

std::strong_ordering result (false < true)

boolean &operator=(const boolean &other)

Copy assignment operator.

Parameters:

other – The boolean to assign from

Returns:

Reference to this boolean

boolean &operator=(boolean &&other) noexcept

Move assignment operator.

Parameters:

other – The boolean to move from

Returns:

Reference to this boolean

boolean &operator=(bool value)

Assignment from native bool.

Parameters:

value – The bool value to assign

Returns:

Reference to this boolean

template<pointer_type P>
boolean &operator=(P) = delete

Refuses a pointer, including a C string, which would otherwise assign “not null”. Construct a boolean to parse a string.

template<std::same_as<std::nullptr_t> N>
boolean &operator=(N) = delete

Refuses nullptr, which would otherwise be read as a null C string.

boolean operator!() const

Logical NOT operator.

Returns:

New boolean with inverted value

boolean operator&&(const boolean &other) const

Logical AND operator.

Parameters:

other – The boolean to AND with

Returns:

New boolean with result of AND operation

boolean operator||(const boolean &other) const

Logical OR operator.

Parameters:

other – The boolean to OR with

Returns:

New boolean with result of OR operation

operator bool() const

Convert to native bool.

Allows boolean to be used directly in conditional contexts.

Returns:

The underlying boolean value

operator std::string() const

Convert to string.

Implicit conversion to string for seamless integration.

Returns:

“true” or “false”

Public Static Functions

static boolean T()

Create a true boolean value.

Factory method for creating true values.

Returns:

A boolean representing true

static boolean F()

Create a false boolean value.

Factory method for creating false values.

Returns:

A boolean representing false

class storage

Public Members

bool value = {false}

The boolean class provides type-safe boolean operations:

#include <iostream>
#include <string>

#include <dross/type/boolean.h>

dross::boolean flag{true};
dross::boolean enabled{"true"};  // From string
dross::boolean active{1};        // From integer

// Seamless string conversion
std::string status = flag;       // "true"
std::cout << status << std::endl;

// Direct output
std::cout << flag << " " << enabled << " " << active << std::endl;

number

class number

Arbitrary precision number class with string-based storage.

The number class provides arbitrary precision arithmetic operations using string-based internal representation. This allows handling numbers of any size without overflow concerns, making it suitable for financial calculations, cryptographic operations, and scientific computing where precision is critical.

Key features:

  • Arbitrary precision arithmetic (no overflow); a quotient that does not terminate within 4096 digits keeps 34 significant digits

  • String-based storage for maximum precision

  • Support for integers and floating-point numbers

  • Full set of arithmetic and comparison operators

  • Conversion to/from standard arithmetic types

  • NaN (Not a Number) support for error handling

  • Value semantics (copyable and assignable)

  • Thread-safe for read operations

Performance characteristics:

  • Construction: O(n) where n is the number of digits

  • Arithmetic operations: O(max(m,n)) for addition/subtraction, O(m*n) for multiplication

  • Comparisons: O(min(m,n)) for most cases

  • Memory usage: Proportional to the number of digits

Error handling:

  • Invalid operations return NaN instead of throwing exceptions

  • Division by zero results in NaN

  • Invalid string representations result in NaN

Thread safety:

  • Const operations are thread-safe

  • Non-const operations require external synchronization

// Basic usage
dross::number a{"123456789012345678901234567890"};
dross::number b{42};
dross::number result = a * b;  // No overflow!

// Arithmetic operations
dross::number sum = dross::number{"999999999999999999"} + dross::number{"1"};

// Comparisons
if (dross::number{"3.14159"} > dross::number{"3.14"}) {
// Handle greater value
}

// Conversion
double d = static_cast<double>(dross::number{"123.456"});
std::string s = static_cast<std::string>(dross::number{42});

Public Functions

number()

Default constructor creating a number with value 0.

number(const number &other)

Copy constructor.

Parameters:

other – The number to copy from

number(number &&other) noexcept

Move constructor.

Parameters:

other – The number to move from

number(const char *str)

Construct from C-style string.

Accepts decimal numbers in standard notation (e.g., “123”, “-45.67”, “1.23e-4”). An exponent is expanded in the text, keeping every digit: “1e3” is stored as 1000. An expansion longer than 4096 digits, and longer than the number as written, results in NaN, as do invalid strings. A decimal point or an exponent in the text makes a floating-point number.

Parameters:

str – Null-terminated string representation of the number

number(const std::string &str)

Construct from std::string.

Accepts decimal numbers in standard notation (e.g., “123”, “-45.67”, “1.23e-4”). An exponent is expanded in the text, keeping every digit: “1e3” is stored as 1000. An expansion longer than 4096 digits, and longer than the number as written, results in NaN, as do invalid strings. A decimal point or an exponent in the text makes a floating-point number.

Parameters:

str – String representation of the number

template<number_type T>
inline number(const T n)

Construct from any arithmetic type.

Converts standard arithmetic types (int, float, double, etc.) to number. A float or double is written as the shortest text that converts back to the same value, so 0.1 is stored as 0.1 and 1e-7 as 0.0000001. A long double follows the standard library’s std::to_chars, which in libc++ writes it at double precision. A value whose expansion is longer than 4096 digits, or that is not finite, results in NaN. A character is read as its code and bool as 0 or 1. A float, double or long double makes a floating-point number.

Parameters:

n – The arithmetic value to convert

~number()

Destructor.

bool is_nan() const

Check if this number represents NaN (Not a Number).

NaN results from invalid operations like division by zero, invalid string parsing, or arithmetic errors.

Returns:

true if the number is NaN, false otherwise

bool is_integer() const

Check if this number represents an integer value.

Returns false for NaN values.

Returns:

true if the number has no fractional part, false otherwise

bool is_floating_point() const

Check if this number was made as a floating-point number.

A number is floating point when its text has a decimal point or an exponent, when it is made from a floating-point type, or when it is the result of arithmetic with a floating-point operand or with a fraction, such as 1 / 4. Unlike is_integer(), this does not depend on the value: 1.0 is both. Comparisons ignore it. Returns false for NaN values.

Returns:

true if the number is floating point, false otherwise

bool equals(const number &other) const

Test equality with another number.

NaN is one value: every NaN equals every other NaN and no number.

Parameters:

other – The number to compare with

Returns:

true if both numbers represent the same value, false otherwise

template<number_type T>
inline bool equals(const T n) const

Test equality with an arithmetic value.

Parameters:

n – The arithmetic value to compare with

Returns:

true if this number equals the arithmetic value, false otherwise

std::weak_ordering compare(const number &other) const noexcept

Three-way comparison with another number.

NaN is one value, ordered below every number, so numbers that hold NaN can be sorted and used as keys. Numbers of the same value are equivalent whether or not they are floating point.

Parameters:

other – The number to compare with

Returns:

std::weak_ordering result (less, equivalent or greater)

template<number_type T>
inline std::weak_ordering compare(const T n) const noexcept

Three-way comparison with an arithmetic value.

Parameters:

n – The arithmetic value to compare with

Returns:

std::weak_ordering result (less, equivalent or greater)

bool operator==(const number &other) const

Equality comparison operator.

Parameters:

other – The number to compare with

Returns:

true if both numbers are equal, false otherwise

bool operator!=(const number &other) const

Inequality comparison operator.

Parameters:

other – The number to compare with

Returns:

true if numbers are not equal, false otherwise

std::weak_ordering operator<=>(const number &other) const noexcept

Three-way comparison operator (spaceship operator).

Parameters:

other – The number to compare with

Returns:

std::weak_ordering result for use with comparison operators

template<number_type T>
inline bool operator==(const T n) const

Equality comparison with arithmetic types.

Parameters:

n – The arithmetic value to compare with

Returns:

true if this number equals the arithmetic value

template<number_type T>
inline bool operator!=(const T n) const

Inequality comparison with arithmetic types.

Parameters:

n – The arithmetic value to compare with

Returns:

true if this number does not equal the arithmetic value

template<number_type T>
inline std::weak_ordering operator<=>(const T n) const noexcept

Three-way comparison with arithmetic types.

Parameters:

n – The arithmetic value to compare with

Returns:

std::weak_ordering result for use with comparison operators

number &operator=(const number &other)

Copy assignment operator.

Parameters:

other – The number to assign from

Returns:

Reference to this number

number &operator=(number &&other) noexcept

Move assignment operator.

Parameters:

other – The number to move from

Returns:

Reference to this number

number &operator=(const char *str)

Assignment from C-style string.

The number is floating point if the text has a decimal point or an exponent, and not otherwise.

Parameters:

str – Null-terminated string representation

Returns:

Reference to this number

number &operator=(const std::string &str)

Assignment from std::string.

The number is floating point if the text has a decimal point or an exponent, and not otherwise.

Parameters:

str – String representation of the number

Returns:

Reference to this number

template<number_type T>
inline number &operator=(const T n)

Assignment from arithmetic types.

Parameters:

n – The arithmetic value to assign

Returns:

Reference to this number

operator std::string() const

Convert to string representation.

Returns “NaN” for NaN values. The string format preserves the full precision of the number.

Returns:

String representation of the number

explicit operator int() const

Convert to int.

Does not throw. A NaN yields 0, a value outside the range of int is clamped to the nearest bound, and a fractional value is rounded to nearest rather than truncated.

Returns:

Rounded integer, clamped to the range of int

explicit operator double() const

Convert to double.

Does not throw. A NaN, or a value that cannot be parsed as a double, yields 0.0. May lose precision for very large numbers or numbers with many decimal places.

Returns:

Double-precision floating-point representation

explicit operator long long() const

Convert to long long.

Does not throw. A NaN, or a value that overflows long long, yields 0.

Returns:

Long long built from the integer part, discarding any fraction

number operator+(const number &other) const

Addition operator.

Returns NaN if either operand is NaN.

Parameters:

other – The number to add

Returns:

Result of addition

number operator-(const number &other) const

Subtraction operator.

Returns NaN if either operand is NaN.

Parameters:

other – The number to subtract

Returns:

Result of subtraction

number operator*(const number &other) const

Multiplication operator.

Returns NaN if either operand is NaN.

Parameters:

other – The number to multiply by

Returns:

Result of multiplication

number operator/(const number &other) const

Division operator.

Returns NaN if either operand is NaN or if dividing by zero. A quotient that terminates within 4096 digits is exact: 1 / 1024 is 0.0009765625. Any other keeps 34 significant digits, as IEEE decimal128 does, and the digits after them are truncated: 1 / 3 is 0.3333333333333333333333333333333333. The integer part is always exact.

Parameters:

other – The divisor

Returns:

Result of division

number operator%(const number &other) const

Modulo operator.

Returns NaN if either operand is NaN, if the divisor is zero, or if either operand is not an integer.

Parameters:

other – The divisor for modulo operation

Returns:

Remainder after division

number &operator+=(const number &other)

Addition assignment operator.

Parameters:

other – The number to add

Returns:

Reference to this number after addition

number &operator-=(const number &other)

Subtraction assignment operator.

Parameters:

other – The number to subtract

Returns:

Reference to this number after subtraction

number &operator*=(const number &other)

Multiplication assignment operator.

Parameters:

other – The number to multiply by

Returns:

Reference to this number after multiplication

number &operator/=(const number &other)

Division assignment operator.

Parameters:

other – The divisor

Returns:

Reference to this number after division

number &operator%=(const number &other)

Modulo assignment operator.

Parameters:

other – The divisor for modulo operation

Returns:

Reference to this number after modulo operation

Public Static Functions

static number nan()

Create a NaN (Not a Number) value.

Use this to create NaN values for error conditions or to test against NaN using is_nan().

Returns:

A number representing NaN

class storage

Public Functions

storage() = default
inline storage(const std::string &s)
inline storage(const std::string &s, bool floating_point)
inline void assign(const std::string &s)

Public Members

std::string number = {"0"}
bool floating_point = false

The number class provides arbitrary precision numeric values. Addition, subtraction and multiplication are exact, and so is a quotient that terminates within 4096 digits; any other quotient keeps 34 significant digits, and the digits after them are truncated:

#include <iostream>
#include <string>

#include <dross/type/number.h>

dross::number n1(42);
dross::number n2("3.14159265358979323846");
dross::number n3 = n1 + n2;

// Seamless string conversion
std::string result = n3;           // Direct conversion
std::cout << result << std::endl;  // Via std::string
std::cout << n3 << std::endl;      // Direct output

string

class string

UTF-8 string class with value semantics.

The string class holds text as UTF-8 bytes and hands those bytes back unchanged. Its operations work on the bytes rather than on characters: length() counts bytes, and the prefix and equality comparisons compare bytes, so they can split or match across a multi-byte character. Nothing validates the content, so the class neither repairs nor rejects malformed UTF-8.

Key features:

  • Byte-oriented operations over UTF-8 content

  • UTF-8 internal encoding

  • Value semantics (copyable and assignable)

  • Safe string manipulation methods

  • Efficient string concatenation

  • Thread-safe for read operations

Performance characteristics:

  • Construction: O(n) where n is the string length

  • Comparison: O(min(m,n)) for most cases

  • Concatenation: O(m+n) where m and n are string lengths

  • Memory usage: Proportional to UTF-8 encoded length

Thread safety:

  • Const operations are thread-safe

  • Non-const operations require external synchronization

// Basic usage
dross::string greeting{"Hello, 世界!"};
dross::string name{"Alice"};

// Length is in bytes: 14 here, for 10 characters
size_t len = greeting.length();

// Concatenation is in place; there is no operator+
if (greeting.starts_with("Hello")) {
    greeting += " ";
    greeting += name;
}

// Comparison
if (greeting == "Hello, 世界! Alice") {
// Handle match
}

// Conversion
std::string std_str = greeting;

Public Functions

string()

Default constructor creating an empty string.

string(const string &other)

Copy constructor.

Parameters:

other – The string to copy from

string(string &&other) noexcept

Move constructor.

Parameters:

other – The string to move from

string(const std::string &str)

Construct from std::string.

The bytes are stored as given. Nothing validates them, so content that is not valid UTF-8 is kept and returned unchanged, and the byte-oriented operations simply operate on it.

Parameters:

str – The std::string to copy from

string(const char *str)

Construct from C-style string.

The bytes are stored as given, with no UTF-8 validation.

Parameters:

str – Null-terminated C-style string

~string()

Destructor.

bool starts_with(const std::string &prefix) const

Check if the string starts with a given prefix.

The comparison is byte-wise over the UTF-8 content and case-sensitive, so a prefix that ends mid-character still matches.

Parameters:

prefix – The prefix to check for

Returns:

true if the string starts with the prefix, false otherwise

size_t length() const

Get the length of the string in bytes.

Counts UTF-8 code units, not code points: a string holding non-ASCII characters reports more than the number of characters it contains.

Returns:

The number of bytes in the UTF-8 encoded content

bool equals(const string &other) const

Test equality with another string.

Parameters:

other – The string to compare with

Returns:

true if both strings hold the same bytes

bool equals(const std::string &str) const

Test equality with a std::string.

Parameters:

str – The std::string to compare with

Returns:

true if the strings are equal

bool equals(const char *str) const

Test equality with a C-style string.

Parameters:

str – The C-style string to compare with

Returns:

true if the strings are equal

bool operator==(const string &other) const

Equality comparison operator.

Parameters:

other – The string to compare with

Returns:

true if strings are equal

bool operator!=(const string &other) const

Inequality comparison operator.

Parameters:

other – The string to compare with

Returns:

true if strings are not equal

bool operator==(const std::string &str) const

Equality comparison with std::string.

Parameters:

str – The std::string to compare with

Returns:

true if strings are equal

bool operator!=(const std::string &str) const

Inequality comparison with std::string.

Parameters:

str – The std::string to compare with

Returns:

true if strings are not equal

bool operator==(const char *str) const

Equality comparison with C-style string.

Parameters:

str – The C-style string to compare with

Returns:

true if strings are equal

bool operator!=(const char *str) const

Inequality comparison with C-style string.

Parameters:

str – The C-style string to compare with

Returns:

true if strings are not equal

string &operator=(const string &other)

Copy assignment operator.

Parameters:

other – The string to assign from

Returns:

Reference to this string

string &operator=(string &&other) noexcept

Move assignment operator.

Parameters:

other – The string to move from

Returns:

Reference to this string

string &operator=(const std::string &str)

Assignment from std::string.

Parameters:

str – The std::string to assign from

Returns:

Reference to this string

string &operator=(const char *str)

Assignment from C-style string.

Parameters:

str – The C-style string to assign from

Returns:

Reference to this string

string &operator+=(const string &other)

Append another string to this string.

Parameters:

other – The string to append

Returns:

Reference to this string after concatenation

string &operator+=(const std::string &str)

Append a std::string to this string.

Parameters:

str – The std::string to append

Returns:

Reference to this string after concatenation

string &operator+=(const char *str)

Append a C-style string to this string.

Parameters:

str – The C-style string to append

Returns:

Reference to this string after concatenation

operator std::string() const

Convert to std::string.

The returned string maintains the UTF-8 encoding and can be used with standard library string operations.

Returns:

std::string representation with UTF-8 encoding

class storage

Public Functions

storage() = default
inline storage(const std::string &s)

Public Members

std::string buffer

The string class holds text as UTF-8 bytes; its length and comparison operations work on those bytes:

#include <iostream>
#include <string>

#include <dross/type/string.h>

dross::string s1("Hello");
dross::string s2(" World");

// Concatenation is in place; there is no operator+
s1 += s2;

// The buffer is UTF-8 and length() reports its size in bytes, so this is
// 11 only because the content is ASCII
std::cout << s1.length() << std::endl;  // 11

// Seamless conversion to std::string, which is what streams accept
std::string result = s1;                // "Hello World"
std::cout << result << std::endl;

timestamp

class timestamp

Timestamp handling with modern timezone support.

The timestamp class provides comprehensive date and time operations with full timezone support using type-safe timezone objects. It uses std::chrono internally for high precision time calculations while providing a user-friendly API for common operations. This class is designed as a general-purpose timestamp type suitable for configuration files, data serialization, logging, scheduling, and any application requiring robust timestamp handling.

Key features:

  • ISO 8601 and RFC 3339 format support

  • Type-safe timezone operations with timezone class

  • Integration with std::chrono for duration arithmetic, kept within the years 0 to 9999 that parsing accepts

  • Value semantics (copyable and assignable, without allocating)

  • Thread-safe for read operations

  • A date alone is read as midnight and written in full

  • Factory methods for common timestamp patterns

  • Compositional design with separate date and time components

Supported timestamp formats (ISO 8601 standard):

  • Offset timestamp: 2024-01-21T15:30:00+09:00

  • Fractional seconds: 2024-01-21T15:30:00.5+09:00 (kept to nanoseconds)

  • UTC timestamp: 2024-01-21T15:30:00Z

  • Timestamp without an offset, read as UTC: 2024-01-21T15:30:00

  • Date, read as midnight UTC: 2024-01-21

Performance characteristics:

  • Construction: O(1) for time_point, O(n) for string parsing

  • Arithmetic operations: O(1) using std::chrono

  • Comparisons: O(1)

  • Formatting: O(n) where n is the output string length

Thread safety:

  • Const operations are thread-safe

  • Non-const operations require external synchronization

// Basic usage with timezone objects
dross::timestamp now = dross::timestamp::now();
dross::timestamp meeting(2024, 1, 21, 15, 30, 0, dross::timezone::offset(9)); // +09:00
dross::timestamp utc_meeting(2024, 1, 21, 6, 30, 0, dross::timezone::utc());  // UTC

// Date-only timestamps using constructor
dross::timestamp birthday(1990, 12, 25);  // Date only (time defaults to 00:00:00)

// String parsing
dross::timestamp iso_meeting("2024-01-21T15:30:00+09:00");

// Duration arithmetic
dross::timestamp tomorrow = now + std::chrono::hours(24);
auto age = now - birthday;

// Accessing components
std::cout << "Year: " << meeting.date().year() << std::endl;
std::cout << "Hour: " << meeting.time().hour() << std::endl;
std::cout << "Timezone: " << meeting.timezone().format() << std::endl;

// Formatting
std::string iso_str = meeting.format(dross::timestamp::format_type::iso8601);
std::string custom = meeting.format("%Y-%m-%d %H:%M");

// Conversion to std::chrono
auto time_point = static_cast<std::chrono::system_clock::time_point>(now);

Public Types

enum class format_type

Format options for timestamp string representation.

Values:

enumerator iso8601
enumerator rfc3339

Public Functions

timestamp()

Default constructor creating epoch time (1970-01-01T00:00:00Z).

timestamp(const std::chrono::system_clock::time_point &tp) noexcept

Construct from std::chrono::system_clock::time_point.

The resulting timestamp will be in UTC (no timezone offset). A time point that from_time_point() rejects results in the nearer of the first and the last nanosecond of the years 0 to 9999, so it does not order on the wrong side of another timestamp.

Parameters:

tp – The time point to construct from

timestamp(const std::string &iso8601_str)

Construct from ISO 8601 string.

Supports various ISO 8601 formats:

  • 2024-01-21T15:30:00+09:00 (offset timestamp)

  • 2024-01-21T15:30:00 (no offset, read as UTC)

  • 2024-01-21 (date only, read as midnight UTC)

Input that from_string() rejects results in epoch time.

Parameters:

iso8601_str – The ISO 8601 formatted string

timestamp(const char *iso8601_str)

Construct from const char*.

Input that from_string() rejects results in epoch time.

Parameters:

iso8601_str – The ISO 8601 formatted string

timestamp(int year, int month, int day, int hour = 0, int minute = 0, int second = 0)

Construct from individual date and time components.

The timezone is UTC. Components that from_components() rejects result in epoch time.

Parameters:
  • year – Year (0-9999)

  • month – Month (1-12)

  • day – Day of month (1 to the last day of the month)

  • hour – Hour (0-23, default 0)

  • minute – Minute (0-59, default 0)

  • second – Second (0-59, default 0)

timestamp(int year, int month, int day, int hour, int minute, int second, const timezone &tz)

Construct from individual date and time components with timezone.

Components that from_components() rejects result in epoch time.

Parameters:
  • year – Year (0-9999)

  • month – Month (1-12)

  • day – Day of month (1 to the last day of the month)

  • hour – Hour (0-23)

  • minute – Minute (0-59)

  • second – Second (0-59)

  • tz – Timezone information

std::optional<std::chrono::system_clock::time_point> to_time_point() const noexcept

Convert to std::chrono::system_clock::time_point, reporting a timestamp outside the range of the clock.

Comparison and adding or subtracting a duration work for every year from 0 to 9999, but system_clock reaches only about 292 years either side of 1970 where its duration counts nanoseconds, and so does a difference between two timestamps: see duration_since().

Returns:

The time point (always in UTC), rounded down to a tick of the clock, or nullopt if it is outside the range of system_clock

operator std::chrono::system_clock::time_point() const noexcept

Implicit conversion to std::chrono::system_clock::time_point.

A timestamp that to_time_point() rejects results in the nearer of time_point::min() and time_point::max(), so it does not order on the wrong side of another time point.

Returns:

The time point (always in UTC), rounded down to a tick of the clock

operator std::string() const

Implicit conversion to std::string in ISO 8601 format.

Always writes the date, the time and the offset, so the string reads back as the same timestamp for any year from 0 to 9999, which arithmetic keeps.

Returns:

ISO 8601 formatted string representation

std::strong_ordering operator<=>(const timestamp &other) const

Three-way comparison operator.

Parameters:

other – The timestamp to compare with

Returns:

Comparison result (strong ordering)

bool operator==(const timestamp &other) const

Equality comparison operator.

Parameters:

other – The timestamp to compare with

Returns:

True if the timestamps represent the same moment in time

timestamp operator+(const std::chrono::minutes &duration) const

Add a duration to this timestamp.

Parameters:

duration – The duration to add (in minutes)

Throws:

std::out_of_range – if the result is outside the years 0 to 9999; add() and subtract() report that as nullopt instead

Returns:

New timestamp with the duration added

timestamp operator-(const std::chrono::minutes &duration) const

Subtract a duration from this timestamp.

Parameters:

duration – The duration to subtract (in minutes)

Throws:

std::out_of_range – if the result is outside the years 0 to 9999; add() and subtract() report that as nullopt instead

Returns:

New timestamp with the duration subtracted

timestamp operator+(const std::chrono::hours &duration) const

Add hours to this timestamp.

Parameters:

duration – The duration to add (in hours)

Throws:

std::out_of_range – if the result is outside the years 0 to 9999; add() and subtract() report that as nullopt instead

Returns:

New timestamp with the duration added

timestamp operator-(const std::chrono::hours &duration) const

Subtract hours from this timestamp.

Parameters:

duration – The duration to subtract (in hours)

Throws:

std::out_of_range – if the result is outside the years 0 to 9999; add() and subtract() report that as nullopt instead

Returns:

New timestamp with the duration subtracted

timestamp operator+(const std::chrono::seconds &duration) const

Add seconds to this timestamp.

Parameters:

duration – The duration to add (in seconds)

Throws:

std::out_of_range – if the result is outside the years 0 to 9999; add() and subtract() report that as nullopt instead

Returns:

New timestamp with the duration added

timestamp operator-(const std::chrono::seconds &duration) const

Subtract seconds from this timestamp.

Parameters:

duration – The duration to subtract (in seconds)

Throws:

std::out_of_range – if the result is outside the years 0 to 9999; add() and subtract() report that as nullopt instead

Returns:

New timestamp with the duration subtracted

std::optional<timestamp> add(std::chrono::seconds duration) const

Add a duration, reporting a result outside the years 0 to 9999.

The years are those parsing accepts and the string writes, so the result always reads back.

Parameters:

duration – The duration to add, which minutes and hours convert to

Returns:

The timestamp with the duration added, or nullopt if its year, in this timestamp’s offset, is outside 0 to 9999

std::optional<timestamp> subtract(std::chrono::seconds duration) const

Subtract a duration, reporting a result outside the years 0 to 9999.

Parameters:

duration – The duration to subtract, which minutes and hours convert to

Returns:

The timestamp with the duration subtracted, or nullopt if its year, in this timestamp’s offset, is outside 0 to 9999

std::optional<std::chrono::system_clock::duration> duration_since(const timestamp &other) const noexcept

Calculate the duration from another timestamp, reporting one that system_clock::duration cannot hold.

system_clock::duration holds about 292 years where it counts nanoseconds. A conversion to time_point rounds down instead, so subtracting the converted time points can differ by a tick.

Parameters:

other – The other timestamp

Returns:

Duration from other to this timestamp, rounded toward zero to a tick of the clock, or nullopt if system_clock::duration cannot hold it

std::chrono::system_clock::duration operator-(const timestamp &other) const noexcept

Calculate the duration between two timestamps.

A duration that duration_since() rejects results in the nearer of duration::min() and duration::max(). Negating duration::min() overflows, as it has no positive counterpart, so take a difference that may be outside the duration with duration_since().

Parameters:

other – The other timestamp

Returns:

Duration from other to this timestamp, rounded toward zero to a tick of the clock

std::string format(format_type fmt = format_type::iso8601) const

Format the timestamp using predefined format.

Parameters:

fmt – The format to use

Returns:

Formatted string representation

std::string format(const std::string &custom_format) const

Format the timestamp using custom format string.

Y and F write the year as the ISO 8601 form does: in four digits, so the year 999 is “0999”. The other conversions are those of std::put_time.

Parameters:

custom_format – strftime-style format string

Returns:

Formatted string representation

const date_part &date() const noexcept

Get the date component.

Returns:

Reference to the date part

const time_part &time() const noexcept

Get the time component.

Returns:

Reference to the time part (always present, defaults to 00:00:00)

const dross::timezone &timezone() const noexcept

Get the timezone information.

Returns:

Reference to the timezone (always present, defaults to UTC)

Public Static Functions

static timestamp now()

Create a timestamp representing the current moment.

Returns:

timestamp object set to current system time in UTC

static std::optional<timestamp> from_string(const std::string &iso8601_str)

Parse an ISO 8601 string, reporting input it cannot represent.

Accepts the forms listed for the string constructor. Fractional seconds are kept to the nanosecond; further digits are dropped.

Parameters:

iso8601_str – The ISO 8601 formatted string

Returns:

The timestamp, or nullopt if the string does not parse, names a date or time that does not exist, or has an offset outside -23:59..+23:59

static std::optional<timestamp> from_components(int year, int month, int day, int hour = 0, int minute = 0, int second = 0, const dross::timezone &tz = dross::timezone::utc())

Build a timestamp from components, reporting values out of range.

Parameters:
  • year – Year (0-9999)

  • month – Month (1-12)

  • day – Day of month (1 to the last day of the month)

  • hour – Hour (0-23)

  • minute – Minute (0-59)

  • second – Second (0-59)

  • tz – Timezone information

Returns:

The timestamp, or nullopt if any component is out of range

static std::optional<timestamp> from_time_point(const std::chrono::system_clock::time_point &tp) noexcept

Build a timestamp from a time point, reporting one out of range.

system_clock reaches past those years where its duration counts microseconds. A timestamp near their ends can be outside them as a time point, when its offset moves it there. A time_point with a coarser duration, such as std::chrono::sys_days, converts before the call, and can overflow there where the duration of system_clock counts nanoseconds.

Parameters:

tp – The time point, read as UTC

Returns:

The timestamp, or nullopt if the time point is outside the years 0 to 9999

class date_part

Date component of a timestamp.

This class represents the date part of a timestamp and can only be constructed through the timestamp class. It provides read-only access to year, month, and day components.

Public Functions

int year() const noexcept

Get the year component.

Returns:

Year (e.g., 2024)

int month() const noexcept

Get the month component.

Returns:

Month (1-12)

int day() const noexcept

Get the day component.

Returns:

Day of month (1-31)

operator std::string() const

Implicit conversion to std::string in ISO 8601 format.

Returns:

Date string in format “YYYY-MM-DD”

operator std::chrono::year_month_day() const noexcept

Conversion to std::chrono::year_month_day.

Returns:

The year_month_day representation

std::strong_ordering operator<=>(const date_part &other) const noexcept

Three-way comparison operator.

Parameters:

other – The date to compare with

Returns:

Comparison result (strong ordering)

bool operator==(const date_part &other) const noexcept

Equality comparison operator.

Parameters:

other – The date to compare with

Returns:

True if the dates are equal

class time_part

Time component of a timestamp.

This class represents the time part of a timestamp and can only be constructed through the timestamp class. It provides read-only access to hour, minute, and second components with nanosecond precision.

Public Functions

int hour() const noexcept

Get the hour component.

Returns:

Hour (0-23)

int minute() const noexcept

Get the minute component.

Returns:

Minute (0-59)

int second() const noexcept

Get the second component.

Returns:

Second (0-59)

int total_seconds() const noexcept

Get the total seconds since midnight.

Returns:

Seconds since 00:00:00

operator std::string() const

Implicit conversion to std::string in ISO 8601 format.

Returns:

Time string in format “HH:MM:SS”

std::chrono::hh_mm_ss<std::chrono::nanoseconds> to_hh_mm_ss() const noexcept

Conversion to std::chrono::hh_mm_ss.

Returns:

The hh_mm_ss representation

std::strong_ordering operator<=>(const time_part &other) const noexcept

Three-way comparison operator.

Parameters:

other – The time to compare with

Returns:

Comparison result (strong ordering)

bool operator==(const time_part &other) const noexcept

Equality comparison operator.

Parameters:

other – The time to compare with

Returns:

True if the times are equal

Public Static Attributes

static const time_part midnight

Static midnight constant.

The timestamp class provides comprehensive date and time handling with timezone support:

#include <chrono>
#include <iostream>
#include <optional>
#include <string>

#include <dross/type/timestamp.h>
#include <dross/type/timezone.h>

// Construction from components, with a timezone object
dross::timestamp meeting{2024, 1, 21, 15, 30, 0, dross::timezone::offset(9)}; // +09:00
dross::timestamp utc_meeting{2024, 1, 21, 6, 30, 0, dross::timezone::utc()}; // UTC

// Date-only timestamps (time defaults to 00:00:00, timezone to UTC)
dross::timestamp birthday{1990, 12, 25};

// Construction from ISO 8601 strings. Each of these compares equal to the
// component-built timestamp above it.
dross::timestamp offset_time{"2024-01-21T15:30:00+09:00"};
dross::timestamp utc_time{"2024-01-21T06:30:00Z"};
dross::timestamp date_only{"1990-12-25"};
std::cout << (offset_time == meeting) << " " << (utc_time == utc_meeting)
          << " " << (date_only == birthday) << std::endl;  // 1 1 1

// Current time
dross::timestamp now = dross::timestamp::now();

// Duration arithmetic
auto tomorrow = now + std::chrono::hours(24);
auto next_week = now + std::chrono::hours(24 * 7);
std::cout << tomorrow << " " << next_week << std::endl;

// Conversion to std::chrono, reporting what system_clock cannot hold.
// Where it counts nanoseconds, it reaches the years 1677 to 2262.
std::optional<std::chrono::system_clock::time_point> tp = meeting.to_time_point();
std::optional<std::chrono::system_clock::duration> since = now.duration_since(meeting);
std::cout << tp.has_value() << " " << since.has_value() << std::endl;  // 1 1

// Formatting
std::string iso_str = meeting.format();  // ISO 8601 format
std::string custom = meeting.format("%Y-%m-%d %H:%M");
std::cout << iso_str << " / " << custom << std::endl;

// Component access (always present)
const auto& date_part = meeting.date();
int year = date_part.year();
int month = date_part.month();
int day = date_part.day();

const auto& time_part = meeting.time(); // Always present (default 00:00:00)
int hour = time_part.hour();
int minute = time_part.minute();
int second = time_part.second();

std::cout << year << "/" << month << "/" << day << " "
          << hour << ":" << minute << ":" << second << std::endl;

const auto& tz = meeting.timezone(); // Always present (default UTC)
auto offset_minutes = tz.offset(); // Returns std::chrono::minutes
std::cout << offset_minutes.count() << " minutes" << std::endl;

// Timezone operations
if (meeting.timezone().is_utc()) {
    std::cout << "Meeting is in UTC" << std::endl;
}
std::cout << "Timezone offset: " << meeting.timezone().format() << std::endl;

// Seamless string conversion
std::string meeting_str = meeting;       // "2024-01-21T15:30:00+09:00"
std::cout << meeting_str << std::endl;
std::cout << utc_meeting << " " << birthday << std::endl;  // Direct output

timezone

class timezone

Timezone representation with offset and formatting support.

The timezone class provides a type-safe and intuitive way to handle timezone information in datetime objects. It supports UTC and fixed offsets with clear, readable API.

Key features:

  • Type-safe timezone representation

  • Clear factory methods for common timezone types

  • ISO 8601 compliant formatting

  • Integration with timestamp class

  • Value semantics (copyable and assignable, without allocating)

Supported timezone types:

  • UTC: Coordinated Universal Time (offset +00:00)

  • Fixed offset: Custom offset from UTC in hours/minutes

// Factory methods
auto utc = dross::timezone::utc();
auto jst = dross::timezone::offset(9);                 // +09:00
auto pdt = dross::timezone::offset(-7, 0);             // -07:00
auto custom = dross::timezone::from_string("+05:30");  // India Standard Time

// Usage with timestamp
dross::timestamp ts(2024, 1, 21, 15, 30, 0, dross::timezone::offset(9));

Public Functions

timezone()

Default constructor creating UTC timezone.

bool is_utc() const noexcept

Check if this is UTC timezone.

Returns:

True if timezone represents UTC (+00:00)

std::chrono::minutes offset() const noexcept

Get the timezone offset from UTC.

Positive values indicate east of UTC, negative values indicate west of UTC. Use std::chrono::duration_cast to convert to hours if needed.

Returns:

Offset as chrono::minutes (UTC=0min, JST=540min, PST=-480min)

std::string format() const

Format timezone as ISO 8601 offset string.

Returns:

Formatted string (e.g., “+09:00”, “-05:30”, “Z” for UTC)

operator std::string() const

Implicit conversion to std::string.

Returns:

ISO 8601 formatted timezone string

bool operator==(const timezone &other) const noexcept

Equality comparison.

Parameters:

other – The timezone to compare with

Returns:

True if timezones are equivalent

std::strong_ordering operator<=>(const timezone &other) const noexcept

Three-way comparison operator.

Parameters:

other – The timezone to compare with

Returns:

Comparison result based on offset

Public Static Functions

static timezone utc()

Create UTC timezone (+00:00).

Returns:

timezone representing UTC

static timezone offset(int hours, int minutes = 0)

Create timezone with fixed offset.

Positive values are east of UTC, negative values are west of UTC. The minutes parameter is always added to the absolute value of hours.

Parameters:
  • hours – Offset hours from UTC (-23 to +23)

  • minutes – Offset minutes from UTC (0 to 59)

Returns:

timezone with specified offset, or UTC if either is out of range

static timezone offset(std::chrono::minutes offset_duration)

Create timezone with chrono-based offset.

Positive values are east of UTC, negative values are west of UTC.

auto jst = dross::timezone::offset(std::chrono::minutes(540));  // +09:00
auto ist = dross::timezone::offset(std::chrono::hours(5) +
                                   std::chrono::minutes(30));  // +05:30

Parameters:

offset_duration – Offset from UTC as chrono::minutes

Returns:

timezone with specified offset, or UTC if it is outside -23:59..+23:59

static std::optional<timezone> from_string(const std::string &tz_str)

Parse timezone from ISO 8601 offset string.

auto tz = dross::timezone::from_string("+09:00");
if (tz) {
    std::cout << "Parsed: " << tz->format() << std::endl;
} else {
    std::cout << "Invalid timezone string" << std::endl;
}

Parameters:

tz_str – Timezone string (e.g., “+09:00”, “-05:30”, “Z”)

Returns:

optional timezone parsed from string, nullopt if parsing fails or the offset is outside -23:59..+23:59

The timezone class provides type-safe timezone representation with modern chrono integration:

#include <chrono>
#include <iostream>
#include <string>

#include <dross/type/timezone.h>

// Factory methods for common timezones
auto utc = dross::timezone::utc();           // UTC (+00:00)
auto jst = dross::timezone::offset(9);       // Japan Standard Time (+09:00)
auto pdt = dross::timezone::offset(-7, 0);   // Pacific Daylight Time (-07:00)
auto ist = dross::timezone::offset(5, 30);   // India Standard Time (+05:30)

// Chrono-based factory method for type safety
auto cet = dross::timezone::offset(std::chrono::minutes(60)); // Central European Time (+01:00)
auto jst_chrono = dross::timezone::offset(std::chrono::minutes(540)); // +09:00
std::cout << pdt << " " << ist << " " << cet << " " << jst_chrono << std::endl;

// Parse from ISO 8601 strings (returns optional for error handling)
if (auto parsed_utc = dross::timezone::from_string("Z")) {
    std::cout << "Parsed UTC: " << parsed_utc->format() << std::endl;
}
if (auto parsed_offset = dross::timezone::from_string("+09:00")) {
    std::cout << "Parsed offset: " << parsed_offset->format() << std::endl;
}

// Invalid strings return nullopt
auto invalid = dross::timezone::from_string("invalid");
if (!invalid) {
    std::cout << "Failed to parse invalid timezone string" << std::endl;
}

// Timezone operations
if (jst.is_utc()) {
    std::cout << "This is UTC" << std::endl;
}

// Get offset as std::chrono::minutes for type safety
auto minutes = jst.offset(); // std::chrono::minutes (540 minutes)
std::cout << "Offset: " << minutes.count() << " minutes" << std::endl;

// Formatting and string conversion
std::string utc_str = utc.format();     // "Z"
std::string jst_str = jst.format();     // "+09:00"
std::cout << utc_str << " " << jst_str << std::endl;

// Implicit string conversion
std::string tz_string = jst;            // "+09:00"
std::cout << "Timezone: " << tz_string << " " << jst << std::endl;

array

class array

Dynamic array container for value objects with iterator support.

The array class provides a dynamic container that can hold any number of value objects. It supports standard container operations like iteration, indexing, and modification, making it suitable for building complex data structures and APIs that need flexible arrays.

Key features:

  • Dynamic sizing with automatic memory management

  • Value semantics (copyable and assignable)

  • Range-based for loop support through iterators

  • Type-safe element access

  • Efficient append and removal operations

  • Thread-safe for read operations

Performance characteristics:

  • Element access: O(1) by index

  • Append operations: Amortized O(1)

  • Search operations: O(n) linear scan

  • Memory usage: Proportional to number of elements

Thread safety:

  • Const operations are thread-safe

  • Non-const operations require external synchronization

// Basic usage
dross::array numbers = {dross::value{1}, dross::value{2}, dross::value{3}};

// Adding elements
numbers.append(dross::value{4});

// Iteration
for (const auto& item : numbers) {
// Process each value
}

// Access by index
dross::value& first = numbers[0];

// Search and removal
size_t pos = numbers.index_of(dross::value{2});
numbers.remove(dross::value{2});

Public Functions

array()

Default constructor creating an empty array.

array(const array &other)

Copy constructor.

Parameters:

other – The array to copy from

array(array &&other) noexcept

Move constructor.

Parameters:

other – The array to move from

array(const std::initializer_list<value> &values)

Construct from initializer list.

Allows convenient array creation with brace initialization.

Parameters:

values – Initializer list of values to populate the array

~array()

Destructor.

bool empty() const

Check if the array is empty.

Returns:

true if the array contains no elements, false otherwise

size_t length() const

Get the number of elements in the array.

Returns:

The number of elements currently stored

bool equals(const array &other) const

Test equality with another array.

Parameters:

other – The array to compare with

Returns:

true if both arrays contain the same elements in the same order

size_t index_of(const value &val) const

Find the index of the first occurrence of a value.

Parameters:

val – The value to search for

Returns:

The index of the first occurrence, or SIZE_MAX if not found

value &value_at(const size_t index)

Get a reference to the value at the specified index.

Parameters:

index – The index to access

Throws:

std::out_of_range – if index is out of bounds

Returns:

Reference to the value at the given index

const value &value_at(const size_t index) const

Get a const reference to the value at the specified index.

Parameters:

index – The index to access

Throws:

std::out_of_range – if index is out of bounds

Returns:

Const reference to the value at the given index

void append(const value &val)

Append a value to the end of the array.

Parameters:

val – The value to append

void append(value &&val)

Append a value to the end of the array, taking its contents.

Parameters:

val – The value to append

void append(iterator first, iterator last)

Append a range of values from iterators.

Parameters:
  • first – Iterator pointing to the beginning of the range

  • last – Iterator pointing to the end of the range

void append(const_iterator first, const_iterator last)

Append a range of values from const iterators.

Parameters:
  • first – Const iterator pointing to the beginning of the range

  • last – Const iterator pointing to the end of the range

void remove(const value &val)

Remove every occurrence of a value from the array.

The remaining elements keep their order. If the value is not found, the array remains unchanged.

Parameters:

val – The value to remove

iterator begin()

Get an iterator to the beginning of the array.

Returns:

Iterator pointing to the first element

iterator end()

Get an iterator to the end of the array.

Returns:

Iterator pointing past the last element

const_iterator begin() const

Get a const iterator to the beginning of the array.

Returns:

Const iterator pointing to the first element

const_iterator end() const

Get a const iterator to the end of the array.

Returns:

Const iterator pointing past the last element

const_iterator cbegin() const

Get a const iterator to the beginning of the array.

Returns:

Const iterator pointing to the first element

const_iterator cend() const

Get a const iterator to the end of the array.

Returns:

Const iterator pointing past the last element

bool operator==(const array &other) const

Equality comparison operator.

Parameters:

other – The array to compare with

Returns:

true if arrays are equal

bool operator!=(const array &other) const

Inequality comparison operator.

Parameters:

other – The array to compare with

Returns:

true if arrays are not equal

array &operator=(const array &other)

Copy assignment operator.

Parameters:

other – The array to assign from

Returns:

Reference to this array

array &operator=(array &&other) noexcept

Move assignment operator.

Parameters:

other – The array to move from

Returns:

Reference to this array

const value &operator[](const size_t index) const &

Access element by index (const version).

Parameters:

index – The index to access

Throws:

std::out_of_range – if index is out of bounds

Returns:

Const reference to the value at the given index

value &operator[](const size_t index) &

Access element by index (non-const version).

Parameters:

index – The index to access

Throws:

std::out_of_range – if index is out of bounds

Returns:

Reference to the value at the given index

class const_iterator

Const forward iterator for array elements.

Provides read-only iterator interface for traversing array elements. Supports range-based for loops and standard library algorithms.

Public Types

using value_type = value
using difference_type = std::ptrdiff_t
using pointer = const value*
using reference = const value&
using iterator_category = std::forward_iterator_tag

Public Functions

const_iterator()

Default constructor. Default-constructed iterators compare equal.

const_iterator(const const_iterator &other)

Copy constructor.

Parameters:

other – The const_iterator to copy from

const_iterator(const iterator &other)

Converting constructor from a mutable iterator.

Parameters:

other – The iterator to convert, pointing to the same element

const_iterator &operator=(const const_iterator &other)

Copy assignment operator.

Parameters:

other – The const_iterator to copy from

Returns:

Reference to this iterator

~const_iterator()

Destructor.

const_iterator &operator++()

Pre-increment operator.

Returns:

Reference to this iterator after incrementing

const_iterator operator++(int)

Post-increment operator.

Returns:

Copy of this iterator before incrementing

const value &operator*() const

Dereference operator.

Returns:

Const reference to the current element

Friends

friend bool operator==(const const_iterator &lhs, const const_iterator &rhs)

Equality comparison operator.

Either side can be an iterator, which converts to a const_iterator. != is derived from it.

Parameters:
Returns:

true if iterators point to the same element

class impl

Public Functions

inline impl(std::vector<value>::const_iterator i)

Public Members

std::vector<value>::const_iterator cursor
class iterator

Forward iterator for array elements.

Provides standard iterator interface for traversing array elements. Supports range-based for loops and standard library algorithms.

Public Types

using value_type = value
using difference_type = std::ptrdiff_t
using pointer = value*
using reference = value&
using iterator_category = std::forward_iterator_tag

Public Functions

iterator()

Default constructor. Default-constructed iterators compare equal.

iterator(const iterator &other)

Copy constructor.

Parameters:

other – The iterator to copy from

iterator &operator=(const iterator &other)

Copy assignment operator.

Parameters:

other – The iterator to copy from

Returns:

Reference to this iterator

~iterator()

Destructor.

iterator &operator++()

Pre-increment operator.

Returns:

Reference to this iterator after incrementing

iterator operator++(int)

Post-increment operator.

Returns:

Copy of this iterator before incrementing

value &operator*() const

Dereference operator.

Returns:

Reference to the current element

Friends

friend bool operator==(const iterator &lhs, const iterator &rhs)

Equality comparison operator. != is derived from it.

Parameters:
  • lhs – The iterator to compare

  • rhs – The iterator to compare with

Returns:

true if iterators point to the same element

class impl

Public Functions

inline impl(std::vector<value>::iterator i)

Public Members

std::vector<value>::iterator cursor
class storage

Public Functions

storage() = default
inline storage(const std::initializer_list<value> &list)

Public Members

std::vector<value> contents

The array class provides a dynamic array of values:

#include <iostream>
#include <string>

#include <dross/type/array.h>
#include <dross/type/value.h>

dross::array arr;
arr.append(42);
arr.append("hello");
arr.append(dross::array{1, 2, 3});

std::cout << "Length: " << arr.length() << std::endl;  // 3

// Range-based for loop. value itself has no operator<<, so dispatch on
// the contained type and print that.
for (const auto& val : arr) {
    if (val.is<dross::number>()) {
        std::cout << val.as<dross::number>() << std::endl;
    } else if (val.is<dross::string>()) {
        std::string text = val.as<dross::string>();
        std::cout << text << std::endl;
    } else if (val.is<dross::array>()) {
        std::cout << "array of " << val.as<dross::array>().length()
                  << std::endl;
    }
}

dictionary

class dictionary

Key-value container for string keys and value objects.

The dictionary class provides an associative container that maps string keys to value objects. It supports standard dictionary operations like key lookup, insertion, and iteration, making it suitable for configuration data, JSON-like structures, and dynamic object representations.

Key features:

  • String-to-value mapping with efficient lookup

  • Value semantics (copyable and assignable)

  • Iterator support for key-value traversal

  • Dynamic sizing with automatic memory management

  • Type-safe element access

  • Thread-safe for read operations

Performance characteristics:

  • Key lookup: O(log n) or better depending on implementation

  • Insertion: O(log n) or better

  • Iteration: O(n) to visit all elements

  • Memory usage: Proportional to number of key-value pairs

Thread safety:

  • Const operations are thread-safe

  • Non-const operations require external synchronization

// Basic usage
dross::dictionary config;
config["host"] = dross::value{dross::string{"localhost"}};
config["port"] = dross::value{dross::number{8080}};
config["ssl"] = dross::value{dross::string{"true"}};

// Key checking and access
if (config.contains("timeout")) {
auto timeout = config["timeout"];
}

// Iteration
for (const auto& [key, val] : config) {
// Process each key-value pair
}

// Size checking
if (!config.empty()) {
size_t count = config.size();
}

Public Functions

dictionary()

Default constructor creating an empty dictionary.

dictionary(const dictionary &other)

Copy constructor.

Parameters:

other – The dictionary to copy from

dictionary(dictionary &&other) noexcept

Move constructor.

Parameters:

other – The dictionary to move from

~dictionary()

Destructor.

bool equals(const dictionary &other) const

Test equality with another dictionary.

Parameters:

other – The dictionary to compare with

Returns:

true if both dictionaries contain the same key-value pairs

bool contains(const std::string &key) const

Check if a key exists in the dictionary.

Parameters:

key – The key to search for

Returns:

true if the key exists, false otherwise

bool empty() const

Check if the dictionary is empty.

Returns:

true if the dictionary contains no key-value pairs

size_t size() const

Get the number of key-value pairs in the dictionary.

Returns:

The number of entries currently stored

bool operator==(const dictionary &other) const

Equality comparison operator.

Parameters:

other – The dictionary to compare with

Returns:

true if dictionaries are equal

bool operator!=(const dictionary &other) const

Inequality comparison operator.

Parameters:

other – The dictionary to compare with

Returns:

true if dictionaries are not equal

dictionary &operator=(const dictionary &other)

Copy assignment operator.

Parameters:

other – The dictionary to assign from

Returns:

Reference to this dictionary

dictionary &operator=(dictionary &&other) noexcept

Move assignment operator.

Parameters:

other – The dictionary to move from

Returns:

Reference to this dictionary

value &operator[](const std::string &key)

Access or create a value by key (non-const version).

If the key doesn’t exist, a new entry is created with a default value.

Parameters:

key – The key to access or create

Returns:

Reference to the value associated with the key

const value &operator[](const std::string &key) const

Access a value by key (const version).

Parameters:

key – The key to access

Throws:

std::out_of_range – if the key doesn’t exist

Returns:

Const reference to the value associated with the key

iterator begin()

Get an iterator to the beginning of the dictionary.

Returns:

Iterator pointing to the first key-value pair

iterator end()

Get an iterator to the end of the dictionary.

Returns:

Iterator pointing past the last key-value pair

const_iterator begin() const

Get a const iterator to the beginning of the dictionary.

Returns:

Const iterator pointing to the first key-value pair

const_iterator end() const

Get a const iterator to the end of the dictionary.

Returns:

Const iterator pointing past the last key-value pair

const_iterator cbegin() const

Get a const iterator to the beginning of the dictionary.

Returns:

Const iterator pointing to the first key-value pair

const_iterator cend() const

Get a const iterator to the end of the dictionary.

Returns:

Const iterator pointing past the last key-value pair

class const_iterator

Const forward iterator for dictionary key-value pairs.

Provides read-only iterator interface for traversing dictionary entries. Each dereferenced iterator returns a pair of const key and value references. value_type is a pair of copies, the same as for iterator.

The pair is returned by value, so the iterator models std::forward_iterator but declares std::input_iterator_tag as its iterator_category, and has no pointer type, as the standard range adaptors do.

Public Types

using value_type = std::pair<std::string, value>
using difference_type = std::ptrdiff_t
using pointer = void
using reference = std::pair<const std::string&, const value&>
using iterator_concept = std::forward_iterator_tag
using iterator_category = std::input_iterator_tag

Public Functions

const_iterator()

Default constructor. Default-constructed iterators compare equal.

const_iterator(const const_iterator &other)

Copy constructor.

Parameters:

other – The const_iterator to copy from

const_iterator(const iterator &other)

Converting constructor from a mutable iterator.

Parameters:

other – The iterator to convert, pointing to the same element

const_iterator &operator=(const const_iterator &other)

Copy assignment operator.

Parameters:

other – The const_iterator to copy from

Returns:

Reference to this iterator

~const_iterator()

Destructor.

const_iterator &operator++()

Pre-increment operator.

Returns:

Reference to this iterator after incrementing

const_iterator operator++(int)

Post-increment operator.

Returns:

Copy of this iterator before incrementing

reference operator*() const

Dereference operator.

Returns:

Pair containing const key and value references

Friends

friend bool operator==(const const_iterator &lhs, const const_iterator &rhs)

Equality comparison operator.

Either side can be an iterator, which converts to a const_iterator. != is derived from it.

Parameters:
Returns:

true if iterators point to the same element

class impl

Public Functions

inline impl(std::map<std::string, dross::value>::const_iterator i)

Public Members

std::map<std::string, dross::value>::const_iterator cursor
class iterator

Forward iterator for dictionary key-value pairs.

Provides iterator interface for traversing dictionary entries. Each dereferenced iterator returns a pair of key and value references. value_type is a pair of copies, so an element kept as a value_type, such as through std::iter_value_t, does not change with the dictionary.

The pair is returned by value, so the iterator models std::forward_iterator but declares std::input_iterator_tag as its iterator_category, and has no pointer type, as the standard range adaptors do.

Public Types

using value_type = std::pair<std::string, value>
using difference_type = std::ptrdiff_t
using pointer = void
using reference = std::pair<const std::string&, value&>
using iterator_concept = std::forward_iterator_tag
using iterator_category = std::input_iterator_tag

Public Functions

iterator()

Default constructor. Default-constructed iterators compare equal.

iterator(const iterator &other)

Copy constructor.

Parameters:

other – The iterator to copy from

iterator &operator=(const iterator &other)

Copy assignment operator.

Parameters:

other – The iterator to copy from

Returns:

Reference to this iterator

~iterator()

Destructor.

iterator &operator++()

Pre-increment operator.

Returns:

Reference to this iterator after incrementing

iterator operator++(int)

Post-increment operator.

Returns:

Copy of this iterator before incrementing

reference operator*() const

Dereference operator.

Returns:

Pair containing key and value references

Friends

friend bool operator==(const iterator &lhs, const iterator &rhs)

Equality comparison operator. != is derived from it.

Parameters:
  • lhs – The iterator to compare

  • rhs – The iterator to compare with

Returns:

true if iterators point to the same element

class impl

Public Functions

inline impl(std::map<std::string, dross::value>::iterator i)

Public Members

std::map<std::string, dross::value>::iterator cursor
class storage

Public Members

std::map<std::string, dross::value> properties

The dictionary class provides key-value storage:

#include <iostream>
#include <string>

#include <dross/type/dictionary.h>
#include <dross/type/value.h>

dross::dictionary dict;

// A literal on the right-hand side is held as its dross type:
// `dict["age"] = 30;` holds a number and `dict["active"] = true;` a boolean.
dict["name"] = dross::string("John Doe");
dict["age"] = dross::number(30);
dict["active"] = dross::boolean(true);

std::cout << "Size: " << dict.size() << std::endl;  // 3

// operator[] inserts a default-constructed value for a missing key,
// so ask contains() first when you only mean to read.
if (dict.contains("name")) {
    const dross::value& name = dict["name"];
    if (name.is<dross::string>()) {
        std::string text = name.as<dross::string>();
        std::cout << "Name: " << text << std::endl;
    }
}

data

class data

Binary data container for byte storage and manipulation.

The data class provides a robust container for binary data storage with STL-compatible interface and seamless integration with the dross type system. It serves as a pure binary data container without built-in encoding or I/O operations, following the single responsibility principle.

Key features:

  • Binary data storage with efficient memory management

  • Value semantics (copyable and assignable)

  • STL-compatible interface and iterators

  • Range-based for loop support

  • Thread-safe for read operations

  • Seamless integration with value type

  • Direct memory access for performance-critical operations

Performance characteristics:

  • Data access: O(1) by index

  • Append operations: Amortized O(1)

  • Memory usage: Proportional to data size with minimal overhead

  • Iterator operations: O(1) for random access

Thread safety:

  • Const operations are thread-safe

  • Non-const operations require external synchronization

Design philosophy:

  • Pure binary data container (no encoding/decoding)

  • No file I/O operations (use separate file classes)

  • Focused on data storage and manipulation only

  • Encoding/decoding handled by separate encoder/decoder classes

// Basic usage
dross::data binary_data;
binary_data.append({0x48, 0x65, 0x6C, 0x6C, 0x6F}); // "Hello"

// Construction from various sources
dross::data from_string{"Hello, World!"};
dross::data from_vector{std::vector<uint8_t>{0x01, 0x02, 0x03}};

// Direct memory access
auto bytes_opt = binary_data.bytes();
if (bytes_opt) {
const uint8_t* raw_bytes = *bytes_opt;
size_t size = binary_data.size();
}

// STL-compatible access
for (uint8_t byte : binary_data) {
// Process each byte
}

// String conversion
std::string text = binary_data; // Implicit conversion (the bytes, unchanged)
// or explicit conversion:
std::string explicit_text = dross::to_string(binary_data);

Public Functions

data()

Default constructor creating empty data.

data(const data &other)

Copy constructor.

Parameters:

other – The data to copy from

data(data &&other) noexcept

Move constructor.

Parameters:

other – The data to move from

data(const std::initializer_list<uint8_t> &bytes)

Construct from initializer list of bytes.

Parameters:

bytes – Initializer list of uint8_t values

data(const std::vector<uint8_t> &bytes)

Construct from vector of bytes.

Parameters:

bytes – Vector of uint8_t values to copy

data(const uint8_t *buffer, size_t length)

Construct from raw byte buffer.

Parameters:
  • buffer – Pointer to byte data

  • length – Number of bytes to copy

data(const std::string &str)

Construct from string.

Stores the bytes of the string unchanged; nothing is encoded or validated.

Parameters:

str – String to convert to byte data

data(const char *str)

Construct from C-style string.

Parameters:

str – Null-terminated string to convert

~data()

Destructor.

bool empty() const noexcept

Check if the data is empty.

Returns:

true if no bytes are stored, false otherwise

size_t size() const noexcept

Get the number of bytes stored.

Returns:

Number of bytes in the data

size_t max_size() const noexcept

Get maximum possible size.

Returns:

Maximum number of bytes that can be stored

std::optional<const uint8_t*> bytes() const noexcept

Get raw pointer to bytes.

Returns:

Optional pointer to first byte (nullopt if empty)

std::optional<uint8_t*> bytes() noexcept

Get mutable raw pointer to bytes.

Returns:

Optional pointer to first byte (nullopt if empty)

std::expected<std::reference_wrapper<const uint8_t>, error> at(size_t index) const noexcept

Access byte at index with bounds checking.

Parameters:

index – Index of byte to access

Returns:

Expected reference to byte at index (error if out of bounds)

std::expected<std::reference_wrapper<uint8_t>, error> at(size_t index) noexcept

Access byte at index with bounds checking.

Parameters:

index – Index of byte to access

Returns:

Expected reference to byte at index (error if out of bounds)

const uint8_t &operator[](size_t index) const noexcept

Access byte at index without bounds checking.

Parameters:

index – Index of byte to access

Returns:

Reference to byte at index

uint8_t &operator[](size_t index) noexcept

Access byte at index without bounds checking.

Parameters:

index – Index of byte to access

Returns:

Reference to byte at index

void append(const data &other)

Append another data object.

Parameters:

other – Data to append

void append(const uint8_t *buffer, size_t length)

Append raw byte buffer.

Parameters:
  • buffer – Pointer to bytes to append

  • length – Number of bytes to append

void append(const std::initializer_list<uint8_t> &bytes)

Append initializer list of bytes.

Parameters:

bytes – Bytes to append

void clear() noexcept

Clear all data.

void resize(size_t new_size, uint8_t fill_value = 0)

Resize the data container.

Parameters:
  • new_size – New size in bytes

  • fill_value – Value to use for new bytes if expanding

void reserve(size_t capacity)

Reserve memory for at least the specified number of bytes.

Parameters:

capacity – Number of bytes to reserve

bool equals(const data &other) const noexcept

Test equality with another data object.

Parameters:

other – The data to compare with

Returns:

true if both contain the same byte sequence

data &operator=(const data &other)

Copy assignment operator.

Parameters:

other – The data to assign from

Returns:

Reference to this data

data &operator=(data &&other) noexcept

Move assignment operator.

Parameters:

other – The data to move from

Returns:

Reference to this data

bool operator==(const data &other) const noexcept

Equality comparison operator.

Parameters:

other – The data to compare with

Returns:

true if data are equal

bool operator!=(const data &other) const noexcept

Inequality comparison operator.

Parameters:

other – The data to compare with

Returns:

true if data are not equal

std::strong_ordering operator<=>(const data &other) const noexcept

Three-way comparison operator.

Parameters:

other – The data to compare with

Returns:

Comparison result (lexicographical ordering)

data operator+(const data &other) const

Concatenation operator.

Parameters:

other – The data to concatenate

Returns:

New data object containing concatenated bytes

data &operator+=(const data &other)

Concatenation assignment operator.

Parameters:

other – The data to append

Returns:

Reference to this data after concatenation

operator std::string() const

Implicit conversion to string.

Returns:

The bytes, unchanged, as a std::string; nothing is decoded or validated

operator const uint8_t*() const noexcept

Implicit conversion to const uint8_t pointer.

Provides direct access to the raw byte data for performance-critical operations. Returns nullptr if the data is empty.

Returns:

Pointer to the underlying byte data

iterator begin() noexcept

Get iterator to beginning.

Returns:

Iterator pointing to first byte

iterator end() noexcept

Get iterator to end.

Returns:

Iterator pointing past last byte

const_iterator begin() const noexcept

Get const iterator to beginning.

Returns:

Const iterator pointing to first byte

const_iterator end() const noexcept

Get const iterator to end.

Returns:

Const iterator pointing past last byte

const_iterator cbegin() const noexcept

Get const iterator to beginning.

Returns:

Const iterator pointing to first byte

const_iterator cend() const noexcept

Get const iterator to end.

Returns:

Const iterator pointing past last byte

class const_iterator

Const random access iterator for data elements.

Provides read-only iterator interface for traversing data bytes. Supports range-based for loops and standard library algorithms.

Public Types

using iterator_category = std::random_access_iterator_tag
using value_type = uint8_t
using difference_type = std::ptrdiff_t
using pointer = const uint8_t*
using reference = const uint8_t&

Public Functions

const_iterator()
explicit const_iterator(const uint8_t *ptr)
const_iterator(const iterator &iter)
const uint8_t &operator*() const
const uint8_t *operator->() const
const uint8_t &operator[](std::ptrdiff_t n) const
const_iterator &operator++()
const_iterator operator++(int)
const_iterator &operator--()
const_iterator operator--(int)
const_iterator &operator+=(std::ptrdiff_t n)
const_iterator &operator-=(std::ptrdiff_t n)
const_iterator operator+(std::ptrdiff_t n) const
const_iterator operator-(std::ptrdiff_t n) const

Friends

friend std::ptrdiff_t operator-(const const_iterator &lhs, const const_iterator &rhs) noexcept
friend bool operator==(const const_iterator &lhs, const const_iterator &rhs) noexcept
friend std::strong_ordering operator<=>(const const_iterator &lhs, const const_iterator &rhs) noexcept
class iterator

Random access iterator for data elements.

Provides standard iterator interface for traversing data bytes. Supports range-based for loops and standard library algorithms.

Public Types

using iterator_category = std::random_access_iterator_tag
using value_type = uint8_t
using difference_type = std::ptrdiff_t
using pointer = uint8_t*
using reference = uint8_t&

Public Functions

iterator()
explicit iterator(uint8_t *ptr)
uint8_t &operator*() const
uint8_t *operator->() const
uint8_t &operator[](std::ptrdiff_t n) const
iterator &operator++()
iterator operator++(int)
iterator &operator--()
iterator operator--(int)
iterator &operator+=(std::ptrdiff_t n)
iterator &operator-=(std::ptrdiff_t n)
iterator operator+(std::ptrdiff_t n) const
iterator operator-(std::ptrdiff_t n) const

Friends

friend std::ptrdiff_t operator-(const iterator &lhs, const iterator &rhs) noexcept
friend bool operator==(const iterator &lhs, const iterator &rhs) noexcept
friend std::strong_ordering operator<=>(const iterator &lhs, const iterator &rhs) noexcept
class storage

Public Functions

storage() = default
inline explicit storage(const std::vector<uint8_t> &b)
inline explicit storage(std::vector<uint8_t> &&b)
inline storage(const uint8_t *buffer, size_t length)
inline storage(const std::string &str)

Public Members

std::vector<uint8_t> bytes

The data class provides raw byte storage:

#include <cstdint>
#include <iostream>
#include <vector>

#include <dross/type/data.h>

std::vector<uint8_t> bytes = {0x48, 0x65, 0x6C, 0x6C, 0x6F};
dross::data d(bytes);

std::cout << "Size: " << d.size() << " bytes" << std::endl;

error

class error

An error code with an optional detail about what failed.

Wraps a std::error_code: a numeric value and the category it belongs to. The detail is text that says what failed and where. Comparisons ignore it. Only the constructor that takes a std::errc and a detail sets it.

Public Functions

error()

Construct the value that means no error.

The code is 0 in system_category(), so operator bool returns false.

error(const error &other)

Copy constructor.

Parameters:

other – The error to copy from

error(error &&other) noexcept

Move constructor.

Parameters:

other – The error to move from

error &operator=(const error &other)

Copy assignment operator.

Parameters:

other – The error to copy from

Returns:

Reference to this error

error &operator=(error &&other) noexcept

Move assignment operator.

Parameters:

other – The error to move from

Returns:

Reference to this error

error(int value, const std::error_category &category)

Construct from a numeric value and its category.

Parameters:
  • value – The numeric value of the code

  • category – The category the value belongs to

error(std::errc e)

Construct from a std::errc.

std::errc names error conditions rather than codes, so it gets its own constructor. The code is std::make_error_code(e), in generic_category().

Parameters:

e – The error condition to name

error(std::errc e, std::string detail)

Construct from a std::errc with a detail.

Comparisons ignore the detail.

Parameters:
  • e – The error condition to name

  • detail – What failed and where, such as the line of a parse error

virtual ~error()

Destructor.

template<error_enum_type E>
inline error(const E e)

Construct from an error code enum.

std::error_code’s own constructor finds make_error_code by argument-dependent lookup, so an enum from any namespace works.

Template Parameters:

E – The enum type

Parameters:

e – The enum value

std::string domain() const

Get the name of the category.

Returns:

The name of the code’s category

int code() const noexcept

Get the numeric value of the code.

Returns:

The value of the code

std::string message() const

Get the text that describes this error.

Returns:

The message of the code, followed by “: “ and the detail when there is one

std::string detail() const

Get what failed and where.

Returns:

The detail, or an empty string when there is none

const std::error_category &category() const noexcept

Get the category of the code.

Returns:

The code’s category

std::error_condition condition() const noexcept

Get the default error condition of the code.

Returns:

The condition that the code’s category maps it to

explicit operator bool() const noexcept

Check whether this holds an error.

Returns:

true when the value of the code is not 0

template<error_enum_type E>
inline bool operator==(const E e) const noexcept

Compare with an error code enum.

Template Parameters:

E – The enum type

Parameters:

e – The enum value to compare with

Returns:

true when the category and the value both match, as std::error_code compares with an error code enum

bool operator==(std::errc e) const noexcept

Compare with a std::errc.

Parameters:

e – The error condition to compare with

Returns:

true when either category reports e as equivalent, as std::error_code compares with an error condition, so a system_category() code matches the std::errc it maps to

bool operator==(const std::error_condition &c) const noexcept

Compare with a std::error_condition.

An error condition enum from any library converts to it.

Parameters:

c – The error condition to compare with

Returns:

true when either category reports c as equivalent, the same as for std::errc

bool operator==(const std::error_category &c) const noexcept

Check whether the code belongs to a category.

Parameters:

c – The category to compare with

Returns:

true when the code’s category is c

bool operator!=(const std::error_category &c) const noexcept

Check whether the code belongs to another category.

Parameters:

c – The category to compare with

Returns:

true when the code’s category is not c

bool operator==(const error &e) const noexcept

Equality comparison operator.

Parameters:

e – The error to compare with

Returns:

true when the category and the value both match; the detail is ignored

bool operator!=(const error &e) const noexcept

Inequality comparison operator.

Parameters:

e – The error to compare with

Returns:

true when the category or the value differs; the detail is ignored

std::weak_ordering operator<=>(const error &e) const noexcept

Three-way comparison operator.

Categories order by address, so the order of errors from different categories can differ from one program to another. Weak, as errors that differ only in their detail are equivalent but can be told apart.

Parameters:

e – The error to compare with

Returns:

The order of the categories, then of the values

The error class provides structured error information:

#include <iostream>
#include <system_error>

#include <dross/type/error.h>

// error wraps a std::error_code: a numeric value plus its category.
// A std::errc is stored in generic_category().
dross::error err{std::errc::invalid_argument};

std::cout << "Domain: " << err.domain() << std::endl;
std::cout << "Code: " << err.code() << std::endl;
std::cout << "Error: " << err.message() << std::endl;

// A detail says what failed and where. message() adds it after the
// message of the code, and comparisons ignore it.
dross::error parse_err{std::errc::invalid_argument, "line 2, column 3: Expected '='"};
std::cout << "Detail: " << parse_err.detail() << std::endl;
std::cout << "Error: " << parse_err.message() << std::endl;

Type Concepts

The type system uses C++20 concepts to constrain template parameters:

template<typename T>
concept number_type
#include <number.h>

Concept that defines arithmetic types suitable for number construction.

Accepts every arithmetic type. A character is read as its code and bool as 0 or 1: number(‘a’) is 97 and number(true) is 1.

template<typename T>
concept string_type
#include <string.h>

Concept that defines string-like types for string construction.

Accepts const char*, char* (what a char array becomes when passed by value) and std::string for convenient string creation.

template<typename E>
concept error_enum_type
#include <error.h>

An enum that std::error_code can be built from.

tparam E:

The enum type, with std::is_error_code_enum specialized as true

template<typename T>
concept container_type
#include <type.h>

Concept defining requirements for concatenatable container types.

A container type must provide begin()/end() iterators and support insertion at the end to be used with the concat() function.

Supported containers include std::vector, std::list, std::deque, and other standard library containers that meet these requirements.

template<typename T>
concept value_convertible_type
#include <value_traits.h>

A type that value_traits converts to and from a dross::value.

Type Conversion

boolean, number, string, data, timestamp and timezone convert to std::string in two ways:

  • Implicit conversion: std::string s = type_instance;

  • STL-style function: std::string s = to_string(type_instance); — declared in <dross/type.h>, not in the individual type headers

Stream output is provided for boolean, number, data, timestamp, timezone and error. string and value have no operator<<: convert a string to std::string first, and unwrap a value before printing it. An error writes domain:code, followed by ": " and the detail when there is one.

value is inspected and unwrapped with member templates:

  • is<T>() - Check whether the value currently holds type T

  • as<T>() - Retrieve the value as type T. When the value holds another type it returns a default-constructed T rather than the contained object, so check is<T>() first. It does not throw. It copies what is held

  • get_if<T>() - Read the held T without copying it: a pointer to it, or nullptr when the value holds another type. The pointer stays valid until the value is assigned to or destroyed, and a temporary value is refused

Example:

// Multiple string conversion approaches
dross::boolean flag{true};
dross::number n{42};
dross::string text{"hello"};
dross::timestamp meeting{2024, 1, 21, 15, 30, 0, dross::timezone::offset(9)}; // +09:00

// 1. Implicit conversion to std::string
std::string flag_str = flag;      // "true"
std::string num_str = n;          // "42"
std::string text_str = text;      // "hello"
std::string timestamp_str = meeting; // "2024-01-21T15:30:00+09:00"

// 2. STL-style explicit conversion
using dross::to_string;
auto flag_string = to_string(flag);      // "true"
auto num_string = to_string(n);          // "42"
auto text_string = to_string(text);      // "hello"
auto timestamp_string = to_string(meeting); // "2024-01-21T15:30:00+09:00"

// 3. Direct stream output. string has no operator<<, so it reaches the
//    stream through its std::string conversion (text_str above).
std::cout << flag << " " << n << " " << text_str << " " << meeting << std::endl;

// Value type conversion
dross::value v = 42;
if (v.is<dross::number>()) {
    dross::number num = v.as<dross::number>();
    std::string s = to_string(num);  // STL-style conversion
}

// Timestamp in value
dross::value ts_value = dross::timestamp::now();
if (ts_value.is<dross::timestamp>()) {
    auto ts = ts_value.as<dross::timestamp>();
    std::cout << "Current time: " << ts.format("%Y-%m-%d %H:%M:%S") << std::endl;
}

Converting Types to and from value

value_traits<T> says how a T becomes a value and comes back from one. A type is given a conversion by specializing it in namespace dross with two static functions. to_value() always succeeds; from_value() returns a std::expected, since a value received from elsewhere can have any shape:

struct point {
    int x;
    int y;
};

template <>
struct dross::value_traits<point> {
    static dross::value to_value(const point& p)
    {
        dross::dictionary d;
        d["x"] = p.x;
        d["y"] = p.y;
        return d;
    }

    static std::expected<point, dross::error> from_value(const dross::value& v)
    {
        const auto* d = v.get_if<dross::dictionary>();
        if (d == nullptr || ! d->contains("x") || ! d->contains("y")) {
            return std::unexpected(dross::value_errc::kind_mismatch);
        }
        auto x = dross::value_traits<int>::from_value((*d)["x"]);
        auto y = dross::value_traits<int>::from_value((*d)["y"]);
        if (! x || ! y) {
            return std::unexpected(! x ? x.error() : y.error());
        }
        return point{ *x, *y };
    }
};

dross gives a conversion to value itself and the kinds it holds, to bool, integer and floating-point types, to std::string, and to std::vector, std::optional, and std::map and std::unordered_map keyed by std::string, of any type that has one. Character types have none. The conversions dross gives report a failure as a value_errc, in the category named dross.value:

  • kind_mismatch - The value holds another kind, or is null

  • out_of_range - The number does not fit the type, or has a fraction or is NaN where an integer is wanted

value_convertible_type<T> tells at compile time whether T has a conversion.

Comparison Operations

boolean, number, data, timestamp, timezone and error provide three-way comparison (the spaceship operator). value, string, array and dictionary provide only == and !=.

dross::number n1 = 42;
dross::number n2 = 43;

if (n1 < n2) {
    std::cout << "n1 is less than n2" << std::endl;
}

auto ordering = n1 <=> n2;  // std::weak_ordering

// value is only equality-comparable
dross::value v1 = 42;
dross::value v2 = 43;

if (v1 != v2) {
    std::cout << "v1 and v2 hold different values" << std::endl;
}

Error Handling

Type operations that may fail use std::optional or std::expected:

void process(const std::string& text);
dross::data toml_input{"title = \"Example\""};

// Returns std::optional<timezone>
if (auto tz = dross::timezone::from_string("+09:00")) {
    process(tz->format());
}

// Error handling with expected
auto result = dross::toml::deserialize(toml_input);
if (!result) {
    std::cerr << "Parse error: " << result.error().message() << std::endl;
}