pub enum Value {
Null,
Bool(bool),
Int(i64),
Uint(u64),
Float(f64),
Str(String),
Extended {
kind: ExtKind,
text: String,
},
Seq(Vec<Value>),
Map(Vec<(Value, Value)>),
}Expand description
An owned, format-independent value tree.
§Canonical form
Two of the scalar variants overlap, so the tree has a canonical spelling
that every constructor in this crate produces — parsing, From, the
ToValue impls, and the serde serializer alike:
- An integer that fits in
i64isValue::Int, whatever Rust type it came from.Value::Uintholds only magnitudes pasti64::MAX. This is what keepsValue::from(3u64) == Value::from(3i64);PartialEqis structural (it compares variants, as a value tree’s equality should), so without the rule the same number could be unequal to itself depending on which door it came in by. The reading accessors (Value::as_i64,Value::as_u64,Value::as_f64) still span both variants, so a hand-builtValue::Uint(3)reads back fine — it just isn’t==toValue::Int(3). Route throughValue::from(orValue::eq_canonical) rather than constructingUintfor a small number. - A float is compared by IEEE rules under
==, which means a value can fail to equal itself:.nanis a scalar fig both parses and renders, andNaN != NaN. A dirty check written asif new != old { … }therefore never converges on a float field holding.nan. UseValue::eq_canonicalfor that; it compares floats by bit pattern.
Variants§
Null
Bool(bool)
Int(i64)
Uint(u64)
An integer too large for i64. Canonically this variant holds only
values above i64::MAX — see the type-level note on canonical form.
Float(f64)
A float, including the non-finite values YAML spells .inf/.nan
(see Value::parse_float). Note that == on a NaN payload is
false, as everywhere else in Rust; Value::eq_canonical is the
reflexive comparison.
Str(String)
Extended
A format-specific scalar (TOML datetime, ZON enum/char literal) carried
verbatim. Produced by crate::Document::to_value when reading TOML/ZON,
and rendered back by Value::serialize. The serde path instead reads
these as plain strings/integers.
Seq(Vec<Value>)
Map(Vec<(Value, Value)>)
Mapping entries, in order. Keys are conventionally strings; a non-string key serializes only to formats whose printer accepts one.
Implementations§
Source§impl Value
impl Value
Sourcepub fn serialize(&self, format: Format) -> Result<String, Error>
pub fn serialize(&self, format: Format) -> Result<String, Error>
Render to format via fig’s core serializer, using default output style.
The value is built through the core’s value API and emitted by fig’s
core, so no JSON/YAML/TOML/ZON formatting happens in this crate.
Sourcepub fn serialize_with(
&self,
format: Format,
options: SerializeOptions,
) -> Result<String, Error>
pub fn serialize_with( &self, format: Format, options: SerializeOptions, ) -> Result<String, Error>
Render to format, with options controlling output style such as
compact vs. pretty-printed JSON.
Sourcepub fn diagnose(
&self,
format: Format,
options: SerializeOptions,
) -> Result<Vec<Warning>, Error>
pub fn diagnose( &self, format: Format, options: SerializeOptions, ) -> Result<Vec<Warning>, Error>
Report what serializing this value to format would silently lose
(values/comments dropped or degraded). The built value has no source
envelopes, so options.lossless is ignored. Returns one crate::Warning
per lossy event (empty if nothing is lost).
Sourcepub fn is_null(&self) -> bool
pub fn is_null(&self) -> bool
true if this is Value::Null.
Sourcepub fn is_bool(&self) -> bool
pub fn is_bool(&self) -> bool
true if this is a Value::Bool.
Sourcepub fn as_bool(&self) -> Option<bool>
pub fn as_bool(&self) -> Option<bool>
The bool, if this is a Value::Bool.
Sourcepub fn is_i64(&self) -> bool
pub fn is_i64(&self) -> bool
true if Value::as_i64 would succeed: this is a Value::Int, or a
Value::Uint that fits in i64.
Sourcepub fn as_i64(&self) -> Option<i64>
pub fn as_i64(&self) -> Option<i64>
The integer, if this is a Value::Int, or a Value::Uint that fits
in i64.
Sourcepub fn is_u64(&self) -> bool
pub fn is_u64(&self) -> bool
true if Value::as_u64 would succeed: this is a Value::Uint, or
a non-negative Value::Int.
Sourcepub fn as_u64(&self) -> Option<u64>
pub fn as_u64(&self) -> Option<u64>
The integer, if this is a Value::Uint, or a non-negative Value::Int.
Sourcepub fn is_f64(&self) -> bool
pub fn is_f64(&self) -> bool
true if this is a Value::Float. Unlike Value::as_f64, integers
don’t count — this asks whether the value was stored as a float, not
whether it’s numerically representable as one.
Sourcepub fn as_f64(&self) -> Option<f64>
pub fn as_f64(&self) -> Option<f64>
The float, if this is a Value::Float. Also widens a Value::Int
or Value::Uint (lossily for magnitudes past 2^53), matching how
[crate::convert::FromValue] reads f64 fields.
Sourcepub fn is_str(&self) -> bool
pub fn is_str(&self) -> bool
true if this is a Value::Str.
Sourcepub fn as_str(&self) -> Option<&str>
pub fn as_str(&self) -> Option<&str>
The string, if this is a Value::Str. Does not match Value::Extended
scalars, whose text is format-specific rather than a plain string.
Sourcepub fn is_extended(&self) -> bool
pub fn is_extended(&self) -> bool
true if this is a Value::Extended scalar.
Sourcepub fn as_extended(&self) -> Option<(ExtKind, &str)>
pub fn as_extended(&self) -> Option<(ExtKind, &str)>
The kind and text, if this is a Value::Extended scalar.
Sourcepub fn is_seq(&self) -> bool
pub fn is_seq(&self) -> bool
true if this is a Value::Seq.
Sourcepub fn as_seq(&self) -> Option<&[Value]>
pub fn as_seq(&self) -> Option<&[Value]>
The elements, if this is a Value::Seq.
Sourcepub fn is_mapping(&self) -> bool
pub fn is_mapping(&self) -> bool
true if this is a Value::Map.
Sourcepub fn as_mapping(&self) -> Option<&[(Value, Value)]>
pub fn as_mapping(&self) -> Option<&[(Value, Value)]>
The entries, if this is a Value::Map.
Sourcepub fn eq_canonical(&self, other: &Value) -> bool
pub fn eq_canonical(&self, other: &Value) -> bool
Structural equality, canonicalised so that a value always equals itself.
== compares the variants exactly, which is what a value tree’s equality
should mean — but it inherits two edges from the scalars:
Value::Float(f64::NAN) != Value::Float(f64::NAN), by IEEE rules, so a value parsed fromx: .nanis not equal to an identical second parse of the same bytes. Here floats compare by bit pattern, so it is. The flip side of that:0.0and-0.0are not equal here, matching the distinct text (0.0/-0.0) they serialize to.Value::IntandValue::Uintare distinct variants, so a hand-builtValue::Uint(3)is not==toValue::Int(3)(the crate’s own constructors never produce the former — see the type-level note on canonical form). Here the two integer variants compare numerically.
Everything else matches ==, including map comparison being
order-sensitive: entries are an ordered Vec, and reordering them
changes the document.
This is the comparison to use for a round-trip or dirty check —
“would writing this value back change the file?” — where == can
report a spurious difference and loop.
use fig::Value;
let nan = Value::Float(f64::NAN);
assert!(nan != nan); // IEEE
assert!(nan.eq_canonical(&nan)); // reflexive
assert!(Value::Int(3).eq_canonical(&Value::Uint(3)));
assert!(!Value::Float(0.0).eq_canonical(&Value::Float(-0.0)));Sourcepub fn parse_number(raw: &str, is_float: bool) -> Result<Value, Error>
pub fn parse_number(raw: &str, is_float: bool) -> Result<Value, Error>
Parse a numeric scalar’s text into a Value, exactly as reading a
document does — the inverse of the number text fig writes out.
is_float is the scalar’s kind, not a guess about its spelling: a float
field holding 3 is Float(3.0), an integer field holding 3 is
Int(3). An integer tries i64 then u64, falling back to a float when
it fits in neither (matching how the deserializer widens); a float goes
through Value::parse_float, so it accepts the .inf/.nan spellings
fig itself emits.
Editors and schema layers that turn edited text back into a value should
use this rather than str::parse, which rejects .inf/.nan — a field
holding one would otherwise become a Value::Str on a no-op edit.
§Notation
The text is a lexeme, not a canonical decimal: fig_node_number
yields the raw source text, and how much of the author’s spelling
survives is the language’s choice. TOML canonicalizes its numbers before
they reach here; fig’s own dialect and ZON deliberately keep the
verbatim lexeme so 0xFF round-trips as 0xFF rather than 255. So
this accepts everything those tokenizers do: the 0x/0o/0b radix
prefixes, _ digit separators, and a leading sign on either.
use fig::Value;
assert_eq!(Value::parse_number("3", false).unwrap(), Value::Int(3));
assert_eq!(Value::parse_number("3", true).unwrap(), Value::Float(3.0));
assert_eq!(Value::parse_number("0xFF", false).unwrap(), Value::Int(255));
assert_eq!(Value::parse_number("1_000", false).unwrap(), Value::Int(1000));
assert_eq!(Value::parse_number("-0o755", false).unwrap(), Value::Int(-493));
// Past i64::MAX, in any notation, is the canonical `Uint` range.
assert_eq!(
Value::parse_number("0xd4f24a95e29f7b74", false).unwrap(),
Value::Uint(15344408888017386356),
);
assert!(Value::parse_number(".inf", true).unwrap().as_f64().unwrap().is_infinite());
assert!(Value::parse_number("nope", false).is_err());Sourcepub fn parse_float(raw: &str) -> Option<f64>
pub fn parse_float(raw: &str) -> Option<f64>
Parse float text the way fig reads it: f64::from_str, plus the
non-finite spellings YAML uses and fig writes — .inf, .Inf, .INF
(with an optional +), their negatives, and .nan, .NaN, .NAN.
None if the text is not a float at all.
This is the inverse of the text fig serializes a Value::Float to, so
a float scalar survives a text round trip unchanged. Rust’s own
"…".parse::<f64>() is not: it rejects .inf/.nan and accepts
inf/NaN, which fig never writes.
Sourcepub fn get<I: Index>(&self, index: I) -> Option<&Value>
pub fn get<I: Index>(&self, index: I) -> Option<&Value>
Index into this value: a string-like [Index] looks up a key among a
Value::Map’s entries (last-wins on duplicates), an integer looks up
a position in a Value::Seq. None if this value isn’t the matching
container kind, or the key/index isn’t present.
Trait Implementations§
Source§impl From<&Value> for Value
Clone a borrowed value into an owned one. This is what lets a &Value still
satisfy the impl Into<Value> value parameters on the editor methods
(pass an owned Value instead to move rather than clone).
impl From<&Value> for Value
Clone a borrowed value into an owned one. This is what lets a &Value still
satisfy the impl Into<Value> value parameters on the editor methods
(pass an owned Value instead to move rather than clone).
Source§impl From<u64> for Value
Normalises into the canonical integer variant: Value::Int when the value
fits in i64, Value::Uint only past i64::MAX. Every other constructor
in the crate funnels unsigned integers through here, so a 3 is the same
value however it was built.
impl From<u64> for Value
Normalises into the canonical integer variant: Value::Int when the value
fits in i64, Value::Uint only past i64::MAX. Every other constructor
in the crate funnels unsigned integers through here, so a 3 is the same
value however it was built.
Source§impl<I: Index> Index<I> for Value
value[key]/value[index], returning Value::Null (rather than
panicking) when the index is out of range or the wrong container kind —
so a chain like value["a"]["b"][0] can walk through a mismatch and still
be checked with Value::is_null at the end. Use Value::get instead
for an Option that distinguishes “absent” from an actual null.
impl<I: Index> Index<I> for Value
value[key]/value[index], returning Value::Null (rather than
panicking) when the index is out of range or the wrong container kind —
so a chain like value["a"]["b"][0] can walk through a mismatch and still
be checked with Value::is_null at the end. Use Value::get instead
for an Option that distinguishes “absent” from an actual null.