Skip to content
CryoCryo home
Stdlibencoding::value

model

import std::encoding::value::model; · source

Types

Value

type enum Value {
    Null;
    Bool(boolean);
    Number(Number);
    String(String);
    Array(Array<Value>);
    Object(Object);
}

A tagged union over the six kinds of the shared data model, the one JSON, YAML and TOML all read into and write from. It is recursive through Array<Value> and Object, each owning variant holds heap storage, and the whole tree is released when the value goes out of scope. A Value displays as its compact JSON text.

Variants

Variant
Null
Bool(boolean)
Number(Number)
String(String)
Array(Array<Value>)
Object(Object)

Constructors

static boolean_value(b: boolean) -> Value;

The JSON boolean b: true or false.

static integer_value(n: i64) -> Value;

The JSON number n, kept as a signed integer (Number::Int) so it is written back without a fraction.

static unsigned_integer_value(n: u64) -> Value;

The JSON number n, kept as an unsigned integer (Number::UInt) so it is written back exactly, values above i64::MAX included.

static from<T>(src: T) -> Value;

JSON string value from a text src. static match (T) restricts the accepted types to a borrowed Str or a raw NUL-terminated string (C-string), copying either into an owned String. The match deliberately admits no numeric/boolean arm: those go through integer_value / unsigned_integer_value / boolean_value or a Number variant, so a number never silently becomes a JSON string.

static string_array(items: &[string]) -> Value;

JSON array of strings from a raw [string]. Each element is escaped at serialize time.

Methods

is_null(&this) -> boolean;

Whether this is the JSON null.

is_boolean(&this) -> boolean;

Whether this is a JSON boolean.

is_number(&this) -> boolean;

Whether this is a JSON number, integer or not.

is_string(&this) -> boolean;

Whether this is a JSON string.

is_array(&this) -> boolean;

Whether this is a JSON array.

is_object(&this) -> boolean;

Whether this is a JSON object.

get(&this, key: Str) -> Option<Value*>;

obj.get("key") for object variants; None for everything else.

at(&this, index: i64) -> Option<Value*>;

Array index access; None outside [0, length) or on a non-array.

![inline]
length(&this) -> i64;

Number of children (object entries / array elements). 0 for scalars.

Constructing

Value::Null and the variants build a value directly. boolean_value, integer_value and unsigned_integer_value build the scalar variants, and from copies a Str or a string into an owned string value — it admits no numeric or boolean argument, so a number never silently becomes a string. A float is Value::Number(Number::Float(x)), and string_array builds an array of strings from a [string].

import std::encoding::value::{ Value, Number, Object };

function main() -> int {
    mut obj: Object = Object::new();
    obj.put("name", Value::from("cryo"));
    obj.put("count", Value::integer_value(3));
    obj.put("ratio", Value::Number(Number::Float(0.5)));
    obj.put("tags", Value::Array(Array::new()));
    obj.put("none", Value::Null);
    const doc: Value = Value::Object(obj);
    return if (doc.length() == 5) { 0 } else { 1 };
}

Inspecting

is_null, is_boolean, is_number, is_string, is_array, and is_object each return boolean.

get(key) is object member lookup, O(1) on average, and at(index) is array element access; both hand back a Value*. length() counts the elements of an array or the members of an object, and as<T>() is typed extraction for any T: TryFrom<&Value>. To read a whole value into a type of your own, use FromValue.

Extract

type trait Extract {
    as<T>(&this) -> Option<T>
    where T: TryFrom<&Value>;
}

as<T>() comes from the Extract trait, which exists only to give the generic method a home where the TryFrom<&Value> bound resolves. TryFrom<&Value> is implemented for boolean, i64, u64, f64, and Str, so it covers the usual extractions. A refusal — the wrong variant, or a number T cannot hold exactly — becomes None; call T::try_from(&value) when the reason matters.

import std::encoding::value::{ Value, Extract };

function main() -> int {
    const count: Value = Value::integer_value(42);
    const number: i64 = count.as::<i64>().unwrap();      // 42
    const flag: Option<boolean> = count.as::<boolean>();  // None
    return if (number == 42 && flag.is_none()) { 0 } else { 1 };
}
Methods
as<T>(&this) -> Option<T> where T: TryFrom<&Value>;

The value read as a T, or None when T::try_from refuses it: the wrong variant, or a number that T cannot hold exactly (as::<f64>() takes any number, rounding an integer beyond 2^53).

Trait implementations

implement trait Extract for Value
implement trait Drop for enum Value
implement trait Clone for enum Value
implement trait Display for enum Value
implement trait Debug for enum Value

TryFrom<&Value> is what as<T>() dispatches through; the list also shows TryFrom's other implementors, which share the trait:

implement trait TryFrom<&Value> for boolean
implement trait TryFrom<&Value> for i64
implement trait TryFrom<&Value> for u64
implement trait TryFrom<&Value> for f64
implement trait TryFrom<&Value> for Str
implement trait TryFrom<Str> for u64
std::collections::str
implement trait TryFrom<Str> for u32
std::collections::str
implement trait TryFrom<Str> for u16
std::collections::str
implement trait TryFrom<Str> for u8
std::collections::str
implement trait TryFrom<Str> for usize
std::collections::str
implement trait TryFrom<Str> for u128
std::collections::str
implement trait TryFrom<Str> for i64
std::collections::str
implement trait TryFrom<Str> for i32
std::collections::str
implement trait TryFrom<Str> for i16
std::collections::str
implement trait TryFrom<Str> for i8
std::collections::str
implement trait TryFrom<Str> for isize
std::collections::str
implement trait TryFrom<Str> for i128
std::collections::str
implement trait TryFrom<Str> for f64
std::collections::str
implement trait TryFrom<Str> for f32
std::collections::str
implement trait TryFrom<Str> for boolean
std::collections::str
implement trait TryFrom<Str> for char
std::collections::str
implement trait TryFrom<i32> for i16
std::core::convert
implement trait TryFrom<i64> for i32
std::core::convert
implement trait TryFrom<u64> for u32
std::core::convert
implement trait TryFrom<i64> for u64
std::core::convert
implement trait TryFrom<u64> for i64
std::core::convert

Number

type enum Number with [Debug, Clone] {
    Int(i64);
    UInt(u64);
    Float(f64);
}

The data model has one number type; this splits it by source representation so integers round-trip exactly — 42 parses and is written back as 42, not 42.0.

Int covers signed values fitting i64, UInt carries values in (i64::MAX, u64::MAX], and everything else — decimals, exponents — is Float. Lossy conversion is opt-in: as_i64() returns None for a UInt beyond i64::MAX or a Float with a fractional component, as_u64() returns None for a negative Int or a non-integral Float, and as_f64() gives the lossy view when you want it.

Variants

Variant
Int(i64)
UInt(u64)
Float(f64)

Methods

as_i64(&this) -> Option<i64>;

Try to view as a signed 64-bit integer. UInt values that exceed i64::MAX and any Float with a fractional component return None.

as_u64(&this) -> Option<u64>;

Try to view as an unsigned 64-bit integer.

as_f64(&this) -> f64;

Always-succeeds f64 view. Int/UInt values larger than 2^53 lose precision in the conversion.

Object

type struct Object {
    private keys:   Array<String>;
    private values: Array<Value>;
    private index:  HashMap<String, i64>;
}

Object access is O(1) on average through a hash index, and insertion order is preserved, so writing one out is deterministic.

insert takes ownership of both key and value; put is the convenience over a C string literal. Inserting a key that is already present replaces its value and keeps the key's original position — last value wins. The JSON parser does not reject duplicate keys and keeps the last; YAML and TOML refuse them (DuplicateKey). get and contains are hash lookups, get_mutable borrows a value for change in place, and key_at / value_at walk in insertion order.

Constructors

static new() -> Object;

An object with no entries.

static with_capacity(capacity: i64) -> Object;

An object with no entries and room for capacity of them before its storage grows.

Methods

![inline]
length(&this) -> i64;

The number of entries; a key inserted twice counts once.

is_empty(&this) -> boolean;

Whether the object has no entries.

insert(mut &this, key: String, value: Value) -> void;

Insert or overwrite the entry for key. Takes ownership of both the key String and the value. If the key already exists, the previous value is dropped and the slot reused.

put(mut &this, key: string, value: Value) -> void;

Insert with a raw NUL-terminated string (C-string) key, interned to an owned String internally. The ergonomic shortcut for the common insert(String::from_str(Str::from(k)), v).

get(&this, key: Str) -> Option<Value*>;

Look up a value by key. Returns a read-only borrowed pointer that is valid until the next mutating operation.

get_mutable(mut &this, key: Str) -> Option<mut Value*>;

Like get, but the borrow is writable: change the value in place through it. Valid until the next mutating operation.

key_at(&this, index: i64) -> Option<Str>;

Borrow the key at index. Returns None if index is outside [0, length).

value_at(&this, index: i64) -> Option<Value*>;

Borrow the value at index, or None outside [0, length).

contains(&this, key: Str) -> boolean;

Whether the object has an entry for key.

Trait implementations

implement trait Drop for struct Object
implement trait Clone for struct Object
implement trait Debug for struct Object