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;
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>;
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;
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;
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;
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;
at_field(this, name: Str) -> ValueDecodeError;This error, met reading the member name of an object.
at_index(this, index: i64) -> ValueDecodeError;
at_index(this, index: i64) -> ValueDecodeError;This error, met reading the element index of an array.
path(&this) -> Str;
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;
expected(&this) -> Str;What was wanted there: a u16, an object.
found(&this) -> Str;
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
| Variant | Notes |
|---|---|
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
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 ToValue {
to_value(&this) -> Value;
}A value that can be written as a Value.
type trait FromValue {
static from_value(value: &Value) -> Result<This, ValueDecodeError>;
}A value that can be read from 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.
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 round_trip(ports: &Array<u16>) -> Result<Array<u16>, ValueDecodeError>(parameter) ports: &Array<u16>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 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.
const 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 text: Stringtype 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.
static Json::to_text(value: &Value) -> Stringvalue as compact JSON text, no whitespace between tokens: {"name":"cryo","tags":[1,2]}.
(parameter) ports: &Array<u16>const parsed: Valuestatic 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).
const text: StringString::as_str(&this) -> StrBorrow as a Str. Invalidated by the next mutating call.
Result::unwrap(this) -> TThe Ok value, aborting on Err. Consumes the result: the value moves out to the caller and the error, if any, is released.
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.
static Array::from_value(value: &Value) -> Result<Array<T, GlobalAllocator>, ValueDecodeError>via trait FromValue
std::encoding::value::convertconst parsed: Valuefunction 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 ports: Array<u16>static Array::new() -> Array<T, GlobalAllocator>Empty array backed by GlobalAllocator.
mut ports: Array<u16>Array::push(mut &this, value: T) -> voidAdd value after the last element, growing the storage when it is full. Panics on allocation failure; try_push returns the error instead.
const back: Array<u16>function round_trip(ports: &Array<u16>) -> Result<Array<u16>, ValueDecodeError>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 back: Array<u16>if (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 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 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 ToValue {
to_value(&this) -> Value;
}A value that can be written as a Value.
ToValue::to_value(&this) -> ValueThis value as a Value the caller owns.
&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 trait FromValue {
static from_value(value: &Value) -> Result<This, ValueDecodeError>;
}A value that can be read from a Value.
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 FromValue::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.
(parameter) value: &ValueThisThe implementing type, inside a trait or implement body. other: &This in a trait method is a reference to whichever type implements it; This::Item names an associated type.
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 Server with [ToValue, FromValue]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.
public function name() { ... }
public:Visible to any module that imports this one - the default for top-level items and for struct fields, so it is mostly written to be explicit. public: opens a visibility block that groups the members after it. A module is always public, so public module is refused (E0117).
Server.host: StringServer.port: u16Server.connections: i64Server.retries: i64Server.nickname: Option<String>type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
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.
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.
ValueDecodeError.path: StringValueDecodeError.expected: 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.
ValueDecodeError.found: Strtype 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 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 parameter EFromTextError::Parse(E)The text is not the format's: what its reader refused, and where.
type parameter EFromTextError::Decode(ValueDecodeError)The text's value is not the type: where in it, and what was wanted there.
namespace 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.
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.
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.
type struct Server with [ToValue, FromValue]ToValue::to_value(&this) -> ValueThis value as a Value the caller owns.
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.
type struct BTreeMap<K, V, A = GlobalAllocator> where A: Allocator {}A map from keys to values kept in ascending key order. Keys need Ord. Lookups and inserts take time logarithmic in the size; iteration and range visit keys in order.
Option::NoneValue::Nullimplement 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 parameter Atype parameter Twhere T: ToValue
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 parameter Vwhere V: ToValue
type parameter Htype struct GlobalAllocator {}Zero-sized handle to the process-wide allocator. Construct with GlobalAllocator::new(); all instances dispatch through the same underlying backend.
static FromValue::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.
type parameter Twhere T: FromValue
type parameter Vwhere V: FromValue
type parameter Hwhere H: Hasher + Copy + Default
type trait Hasher {
write_u8(mut &this, value: u8) -> void;
write_bytes(mut &this, bytes: &Slice<u8>) -> void;
write_unsigned_integer(mut &this, value: u128, byte_count: u32) -> void;
fold<T>(mut &this, value: T) -> void
where T: Primitive;
fold_text(mut &this, text: Str) -> void;
finish(&this) -> u64;
}A running hash state that values feed their bytes into, one write_* call at a time; finish reads the digest of everything fed so far.
type trait Copy {}Types whose values can be duplicated by a bitwise copy. Integers, floats, pointers, and pure-POD structs qualify; anything that owns resources (heap storage, file handles, refcount) does not.
std::core::markertype trait Default {
static default() -> This;
}A type with a canonical starting value, which generic code can make without knowing the type: 0 for the numbers, false, '\0', and an empty value for the collections that implement it.
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.
type trait FromJson {
static from_json(text: Str) -> Result<This, FromTextError<JsonError>>;
}A type read from JSON text: the text parsed as Json::parse parses it, then its value read as the type through FromValue. Every type with FromValue has it, a type of its own through with [FromJson], which derives FromValue.
type trait FromYaml {
static from_yaml(text: Str) -> Result<This, FromTextError<YamlError>>;
}A type read from YAML text: the one document the text holds, parsed as Yaml::parse parses it, then its value read as the type through FromValue. Every type with FromValue has it, a type of its own through with [FromYaml], which derives FromValue.
type trait FromToml {
static from_toml(text: Str) -> Result<This, FromTextError<TomlError>>;
}A type read from TOML text: the document parsed as Toml::parse parses it, then its root table read as the type through FromValue. Every type with FromValue has it, a type of its own through with [FromToml], which derives FromValue.
type trait ToJson {
to_json(&this) -> String;
to_pretty_json(&this) -> String;
}A type written as JSON text: its Value, from ToValue, written as Json::to_text writes one. Every type with ToValue has it, a type of its own through with [ToJson], which derives ToValue.
type trait ToYaml {
to_yaml(&this) -> String;
to_pretty_yaml(&this) -> String;
}A type written as YAML text: its Value, from ToValue, written as Yaml's writers write one. Every type with ToValue has it, a type of its own through with [ToYaml], which derives ToValue.
type trait ToToml {
to_toml(&this) -> Result<String, TomlError>;
}A type written as TOML text: its Value, from ToValue, written as Toml::to_text writes one. Every type with ToValue has it, a type of its own through with [ToToml], which derives ToValue.
// reservedOpens no form of the language: a declaration or member written with it is refused where it is written (E0117). It still names a method: Default::default() is the trait's constructor.
ValueDecodeError::path(&this) -> StrWhere the value that could not be read is: .servers[2].port, or empty for the value read itself.
ValueDecodeError::expected(&this) -> StrWhat was wanted there: a u16, an object.
ValueDecodeError::found(&this) -> StrWhat was there: a string, a number out of its range, nothing.
primitive stringNUL-terminated raw string (u8*), matching the C ABI. Length-typed text is Str / String.
static ValueDecodeError::unexpected(expected: Str, value: &Value) -> ValueDecodeErrorvalue was found where expected ("a u16", "an object") was wanted.
static ValueDecodeError::out_of_range(expected: Str) -> ValueDecodeErrorA number was found where expected was wanted, but it is out of that type's range or is not a whole number.
static ValueDecodeError::missing_field(name: Str) -> ValueDecodeErrorAn object has no member name, which the type being read needs.
ValueDecodeError::at_field(this, name: Str) -> ValueDecodeErrorThis error, met reading the member name of an object.
ValueDecodeError::at_index(this, index: i64) -> ValueDecodeErrorThis error, met reading the element index of an array.
(parameter) expected: Str(parameter) name: Str(parameter) index: i64function range<T>(low: T, high: T) -> T
where T: NumericA uniform value in [low, high), of any integer type or f32/f64: random::range(1, 7) rolls a die. Unbiased; panics unless low < high.
FromTextError::Parse(E)The text is not the format's: what its reader refused, and where.
std::encoding::value::converttype struct JsonError {
kind: JsonErrorKind;
line: u64;
column: u64;
offset: u64;
msg: String;
}Why JSON text could not be parsed, and where: the failure's kind, its position in the source, and a message for a person to read.
std::encoding::json::errortype struct YamlError {
kind: YamlErrorKind;
line: u64;
column: u64;
offset: u64;
msg: String;
}Why YAML text could not be read, and where: the failure's kind, its position in the source, and a message for a person to read.
std::encoding::yaml::errortype struct TomlError {
kind: TomlErrorKind;
line: u64;
column: u64;
offset: u64;
msg: String;
}Why TOML text could not be read or a value written, and where: the failure's kind, its position in the source (0 for the writer's), and a message for a person to read.
std::encoding::toml::errorFromTextError::Decode(ValueDecodeError)The text's value is not the type: where in it, and what was wanted there.
std::encoding::value::converttype trait Error : Display, Debug {
source(&this) -> Option<virtual &Error>;
}An error: a message for a person through Display, a fuller form through Debug, and the error it was caused by, if it keeps one.
type struct BoxedError {}Any error, owned whole: the value of whatever type implements Error, moved to the heap and reached through its Error table.
const E: f64 = 2.718281828459045;type parameter Ewhere E: Display
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.
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 parameter Ewhere E: Debug
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 parameter Ewhere E: Error