Skip to main content

OptionalValue

Enum OptionalValue 

Source
pub enum OptionalValue {
    None,
    Some(Box<Value>),
}
Expand description

A CEL optional value.

Variants§

§

None

An absent optional value.

§

Some(Box<Value>)

A present optional value.

Implementations§

Source§

impl OptionalValue

Source

pub fn none() -> Self

Create an absent optional.

Source

pub fn some(value: Value) -> Self

Create a present optional.

Source

pub fn is_present(&self) -> bool

Returns true if the optional is present.

Examples found in repository?
examples/extract_values.rs (line 79)
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 as_value(&self) -> Option<&Value>

Get the inner value, or None if absent.

Examples found in repository?
examples/extract_values.rs (line 80)
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 unwrap_or(self, default: Value) -> Value

Unwrap the value or return a default.

Trait Implementations§

Source§

impl Clone for OptionalValue

Source§

fn clone(&self) -> OptionalValue

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 OptionalValue

Source§

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

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

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

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.