pub struct Optional<T>(/* private fields */);
Expand description
CEL-compatible optional value type.
Optional<T>
is similar to Rust’s Option<T>
but designed specifically for CEL’s
optional value semantics. It provides a comprehensive API for working with optional
values in CEL expressions.
§Type Parameters
T
: The type of the optional value
§Examples
use cel_cxx::{Optional, Value};
// Create optional values
let some_val = Optional::new("hello");
let none_val: Optional<String> = Optional::none();
// Convert from/to Option
let option = Some(42i64);
let optional = Optional::from_option(option);
let back_to_option = optional.into_option();
// Chain operations
let result = Optional::new(10)
.map(|x| x * 2)
.filter(|&x| x > 15)
.or(Optional::new(0));
Implementations§
Source§impl<T> Optional<T>
impl<T> Optional<T>
Sourcepub fn new(value: T) -> Self
pub fn new(value: T) -> Self
Creates a new optional value containing the given value.
§Examples
use cel_cxx::Optional;
let opt = Optional::new(42);
assert!(opt.as_option().is_some());
Sourcepub fn none() -> Self
pub fn none() -> Self
Creates an empty optional value.
§Examples
use cel_cxx::Optional;
let opt: Optional<i32> = Optional::none();
assert!(opt.as_option().is_none());
Sourcepub fn into_option(self) -> Option<T>
pub fn into_option(self) -> Option<T>
Converts the optional into a standard Option
.
§Examples
use cel_cxx::Optional;
let opt = Optional::new(42);
let option = opt.into_option();
assert_eq!(option, Some(42));
Sourcepub fn from_option(opt: Option<T>) -> Self
pub fn from_option(opt: Option<T>) -> Self
Creates an optional from a standard Option
.
§Examples
use cel_cxx::Optional;
let option = Some(42);
let opt = Optional::from_option(option);
assert_eq!(opt.into_option(), Some(42));
Sourcepub fn as_option(&self) -> &Option<T>
pub fn as_option(&self) -> &Option<T>
Returns a reference to the contained Option
.
§Examples
use cel_cxx::Optional;
let opt = Optional::new(42);
assert_eq!(opt.as_option(), &Some(42));
Sourcepub fn as_option_mut(&mut self) -> &mut Option<T>
pub fn as_option_mut(&mut self) -> &mut Option<T>
Returns a mutable reference to the contained Option
.
§Examples
use cel_cxx::Optional;
let mut opt = Optional::new(42);
*opt.as_option_mut() = Some(100);
assert_eq!(opt.into_option(), Some(100));
Sourcepub fn as_ref(&self) -> Optional<&T>
pub fn as_ref(&self) -> Optional<&T>
Converts from Optional<T>
to Optional<&T>
.
§Examples
use cel_cxx::Optional;
let opt = Optional::new("hello".to_string());
let opt_ref = opt.as_ref();
assert_eq!(opt_ref.into_option(), Some(&"hello".to_string()));
Sourcepub fn as_mut(&mut self) -> Optional<&mut T>
pub fn as_mut(&mut self) -> Optional<&mut T>
Converts from Optional<T>
to Optional<&mut T>
.
§Examples
use cel_cxx::Optional;
let mut opt = Optional::new("hello".to_string());
let opt_mut = opt.as_mut();
// Can modify the contained value through opt_mut
Sourcepub fn map<U, F>(self, f: F) -> Optional<U>where
F: FnOnce(T) -> U,
pub fn map<U, F>(self, f: F) -> Optional<U>where
F: FnOnce(T) -> U,
Maps an Optional<T>
to Optional<U>
by applying a function to the contained value.
§Examples
use cel_cxx::Optional;
let opt = Optional::new(5);
let doubled = opt.map(|x| x * 2);
assert_eq!(doubled.into_option(), Some(10));
Sourcepub fn inspect<F>(self, f: F) -> Self
pub fn inspect<F>(self, f: F) -> Self
Calls the provided closure with the contained value (if any).
§Examples
use cel_cxx::Optional;
let opt = Optional::new(42);
let result = opt.inspect(|x| println!("Value: {}", x));
assert_eq!(result.into_option(), Some(42));
Sourcepub fn filter<P>(self, predicate: P) -> Self
pub fn filter<P>(self, predicate: P) -> Self
Returns the optional if it contains a value, otherwise returns an empty optional.
§Examples
use cel_cxx::Optional;
let opt = Optional::new(5);
let filtered = opt.filter(|&x| x > 3);
assert_eq!(filtered.into_option(), Some(5));
let opt = Optional::new(2);
let filtered = opt.filter(|&x| x > 3);
assert_eq!(filtered.into_option(), None);
Sourcepub fn or(self, other: Optional<T>) -> Optional<T>
pub fn or(self, other: Optional<T>) -> Optional<T>
Returns the optional if it contains a value, otherwise returns other
.
§Examples
use cel_cxx::Optional;
let some = Optional::new(2);
let none: Optional<i32> = Optional::none();
let other = Optional::new(100);
assert_eq!(some.or(other.clone()).into_option(), Some(2));
assert_eq!(none.or(other).into_option(), Some(100));
Sourcepub fn or_else<F>(self, f: F) -> Optional<T>
pub fn or_else<F>(self, f: F) -> Optional<T>
Returns the optional if it contains a value, otherwise calls f
and returns the result.
§Examples
use cel_cxx::Optional;
let none: Optional<i32> = Optional::none();
let result = none.or_else(|| Optional::new(42));
assert_eq!(result.into_option(), Some(42));
Sourcepub fn xor(self, other: Optional<T>) -> Optional<T>
pub fn xor(self, other: Optional<T>) -> Optional<T>
Returns Some
if exactly one of self
, other
is Some
, otherwise returns None
.
§Examples
use cel_cxx::Optional;
let some = Optional::new(2);
let none: Optional<i32> = Optional::none();
assert_eq!(some.clone().xor(none.clone()).into_option(), Some(2));
assert_eq!(none.xor(some).into_option(), Some(2));
Sourcepub fn and<U>(self, other: Optional<U>) -> Optional<U>
pub fn and<U>(self, other: Optional<U>) -> Optional<U>
Returns the optional if it contains a value, otherwise returns an empty optional of type U
.
§Examples
use cel_cxx::Optional;
let some = Optional::new(2);
let other = Optional::new("hello");
let result = some.and(other);
assert_eq!(result.into_option(), Some("hello"));
Sourcepub fn and_then<U, F>(self, f: F) -> Optional<U>
pub fn and_then<U, F>(self, f: F) -> Optional<U>
Returns an empty optional if the optional is empty, otherwise calls f
with the wrapped value and returns the result.
§Examples
use cel_cxx::Optional;
let opt = Optional::new(5);
let result = opt.and_then(|x| {
if x > 0 {
Optional::new(x * 2)
} else {
Optional::none()
}
});
assert_eq!(result.into_option(), Some(10));
Sourcepub fn take(&mut self) -> Optional<T>
pub fn take(&mut self) -> Optional<T>
Takes the value out of the optional, leaving an empty optional in its place.
§Examples
use cel_cxx::Optional;
let mut opt = Optional::new(42);
let taken = opt.take();
assert_eq!(taken.into_option(), Some(42));
assert_eq!(opt.into_option(), None);
Sourcepub fn take_if<P>(&mut self, predicate: P) -> Optional<T>
pub fn take_if<P>(&mut self, predicate: P) -> Optional<T>
Takes the value out of the optional if the predicate returns true
.
§Examples
use cel_cxx::Optional;
let mut opt = Optional::new(42);
let taken = opt.take_if(|x| *x > 40);
assert_eq!(taken.into_option(), Some(42));
Sourcepub fn replace(&mut self, value: T) -> Optional<T>
pub fn replace(&mut self, value: T) -> Optional<T>
Replaces the actual value in the optional with the value given in parameter, returning the old value if present.
§Examples
use cel_cxx::Optional;
let mut opt = Optional::new(42);
let old = opt.replace(100);
assert_eq!(old.into_option(), Some(42));
assert_eq!(opt.into_option(), Some(100));
Sourcepub fn zip<U>(self, other: Optional<U>) -> Optional<(T, U)>
pub fn zip<U>(self, other: Optional<U>) -> Optional<(T, U)>
Zips self
with another optional.
§Examples
use cel_cxx::Optional;
let opt1 = Optional::new(1);
let opt2 = Optional::new("hello");
let zipped = opt1.zip(opt2);
assert_eq!(zipped.into_option(), Some((1, "hello")));
Sourcepub fn as_deref(&self) -> Optional<&<T as Deref>::Target>where
T: Deref,
pub fn as_deref(&self) -> Optional<&<T as Deref>::Target>where
T: Deref,
Converts from Optional<T>
(or &Optional<T>
) to Optional<&T::Target>
.
§Examples
use cel_cxx::Optional;
let opt = Optional::new("hello".to_string());
let deref_opt = opt.as_deref();
assert_eq!(deref_opt.into_option(), Some("hello"));
Sourcepub fn as_deref_mut(&mut self) -> Optional<&mut <T as Deref>::Target>where
T: DerefMut,
pub fn as_deref_mut(&mut self) -> Optional<&mut <T as Deref>::Target>where
T: DerefMut,
Converts from Optional<T>
(or &mut Optional<T>
) to Optional<&mut T::Target>
.
§Examples
use cel_cxx::Optional;
let mut opt = Optional::new("hello".to_string());
let deref_mut_opt = opt.as_deref_mut();
// Can modify the dereferenced value
Source§impl<T, U> Optional<(T, U)>
impl<T, U> Optional<(T, U)>
Sourcepub fn unzip(self) -> (Optional<T>, Optional<U>)
pub fn unzip(self) -> (Optional<T>, Optional<U>)
Unzips an optional containing a tuple into a tuple of optionals.
§Examples
use cel_cxx::Optional;
let opt = Optional::new((1, "hello"));
let (opt1, opt2) = opt.unzip();
assert_eq!(opt1.into_option(), Some(1));
assert_eq!(opt2.into_option(), Some("hello"));
Source§impl<T> Optional<&T>
impl<T> Optional<&T>
Sourcepub fn copied(self) -> Optional<T>where
T: Copy,
pub fn copied(self) -> Optional<T>where
T: Copy,
Maps an Optional<&T>
to an Optional<T>
by copying the contents of the optional.
§Examples
use cel_cxx::Optional;
let opt_ref = Optional::new(&42);
let opt_owned = opt_ref.copied();
assert_eq!(opt_owned.into_option(), Some(42));
Sourcepub fn cloned(self) -> Optional<T>where
T: Clone,
pub fn cloned(self) -> Optional<T>where
T: Clone,
Maps an Optional<&T>
to an Optional<T>
by cloning the contents of the optional.
§Examples
use cel_cxx::Optional;
let hello_string = "hello".to_string();
let opt_ref = Optional::new(&hello_string);
let opt_owned = opt_ref.cloned();
assert_eq!(opt_owned.into_option(), Some("hello".to_string()));
Source§impl<T, E> Optional<Result<T, E>>
impl<T, E> Optional<Result<T, E>>
Sourcepub fn transpose(self) -> Result<Optional<T>, E>
pub fn transpose(self) -> Result<Optional<T>, E>
Transposes an Optional
of a Result
into a Result
of an Optional
.
§Examples
use cel_cxx::Optional;
let opt_result: Optional<Result<i32, &str>> = Optional::new(Ok(42));
let result_opt = opt_result.transpose();
assert_eq!(result_opt, Ok(Optional::new(42)));
Methods from Deref<Target = Option<T>>§
1.0.0 · Sourcepub fn as_ref(&self) -> Option<&T>
pub fn as_ref(&self) -> Option<&T>
Converts from &Option<T>
to Option<&T>
.
§Examples
Calculates the length of an Option<String>
as an Option<usize>
without moving the String
. The map
method takes the self
argument by value,
consuming the original, so this technique uses as_ref
to first take an Option
to a
reference to the value inside the original.
let text: Option<String> = Some("Hello, world!".to_string());
// First, cast `Option<String>` to `Option<&String>` with `as_ref`,
// then consume *that* with `map`, leaving `text` on the stack.
let text_length: Option<usize> = text.as_ref().map(|s| s.len());
println!("still can print text: {text:?}");
1.0.0 · Sourcepub fn as_mut(&mut self) -> Option<&mut T>
pub fn as_mut(&mut self) -> Option<&mut T>
Converts from &mut Option<T>
to Option<&mut T>
.
§Examples
let mut x = Some(2);
match x.as_mut() {
Some(v) => *v = 42,
None => {},
}
assert_eq!(x, Some(42));
1.75.0 · Sourcepub fn as_slice(&self) -> &[T]
pub fn as_slice(&self) -> &[T]
Returns a slice of the contained value, if any. If this is None
, an
empty slice is returned. This can be useful to have a single type of
iterator over an Option
or slice.
Note: Should you have an Option<&T>
and wish to get a slice of T
,
you can unpack it via opt.map_or(&[], std::slice::from_ref)
.
§Examples
assert_eq!(
[Some(1234).as_slice(), None.as_slice()],
[&[1234][..], &[][..]],
);
The inverse of this function is (discounting
borrowing) [_]::first
:
for i in [Some(1234_u16), None] {
assert_eq!(i.as_ref(), i.as_slice().first());
}
1.75.0 · Sourcepub fn as_mut_slice(&mut self) -> &mut [T]
pub fn as_mut_slice(&mut self) -> &mut [T]
Returns a mutable slice of the contained value, if any. If this is
None
, an empty slice is returned. This can be useful to have a
single type of iterator over an Option
or slice.
Note: Should you have an Option<&mut T>
instead of a
&mut Option<T>
, which this method takes, you can obtain a mutable
slice via opt.map_or(&mut [], std::slice::from_mut)
.
§Examples
assert_eq!(
[Some(1234).as_mut_slice(), None.as_mut_slice()],
[&mut [1234][..], &mut [][..]],
);
The result is a mutable slice of zero or one items that points into
our original Option
:
let mut x = Some(1234);
x.as_mut_slice()[0] += 1;
assert_eq!(x, Some(1235));
The inverse of this method (discounting borrowing)
is [_]::first_mut
:
assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123))
1.40.0 · Sourcepub fn as_deref(&self) -> Option<&<T as Deref>::Target>where
T: Deref,
pub fn as_deref(&self) -> Option<&<T as Deref>::Target>where
T: Deref,
Converts from Option<T>
(or &Option<T>
) to Option<&T::Target>
.
Leaves the original Option in-place, creating a new one with a reference
to the original one, additionally coercing the contents via Deref
.
§Examples
let x: Option<String> = Some("hey".to_owned());
assert_eq!(x.as_deref(), Some("hey"));
let x: Option<String> = None;
assert_eq!(x.as_deref(), None);
1.40.0 · Sourcepub fn as_deref_mut(&mut self) -> Option<&mut <T as Deref>::Target>where
T: DerefMut,
pub fn as_deref_mut(&mut self) -> Option<&mut <T as Deref>::Target>where
T: DerefMut,
Converts from Option<T>
(or &mut Option<T>
) to Option<&mut T::Target>
.
Leaves the original Option
in-place, creating a new one containing a mutable reference to
the inner type’s Deref::Target
type.
§Examples
let mut x: Option<String> = Some("hey".to_owned());
assert_eq!(x.as_deref_mut().map(|x| {
x.make_ascii_uppercase();
x
}), Some("HEY".to_owned().as_mut_str()));
1.0.0 · Sourcepub fn iter(&self) -> Iter<'_, T>
pub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
§Examples
let x = Some(4);
assert_eq!(x.iter().next(), Some(&4));
let x: Option<u32> = None;
assert_eq!(x.iter().next(), None);
1.0.0 · Sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
pub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
§Examples
let mut x = Some(4);
match x.iter_mut().next() {
Some(v) => *v = 42,
None => {},
}
assert_eq!(x, Some(42));
let mut x: Option<u32> = None;
assert_eq!(x.iter_mut().next(), None);
1.53.0 · Sourcepub fn insert(&mut self, value: T) -> &mut T
pub fn insert(&mut self, value: T) -> &mut T
Inserts value
into the option, then returns a mutable reference to it.
If the option already contains a value, the old value is dropped.
See also Option::get_or_insert
, which doesn’t update the value if
the option already contains Some
.
§Example
let mut opt = None;
let val = opt.insert(1);
assert_eq!(*val, 1);
assert_eq!(opt.unwrap(), 1);
let val = opt.insert(2);
assert_eq!(*val, 2);
*val = 3;
assert_eq!(opt.unwrap(), 3);
1.20.0 · Sourcepub fn get_or_insert(&mut self, value: T) -> &mut T
pub fn get_or_insert(&mut self, value: T) -> &mut T
Inserts value
into the option if it is None
, then
returns a mutable reference to the contained value.
See also Option::insert
, which updates the value even if
the option already contains Some
.
§Examples
let mut x = None;
{
let y: &mut u32 = x.get_or_insert(5);
assert_eq!(y, &5);
*y = 7;
}
assert_eq!(x, Some(7));
1.83.0 · Sourcepub fn get_or_insert_default(&mut self) -> &mut Twhere
T: Default,
pub fn get_or_insert_default(&mut self) -> &mut Twhere
T: Default,
1.20.0 · Sourcepub fn get_or_insert_with<F>(&mut self, f: F) -> &mut Twhere
F: FnOnce() -> T,
pub fn get_or_insert_with<F>(&mut self, f: F) -> &mut Twhere
F: FnOnce() -> T,
1.80.0 · Sourcepub fn take_if<P>(&mut self, predicate: P) -> Option<T>
pub fn take_if<P>(&mut self, predicate: P) -> Option<T>
Takes the value out of the option, but only if the predicate evaluates to
true
on a mutable reference to the value.
In other words, replaces self
with None
if the predicate returns true
.
This method operates similar to Option::take
but conditional.
§Examples
let mut x = Some(42);
let prev = x.take_if(|v| if *v == 42 {
*v += 1;
false
} else {
false
});
assert_eq!(x, Some(43));
assert_eq!(prev, None);
let prev = x.take_if(|v| *v == 43);
assert_eq!(x, None);
assert_eq!(prev, Some(43));
1.31.0 · Sourcepub fn replace(&mut self, value: T) -> Option<T>
pub fn replace(&mut self, value: T) -> Option<T>
Replaces the actual value in the option by the value given in parameter,
returning the old value if present,
leaving a Some
in its place without deinitializing either one.
§Examples
let mut x = Some(2);
let old = x.replace(5);
assert_eq!(x, Some(5));
assert_eq!(old, Some(2));
let mut x = None;
let old = x.replace(3);
assert_eq!(x, Some(3));
assert_eq!(old, None);
Trait Implementations§
Source§impl<'a, T: TryFrom<&'a Value, Error = FromValueError> + TypedValue> TryFrom<&'a Value> for Optional<T>
impl<'a, T: TryFrom<&'a Value, Error = FromValueError> + TypedValue> TryFrom<&'a Value> for Optional<T>
Source§impl<T: TryFrom<Value, Error = FromValueError> + TypedValue> TryFrom<Value> for Optional<T>
impl<T: TryFrom<Value, Error = FromValueError> + TypedValue> TryFrom<Value> for Optional<T>
Source§impl<T: TypedValue> TypedValue for Optional<T>
impl<T: TypedValue> TypedValue for Optional<T>
Source§fn value_type() -> ValueType
fn value_type() -> ValueType
impl<T> StructuralPartialEq for Optional<T>
Auto Trait Implementations§
impl<T> Freeze for Optional<T>
impl<T> RefUnwindSafe for Optional<T>where
T: RefUnwindSafe,
impl<T> Send for Optional<T>where
T: Send,
impl<T> Sync for Optional<T>where
T: Sync,
impl<T> Unpin for Optional<T>
impl<T> UnwindSafe for Optional<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more