Skip to main content

Value

Enum Value 

Source
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 i64 is Value::Int, whatever Rust type it came from. Value::Uint holds only magnitudes past i64::MAX. This is what keeps Value::from(3u64) == Value::from(3i64); PartialEq is 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-built Value::Uint(3) reads back fine — it just isn’t == to Value::Int(3). Route through Value::from (or Value::eq_canonical) rather than constructing Uint for a small number.
  • A float is compared by IEEE rules under ==, which means a value can fail to equal itself: .nan is a scalar fig both parses and renders, and NaN != NaN. A dirty check written as if new != old { … } therefore never converges on a float field holding .nan. Use Value::eq_canonical for 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.

Fields

§kind: ExtKind
§text: String
§

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

Source

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 C value API and emitted by fig, so no JSON/YAML/TOML/ZON formatting happens in Rust.

Source

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.

Source

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).

Source

pub fn is_null(&self) -> bool

true if this is Value::Null.

Source

pub fn is_bool(&self) -> bool

true if this is a Value::Bool.

Source

pub fn as_bool(&self) -> Option<bool>

The bool, if this is a Value::Bool.

Source

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.

Source

pub fn as_i64(&self) -> Option<i64>

The integer, if this is a Value::Int, or a Value::Uint that fits in i64.

Source

pub fn is_u64(&self) -> bool

true if Value::as_u64 would succeed: this is a Value::Uint, or a non-negative Value::Int.

Source

pub fn as_u64(&self) -> Option<u64>

The integer, if this is a Value::Uint, or a non-negative Value::Int.

Source

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.

Source

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.

Source

pub fn is_str(&self) -> bool

true if this is a Value::Str.

Source

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.

Source

pub fn is_extended(&self) -> bool

true if this is a Value::Extended scalar.

Source

pub fn as_extended(&self) -> Option<(ExtKind, &str)>

The kind and text, if this is a Value::Extended scalar.

Source

pub fn is_seq(&self) -> bool

true if this is a Value::Seq.

Source

pub fn as_seq(&self) -> Option<&[Value]>

The elements, if this is a Value::Seq.

Source

pub fn is_mapping(&self) -> bool

true if this is a Value::Map.

Source

pub fn as_mapping(&self) -> Option<&[(Value, Value)]>

The entries, if this is a Value::Map.

Source

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 from x: .nan is 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.0 and -0.0 are not equal here, matching the distinct text (0.0 / -0.0) they serialize to.
  • Value::Int and Value::Uint are distinct variants, so a hand-built Value::Uint(3) is not == to Value::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)));
Source

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());
Source

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.

Source

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 Clone for Value

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Value

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
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/embed methods (pass an owned Value instead to move rather than clone).

Source§

fn from(v: &Value) -> Self

Converts to this type from the input type.
Source§

impl From<&str> for Value

Source§

fn from(v: &str) -> Self

Converts to this type from the input type.
Source§

impl From<String> for Value

Source§

fn from(v: String) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<Value>> for Value

Source§

fn from(v: Vec<Value>) -> Self

Converts to this type from the input type.
Source§

impl From<bool> for Value

Source§

fn from(v: bool) -> Self

Converts to this type from the input type.
Source§

impl From<f64> for Value

Source§

fn from(v: f64) -> Self

Converts to this type from the input type.
Source§

impl From<i32> for Value

Source§

fn from(v: i32) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for Value

Source§

fn from(v: i64) -> Self

Converts to this type from the input type.
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.

Source§

fn from(v: u64) -> Self

Converts to this type from the input type.
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.

Source§

type Output = Value

The returned type after indexing.
Source§

fn index(&self, index: I) -> &Value

Performs the indexing (container[index]) operation. Read more
Source§

impl PartialEq for Value

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Value

Auto Trait Implementations§

§

impl Freeze for Value

§

impl RefUnwindSafe for Value

§

impl Send for Value

§

impl Sync for Value

§

impl Unpin for Value

§

impl UnsafeUnpin for Value

§

impl UnwindSafe for Value

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.