Skip to content
CryoCryo home
Stdlibencoding::value

convert

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

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.

import std::encoding::value::{ Value, ToValue, FromValue, ValueDecodeError };
import std::encoding::json::{ Json };

function round_trip(ports: &Array<u16>) -> Result<Array<u16>, ValueDecodeError> {
    const text: String = Json::to_text(&ports.to_value());      // [80,443]
    const parsed: Value = Json::parse(text.as_str()).unwrap();
    return Array::<u16>::from_value(&parsed);
}

function main() -> int {
    mut ports: Array<u16> = Array::new();
    ports.push(80);
    ports.push(443);
    const back: Array<u16> = round_trip(&ports).unwrap();
    return if (back.length() == 2) { 0 } else { 1 };
}

TryFrom<&Value> and value.as::<T>() stay the way to borrow a scalar out of a value in place; FromValue builds an owned value of any shape and says where reading it failed. Each text format names the parse and the read together — Server::from_json(text), server.to_json() — through FromJson / ToJson, FromYaml / ToYaml and FromToml / ToToml, which every type with FromValue or ToValue has.

Types

ToValue

type trait ToValue {
    to_value(&this) -> Value;
}

Methods

to_value(&this) -> Value;

This value as a Value the caller owns.

Implementors

The standard types implement both traits: boolean, every integer width, f32, f64, String, Array<T> (an array), HashMap<String, V> and BTreeMap<String, V> (an object, one member per key), and Option<T> (None as Null). Str is written only.

implement trait ToValue for boolean
implement trait ToValue for i8
implement trait ToValue for i16
implement trait ToValue for i32
implement trait ToValue for i64
implement trait ToValue for u8
implement trait ToValue for u16
implement trait ToValue for u32
implement trait ToValue for u64
implement trait ToValue for f64
implement trait ToValue for f32
implement<A> trait ToValue for struct String<A>
implement trait ToValue for Str
implement<T> trait ToValue for enum Option<T> where T: ToValue
implement<T, A> trait ToValue for struct Array<T, A> where T: ToValue
implement<V, H> trait ToValue for struct HashMap<String<GlobalAllocator>, V, GlobalAllocator, H> where V: ToValue
implement<V> trait ToValue for struct BTreeMap<String<GlobalAllocator>, V, GlobalAllocator> where V: ToValue

FromValue

type trait FromValue {
    static from_value(value: &Value) -> Result<This, ValueDecodeError>;
}

Reading checks the shape and the range: 300 read as a u8, or 1.5 read as any integer, is a ValueDecodeError naming where in the value it was and what was expected there, not a wrapped value.

Constructors

static from_value(value: &Value) -> Result<This, ValueDecodeError>;

Read a value of this type from value, or say where in it and why it could not be read.

Implementors

implement trait FromValue for boolean
implement trait FromValue for i8
implement trait FromValue for i16
implement trait FromValue for i32
implement trait FromValue for i64
implement trait FromValue for u8
implement trait FromValue for u16
implement trait FromValue for u32
implement trait FromValue for u64
implement trait FromValue for f64
implement trait FromValue for f32
implement trait FromValue for struct String<GlobalAllocator>
implement<T> trait FromValue for enum Option<T> where T: FromValue
implement<T> trait FromValue for struct Array<T, GlobalAllocator> where T: FromValue
implement<V, H> trait FromValue for struct HashMap<String<GlobalAllocator>, V, GlobalAllocator, H> where V: FromValue, H: Hasher + Copy + Default
implement<V> trait FromValue for struct BTreeMap<String<GlobalAllocator>, V, GlobalAllocator> where V: FromValue

Deriving

with [ToValue, FromValue] on a declaration generates both implementations (§10.8). A struct is written as an object holding each field's to_value() under the field's name, in declaration order, and read from an object member by member, a refusal reported at the member it is about. Members the struct does not name are ignored, and an absent member reads as whatever the field's type reads null as — an Option field is None. An enum whose variants carry nothing is written as the string naming its variant; an enum whose variants carry values implements the traits by hand.

A text format's traits derive too, each as the data-model trait it reads or writes through: FromJson, FromYaml and FromToml derive FromValue, and ToJson, ToYaml and ToToml derive ToValue. So with [FromJson, ToJson] reads and writes JSON with only json::{ FromJson, ToJson } imported. Two entries derived as one trait — with [FromValue, FromJson], or with [FromJson, FromYaml] — would implement it twice and are refused (E0318); a type that reads several formats lists FromValue once.

A field's member is adjusted with ![json(...)], any of these options together:

import std::encoding::value::{ ToValue, FromValue };

type struct Server with [ToValue, FromValue] {
    public host: String;
    ![json(rename = "port_number")]
    public port: u16;                  // the member is `port_number`, read and written
    ![json(skip)]
    public connections: i64;           // never written; read as `i64`'s `default()`
    ![json(default)]
    public retries: i64;               // an absent member reads as `default()`
    ![json(skip_none)]
    public nickname: Option<String>;   // left out of the object when it writes `null`
}

function main() -> int { return 0; }

A skip or default field's type must have Default. An option ![json] does not know is E0152, and a derive the type cannot have — ToValue on an enum whose variants carry values, a field whose type lacks the trait, a type declared in a function body — is E0318.

ValueDecodeError

type struct ValueDecodeError {
    private path:     String;
    private expected: Str;
    private found:    Str;
}

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.

A hand-written FromValue makes one with unexpected, out_of_range or missing_field, and wraps an error met reading a member or an element with at_field or at_index, so the path builds outward from the value that failed.

Constructors

static unexpected(expected: Str, value: &Value) -> ValueDecodeError;

value was found where expected ("a u16", "an object") was wanted.

static out_of_range(expected: Str) -> ValueDecodeError;

A number was found where expected was wanted, but it is out of that type's range or is not a whole number.

static missing_field(name: Str) -> ValueDecodeError;

An object has no member name, which the type being read needs.

Methods

at_field(this, name: Str) -> ValueDecodeError;

This error, met reading the member name of an object.

at_index(this, index: i64) -> ValueDecodeError;

This error, met reading the element index of an array.

path(&this) -> Str;

Where the value that could not be read is: .servers[2].port, or empty for the value read itself.

expected(&this) -> Str;

What was wanted there: a u16, an object.

found(&this) -> Str;

What was there: a string, a number out of its range, nothing.

FromTextError<E>

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). It is what from_json, from_yaml and from_toml refuse with; it prints as the error it holds, and is an Error when that error is one, so ? passes it on as a BoxedError.

Variants

VariantNotes
Parse(E)The text is not the format's: what its reader refused, and where.
Decode(ValueDecodeError)The text's value is not the type: where in it, and what was wanted there.

Trait implementations

implement<E> trait Display for enum FromTextError<E> where E: Display
std::fmt::display
implement<E> trait Debug for enum FromTextError<E> where E: Debug
std::fmt::display
implement<E> trait Error for enum FromTextError<E> where E: Error
std::fmt::display