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;
static boolean_value(b: boolean) -> Value;The JSON boolean b: true or false.
static integer_value(n: i64) -> Value;
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;
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;
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;
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;
is_null(&this) -> boolean;Whether this is the JSON null.
is_boolean(&this) -> boolean;
is_boolean(&this) -> boolean;Whether this is a JSON boolean.
is_number(&this) -> boolean;
is_number(&this) -> boolean;Whether this is a JSON number, integer or not.
is_string(&this) -> boolean;
is_string(&this) -> boolean;Whether this is a JSON string.
is_array(&this) -> boolean;
is_array(&this) -> boolean;Whether this is a JSON array.
is_object(&this) -> boolean;
is_object(&this) -> boolean;Whether this is a JSON object.
get(&this, key: Str) -> Option<Value*>;
get(&this, key: Str) -> Option<Value*>;obj.get("key") for object variants; None for everything else.
at(&this, index: i64) -> Option<Value*>;
at(&this, index: i64) -> Option<Value*>;Array index access; None outside [0, length) or on a non-array.
![inline]length(&this) -> i64;
![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>;
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>;
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>;
as_u64(&this) -> Option<u64>;Try to view as an unsigned 64-bit integer.
as_f64(&this) -> f64;
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;
static new() -> Object;An object with no entries.
static with_capacity(capacity: i64) -> Object;
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;
![inline]length(&this) -> i64;The number of entries; a key inserted twice counts once.
is_empty(&this) -> boolean;
is_empty(&this) -> boolean;Whether the object has no entries.
insert(mut &this, key: String, value: Value) -> void;
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;
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*>;
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*>;
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>;
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*>;
value_at(&this, index: i64) -> Option<Value*>;Borrow the value at index, or None outside [0, length).
contains(&this, key: Str) -> boolean;
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
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type enum Name {
Unit,
Payload(T),
Named { x: i32 },
}An algebraic data type. Variants may be bare or carry a tuple or struct payload, and a match on an enum must cover every variant. Name::Variant names a variant; methods are added with implement enum Name { ... }.
type enum Value {
Null;
Bool(boolean);
Number(Number);
String(String);
Array(Array<Value>);
Object(Object);
}One JSON value. Recursive through Array and Object.
Value::NullValue::Bool(boolean)Value::Number(Number)type enum Number with [Debug, Clone] {
Int(i64);
UInt(u64);
Float(f64);
}JSON's single number type, split by source representation so integers round-trip exactly. Int covers signed values that fit i64; UInt carries values in (i64::MAX, u64::MAX]; everything else (decimals, exponents, NaN-shaped inputs the parser accepts as floats) is Float.
Value::String(String)type struct String<A = GlobalAllocator> {}Owned, growable UTF-8 text. It dereferences to Str, the read-only view most text functions take, so every Str method reads a String too (s.contains(...), s.split(...)); as_str hands the view out.
Value::Array(Array<Value>)type struct Array<T, A = GlobalAllocator> where A: Allocator {}A growable sequence of Ts stored contiguously, owning its elements; A is the allocator its storage comes from. Indexing out of range panics; get answers None instead.
type enum Value {
Null;
Bool(boolean);
Number(Number);
String(String);
Array(Array<Value>);
Object(Object);
}One JSON value. Recursive through Array and Object.
Value::Object(Object)type struct Object {}JSON object. Insertion-ordered keys + parallel value array; a HashMap from String to slot index gives O(1) lookup. Owns its keys and values, and releases them when it goes out of scope.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
namespace std::encoding::value;value: the data model the text encodings read into and write from.
module pagefunction name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function main() -> intmut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
mut obj: Objectmut obj: ObjectObject::put(mut &this, key: string, value: Value) -> voidInsert 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).
static Value::from<T>(src: T) -> ValueJSON 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.
static Value::integer_value(n: i64) -> ValueThe JSON number n, kept as a signed integer (Number::Int) so it is written back without a fraction.
Value::Number(Number)Number::Float(f64)Value::Array(Array<Value>)static Array::new() -> Array<T, GlobalAllocator>Empty array backed by GlobalAllocator.
Value::Nullconst name: Type = value;An immutable binding: it cannot be reassigned after initialisation. The annotation may be omitted when an initialiser is present - the binding takes the initialiser's concrete type, inferred locally. Mutability is opt-in through mut.
const doc: ValueValue::Object(Object)return value;Leaves the current function with the given value. A function whose return type is not void must return one; a bare return; is for void. In an async function it completes the future with the value.
if (condition) { ... } else if (condition) { ... } else { ... }Branches on a parenthesised boolean condition. Bodies are always braced; there is no single-statement form. Used as an expression, both arms are required and must produce the same type: const sign = if (n < 0) { -1 } else { 1 };.
const doc: ValueValue::length(&this) -> i64Number of children (object entries / array elements). 0 for scalars.
std::encoding::value::modelif (condition) { ... } else { ... }The branch taken when every preceding if condition is false; else if chains another condition. In expression form the else arm is mandatory, so the expression always has a value.
type trait Name : Base {
method(&this, other: &This) -> Ret;
}Names a set of methods a type may implement. Inside the body This is the implementing type; methods may carry default bodies, and a trait may require a base trait (type trait Ord : Eq). Generic code asks for a trait with where T: Name.
type trait Extract {
as<T>(&this) -> Option<T>
where T: TryFrom<&Value>;
}Typed scalar extraction from a Value, dispatched on the requested type T. json.as::<i64>() yields Some when the value is a number representable as i64, else None; likewise as::<boolean>, as::<u64>, as::<f64>, and as::<Str> (a borrow into the value's owned string, valid for the Value's lifetime).
Extract::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).
type parameter Twhere T: TryFrom
&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
where T: Ord + Clone, U: HashConstrains generic parameters to types that implement the listed traits, which is what makes those traits' methods callable on T. Bounds on one parameter join with +; parameters separate with ,. A where on a single method narrows the type's parameter for that method only.
type trait TryFrom<T> {
static try_from(value: T) -> Result<This, ConversionError>;
}A conversion from a T into this type that can fail, such as a narrowing of an integer whose value may not fit.
type trait Extract {
as<T>(&this) -> Option<T>
where T: TryFrom<&Value>;
}Typed scalar extraction from a Value, dispatched on the requested type T. json.as::<i64>() yields Some when the value is a number representable as i64, else None; likewise as::<boolean>, as::<u64>, as::<f64>, and as::<Str> (a borrow into the value's owned string, valid for the Value's lifetime).
const count: Valueconst number: i64const count: ValueValue::as<T>(&this) -> Option<T>
where T: TryFrom<&Value>via trait Extract
std::encoding::value::modelconst flag: Option<boolean>const number: i64const flag: Option<boolean>type enum Number with [Debug, Clone] {
Int(i64);
UInt(u64);
Float(f64);
}JSON's single number type, split by source representation so integers round-trip exactly. Int covers signed values that fit i64; UInt carries values in (i64::MAX, u64::MAX]; everything else (decimals, exponents, NaN-shaped inputs the parser accepts as floats) is Float.
type struct Point with [Eq, Clone, Debug] { .. }Asks the compiler to generate implementations of the listed traits for the type, each working through its fields or variants in declaration order. The derivable traits are Eq, Ord, Hash, Clone, Debug, Default, ToValue and FromValue, and the text formats' FromJson, ToJson, FromYaml, ToYaml, FromToml and ToToml. The clause comes after the name and its parameters, before where.
type trait Debug {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
}How a value reads to a programmer: what {x:?} writes, and {x:#?} over several lines. with [Debug] on a declaration writes it field by field.
type trait Clone {
clone(&this) -> This;
}A type whose values can be duplicated into independent copies. A type takes it with with [Clone] on its declaration, or by implementing clone by hand.
Number::Int(i64)Number::UInt(u64)Number::Float(f64)type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct Object {}JSON object. Insertion-ordered keys + parallel value array; a HashMap from String to slot index gives O(1) lookup. Owns its keys and values, and releases them when it goes out of scope.
private type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
Object.keys: Array<String>Object.values: Array<Value>Object.index: HashMap<String, i64>type struct HashMap<K, V, A = GlobalAllocator, H = SipHasher> where A: Allocator {}A map from keys to values, found by the key's hash. Keys need Hash and Eq. H is the hasher: SipHasher by default, which resists keys chosen to collide; FnvHasher is faster for trusted keys. Iteration order is unspecified; BTreeMap keeps keys sorted.
namespace std::encoding::value::model;Value: tagged union over the six kinds of the shared data model.
module pageValue::Bool(boolean)Value::String(String)static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
static Value::boolean_value(b: boolean) -> ValueThe JSON boolean b: true or false.
(parameter) b: booleantrueThe boolean literal. Booleans are a distinct 1-byte type, not interchangeable with integers; if and while conditions must be boolean.
falseThe boolean literal. Booleans are a distinct 1-byte type, not interchangeable with integers; if and while conditions must be boolean.
(parameter) n: i64Number::Int(i64)static Value::unsigned_integer_value(n: u64) -> ValueThe JSON number n, kept as an unsigned integer (Number::UInt) so it is written back exactly, values above i64::MAX included.
(parameter) n: u64Number::UInt(u64)// reservedA reserved keyword with no syntax of its own in the current grammar. The standard library uses it freely as a method and parameter name (Str::from, from: u64).
(parameter) src: Tstatic match (T) { ... }Opens a compile-time match on a type parameter: the one arm whose type matches is kept during monomorphisation and the rest are discarded.
static match (T) {
u8 | u16 => { ... }
_ => { ... }
}Selects a body by inspecting a type parameter at compile time. The subject is a type and each arm is a type (| groups several; _ takes the rest). During monomorphisation the one matching arm is kept and the others discarded, so there is no runtime branch.
type struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
primitive stringNUL-terminated raw string (u8*), matching the C ABI. Length-typed text is Str / String.
static Value::string_array(items: &[string]) -> ValueJSON array of strings from a raw [string]. Each element is escaped at serialize time.
(parameter) items: &[string]nullThe null pointer literal, valid in any pointer context - including the primitive string, which is a NUL-terminated u8*. Compare with == null; it is not an Option.
Value::is_number(&this) -> booleanWhether this is a JSON number, integer or not.
std::encoding::value::modelObject::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.
std::encoding::value::model(parameter) key: StrOption::NoneValue::at(&this, index: i64) -> Option<Value*>Array index access; None outside [0, length) or on a non-array.
(parameter) index: i64Object::length(&this) -> i64The number of entries; a key inserted twice counts once.
std::encoding::value::modelvalue as TypeExplicit conversion: between numeric types, or reinterpreting one pointer type as another. Cryo never converts implicitly, and as inserts no range checks - a narrowing cast is the programmer's responsibility.
function value<T>() -> TA uniform value of type T: any integer width over its whole range, boolean, f32/f64 in [0.0, 1.0), or a char that is any Unicode scalar value.
implement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
implement trait Trait for Type { ... }Introduces a trait implementation: the block supplies, for one concrete type, the method bodies the trait requires.
language referenceimplement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype trait Drop {
drop(mut &this) -> void;
}A type that releases something when a value of it ends: memory, a file handle, a lock. The compiler calls drop once when an owned value goes out of scope; release a value early with mem::drop(value).
type trait Display {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
to_string(&this) -> String;
}How a value reads to a person: what {x} in an f-string and println write. Implement it for a type a user sees.
primitive usizePointer-width unsigned integer; the natural type for sizes and indices.
primitive typeNumber::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.
Number::as_u64(&this) -> Option<u64>Try to view as an unsigned 64-bit integer.
std::encoding::value::modelNumber::as_f64(&this) -> f64Always-succeeds f64 view. Int/UInt values larger than 2^53 lose precision in the conversion.
Object::insert(mut &this, key: String, value: Value) -> voidInsert 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.
Object::contains(&this, key: Str) -> booleanWhether the object has an entry for key.
Object::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.
Object::key_at(&this, index: i64) -> Option<Str>Borrow the key at index. Returns None if index is outside [0, length).
Object::value_at(&this, index: i64) -> Option<Value*>Borrow the value at index, or None outside [0, length).
static Object::with_capacity(capacity: i64) -> ObjectAn object with no entries and room for capacity of them before its storage grows.
(parameter) capacity: i64mut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
(parameter) key: String(parameter) value: Value(parameter) key: stringstatic String::from_str(source: Str) -> StringConstruct from a Str by copying its bytes. Panics on allocation failure.
static Str::from<T>(src: T) -> StrConstruct a Str view from a text source, dispatched on T at compile time: - string - a NUL-terminated C-string (literal or an i8*/u8* cast to string), viewed as Str::new views it: the NUL is not part of the view, and a null one is the empty view.