Skip to main content

ValueMap

Struct ValueMap 

Source
pub struct ValueMap { /* private fields */ }
Expand description

A CEL map with heterogeneous keys.

Uses a BTreeMap with a custom key type for deterministic iteration order.

Implementations§

Source§

impl ValueMap

Source

pub fn new() -> Self

Create a new empty map.

Source

pub fn from_entries(entries: impl IntoIterator<Item = (MapKey, Value)>) -> Self

Create a map from an iterator of key-value pairs.

Source

pub fn get(&self, key: &MapKey) -> Option<&Value>

Get a value by key.

Source

pub fn insert(&mut self, key: MapKey, value: Value)

Insert a key-value pair.

Source

pub fn contains_key(&self, key: &MapKey) -> bool

Check if a key exists.

Source

pub fn get_with_numeric_coercion(&self, key: &MapKey) -> Option<&Value>

Get a value by key with cross-type numeric coercion. Tries exact match first, then Int↔UInt coercion for in-range values.

Source

pub fn contains_key_with_numeric_coercion(&self, key: &MapKey) -> bool

Check if a key exists with cross-type numeric coercion.

Source

pub fn len(&self) -> usize

Get the number of entries.

Examples found in repository?
examples/extract_values.rs (line 63)
7fn main() {
8    let env = Env::with_standard_library()
9        .with_variable("count", CelType::Int)
10        .with_variable("items", CelType::list(CelType::Int))
11        .with_variable("config", CelType::map(CelType::String, CelType::String));
12
13    let mut activation = MapActivation::new();
14    activation.insert("count", 42); // i32 automatically widens to i64
15    activation.insert("items", Value::list([1, 2, 3]));
16    activation.insert(
17        "config",
18        Value::map([("host", "localhost"), ("port", "8080")]),
19    );
20
21    // Extract i64
22    let ast = env.compile("count * 2").unwrap();
23    let program = env.program(&ast).unwrap();
24    let result = program.eval(&activation);
25
26    let value: i64 = (&result).try_into().expect("expected int");
27    println!("i64: {}", value);
28
29    // Extract bool
30    let ast = env.compile("count > 10").unwrap();
31    let program = env.program(&ast).unwrap();
32    let result = program.eval(&activation);
33
34    let value: bool = (&result).try_into().expect("expected bool");
35    println!("bool: {}", value);
36
37    // Extract &str
38    let ast = env.compile("config.host").unwrap();
39    let program = env.program(&ast).unwrap();
40    let result = program.eval(&activation);
41
42    let value: &str = (&result).try_into().expect("expected string");
43    println!("&str: {}", value);
44
45    // Extract &[Value] (list)
46    let ast = env.compile("items.filter(x, x > 1)").unwrap();
47    let program = env.program(&ast).unwrap();
48    let result = program.eval(&activation);
49
50    let list: &[Value] = (&result).try_into().expect("expected list");
51    println!("list length: {}", list.len());
52    for (i, v) in list.iter().enumerate() {
53        let n: i64 = v.try_into().expect("expected int");
54        println!("  [{}] = {}", i, n);
55    }
56
57    // Extract &ValueMap
58    let ast = env.compile("config").unwrap();
59    let program = env.program(&ast).unwrap();
60    let result = program.eval(&activation);
61
62    let map: &ValueMap = (&result).try_into().expect("expected map");
63    println!("map size: {}", map.len());
64    for (k, v) in map.iter() {
65        println!("  {:?} = {}", k, v);
66    }
67
68    // Handle errors gracefully
69    let result = Value::from("not an int");
70    let attempt: Result<i64, _> = (&result).try_into();
71    match attempt {
72        Ok(v) => println!("got: {}", v),
73        Err(e) => println!("conversion error: {}", e),
74    }
75
76    // Extract &OptionalValue
77    let opt_result = Value::optional_some(Value::from(99));
78    let opt: &OptionalValue = (&opt_result).try_into().expect("expected optional");
79    if opt.is_present() {
80        let inner: i64 = opt.as_value().unwrap().try_into().expect("expected int");
81        println!("optional value: {}", inner);
82    }
83}
Source

pub fn is_empty(&self) -> bool

Check if the map is empty.

Source

pub fn iter(&self) -> impl Iterator<Item = (&MapKey, &Value)>

Iterate over entries.

Examples found in repository?
examples/extract_values.rs (line 64)
7fn main() {
8    let env = Env::with_standard_library()
9        .with_variable("count", CelType::Int)
10        .with_variable("items", CelType::list(CelType::Int))
11        .with_variable("config", CelType::map(CelType::String, CelType::String));
12
13    let mut activation = MapActivation::new();
14    activation.insert("count", 42); // i32 automatically widens to i64
15    activation.insert("items", Value::list([1, 2, 3]));
16    activation.insert(
17        "config",
18        Value::map([("host", "localhost"), ("port", "8080")]),
19    );
20
21    // Extract i64
22    let ast = env.compile("count * 2").unwrap();
23    let program = env.program(&ast).unwrap();
24    let result = program.eval(&activation);
25
26    let value: i64 = (&result).try_into().expect("expected int");
27    println!("i64: {}", value);
28
29    // Extract bool
30    let ast = env.compile("count > 10").unwrap();
31    let program = env.program(&ast).unwrap();
32    let result = program.eval(&activation);
33
34    let value: bool = (&result).try_into().expect("expected bool");
35    println!("bool: {}", value);
36
37    // Extract &str
38    let ast = env.compile("config.host").unwrap();
39    let program = env.program(&ast).unwrap();
40    let result = program.eval(&activation);
41
42    let value: &str = (&result).try_into().expect("expected string");
43    println!("&str: {}", value);
44
45    // Extract &[Value] (list)
46    let ast = env.compile("items.filter(x, x > 1)").unwrap();
47    let program = env.program(&ast).unwrap();
48    let result = program.eval(&activation);
49
50    let list: &[Value] = (&result).try_into().expect("expected list");
51    println!("list length: {}", list.len());
52    for (i, v) in list.iter().enumerate() {
53        let n: i64 = v.try_into().expect("expected int");
54        println!("  [{}] = {}", i, n);
55    }
56
57    // Extract &ValueMap
58    let ast = env.compile("config").unwrap();
59    let program = env.program(&ast).unwrap();
60    let result = program.eval(&activation);
61
62    let map: &ValueMap = (&result).try_into().expect("expected map");
63    println!("map size: {}", map.len());
64    for (k, v) in map.iter() {
65        println!("  {:?} = {}", k, v);
66    }
67
68    // Handle errors gracefully
69    let result = Value::from("not an int");
70    let attempt: Result<i64, _> = (&result).try_into();
71    match attempt {
72        Ok(v) => println!("got: {}", v),
73        Err(e) => println!("conversion error: {}", e),
74    }
75
76    // Extract &OptionalValue
77    let opt_result = Value::optional_some(Value::from(99));
78    let opt: &OptionalValue = (&opt_result).try_into().expect("expected optional");
79    if opt.is_present() {
80        let inner: i64 = opt.as_value().unwrap().try_into().expect("expected int");
81        println!("optional value: {}", inner);
82    }
83}
Source

pub fn keys(&self) -> impl Iterator<Item = &MapKey>

Iterate over keys.

Source

pub fn values(&self) -> impl Iterator<Item = &Value>

Iterate over values.

Trait Implementations§

Source§

impl Clone for ValueMap

Source§

fn clone(&self) -> ValueMap

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ValueMap

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for ValueMap

Source§

fn default() -> ValueMap

Returns the “default value” for a type. Read more
Source§

impl<'a> TryFrom<&'a Value> for &'a ValueMap

Source§

type Error = ValueError

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

fn try_from(v: &'a Value) -> Result<Self, Self::Error>

Performs the conversion.

Auto Trait Implementations§

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.