value
The data model the text encodings read into and write from. Value is a tagged union over six kinds — Null, Bool, Number, String, Array and Object. A Number keeps the kind its source wrote (Int, UInt or Float), so an integer read as 42 is written back as 42; as_f64() converts on request. An Object keeps its members in insertion order and finds one by key in O(1) on average.
A value of a Cryo type is written as a Value through ToValue and read back from one through FromValue; a type gets both from with [ToValue, FromValue]. A refused read is a ValueDecodeError naming where in the value it was and what was expected there.
Each format reads and writes the model through a type of its own module — Json, Yaml, Toml — and each also names the two steps together for a type: every type with FromValue has from_json, from_yaml and from_toml, refusing with a FromTextError, and every type with ToValue has to_json, to_yaml and to_toml.
import std::encoding::value::{ Value, Extract };
import std::encoding::json::{ Json };
function port_of(source: Str) -> i64 {
match (Json::parse(source)) {
Result::Ok(doc) => {
match (doc.get("port")) {
Option::Some(v) => { return v.as::<i64>().unwrap_or(0); }
Option::None => { return 0; }
}
}
Result::Err(e) => { return -1; } // e.line, e.column, e.describe()
}
}
function main() -> int {
return if (port_of("{\"port\": 8080}") == 8080) { 0 } else { 1 };
}
module encoding::value::model;
module encoding::value::convert;
export std::encoding::value::model::{ Extract, Number, Object, Value };
export std::encoding::value::convert::{ FromTextError, FromValue, ToValue, ValueDecodeError };
| File | What it holds | Import |
|---|---|---|
model | Value, Number, Object, Extract | import std::encoding::value::model; |
convert | ToValue, FromValue, ValueDecodeError, FromTextError | import std::encoding::value::convert; |
std::encoding::value re-exports every name in the table, so import std::encoding::value::{ Value, FromValue }; is the usual spelling.
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 pagetype enum Value {
Null;
Bool(boolean);
Number(Number);
String(String);
Array(Array<Value>);
Object(Object);
}One JSON value. Recursive through Array and Object.
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).
namespace std::encoding::json;json: RFC 8259 JSON text, read into and written from the shared data model std::encoding::value::Value.
type struct Json {}The JSON text format: reading a Value from JSON text and writing one as JSON text.
function 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 port_of(source: Str) -> i64(parameter) source: Strtype 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.
match (subject) {
Pattern(x) => { ... }
_ => { ... }
}The primary discriminator: branches on enum variants, integers, ranges, constants, and tuple and destructuring patterns, such as (0, 1..8) or Option::Some((count, _)), and the compiler rejects a match that misses a case. There is no fallthrough. As an expression it evaluates to the chosen arm's value, so every arm must produce the same type.
static Json::parse(text: Str) -> Result<Value, JsonError>Read a complete JSON document, or say where it stops being JSON: the JsonError points at the first byte that failed. Trailing whitespace is allowed; trailing non-whitespace is JsonErrorKind::TrailingData. Arrays and objects nest at most 256 deep, counted together (JsonErrorKind::DepthExceeded).
(parameter) source: Strtype enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
Result::Ok(T)doc: Valuepattern => { body }Separates a match arm's pattern from its body. Arms do not fall through.
doc: ValueValue::get(&this, key: Str) -> Option<Value*>obj.get("key") for object variants; None for everything else.
type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
Option::Some(T)v: Value*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.
v: Value*Value::as<T>(&this) -> Option<T>
where T: TryFrom<&Value>via trait Extract
std::encoding::value::modelOption::NoneResult::Err(E)e: JsonErrorfunction main() -> intif (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 };.
function port_of(source: Str) -> i64if (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.
module collections::array;
module { a::b; a::c; }
internal module a::detail;In a directory's _module.cryo aggregator, declares a submodule. A module is public; internal module keeps it and everything it declares to its own package. The line is structure only: reaching the child's names still takes an import or an export.
namespace std::encoding::value::model;Value: tagged union over the six kinds of the shared data model.
module pagenamespace std::encoding::value::convert;Typed values: a value of a Cryo type written as a Value (ToValue), and read back from one (FromValue), whatever text format the Value is read from or written as.
export a::b::Name;
export a::b::{ X, Y as Z };Passes a name this module did not declare on to its importers, exactly as if they had imported the same path - how an aggregator presents a flat surface over its files. Every hop is explicit, and there is no glob form.
language referencetype 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 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.
type enum FromTextError<E> {
Parse(E);
Decode(ValueDecodeError);
}Why text could not be read as a type: it is not the format's text (Parse, holding the format's own error - a JsonError, YamlError or TomlError), or the value it holds is not the type (Decode).
type trait FromValue {
static from_value(value: &Value) -> Result<This, ValueDecodeError>;
}A value that can be read from a Value.
type trait ToValue {
to_value(&this) -> Value;
}A value that can be written as a Value.
type struct ValueDecodeError {}Why a Value could not be read as a type: where in it (path, from the value read: .servers[2].port, empty for the value itself), what was expected there and what was found. It prints as at .servers[2].port: expected a u16, found a string.
Value::NullValue::Bool(boolean)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.
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.
Number::Int(i64)Number::UInt(u64)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.