Skip to content
CryoCryo home
Stdlibencoding

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 };
FileWhat it holdsImport
modelValue, Number, Object, Extractimport std::encoding::value::model;
convertToValue, FromValue, ValueDecodeError, FromTextErrorimport 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.