Skip to main content

cel_cxx/values/
mod.rs

1//! CEL Value Types and Operations
2//!
3//! This module provides the core value types used in CEL expressions, along with
4//! comprehensive conversion and manipulation utilities. It forms the foundation
5//! of the CEL type system, supporting both primitive and composite data types.
6//!
7//! # Value Type Hierarchy
8//!
9//! The CEL value system is built around several core types:
10//!
11//! ## Primitive Types
12//! - **Null**: Represents absent values (`null`)
13//! - **Bool**: Boolean values (`true`, `false`)
14//! - **Int**: 64-bit signed integers (`i64`)
15//! - **Uint**: 64-bit unsigned integers (`u64`)
16//! - **Double**: IEEE 754 double-precision floating point (`f64`)
17//! - **String**: UTF-8 encoded strings
18//! - **Bytes**: Arbitrary byte sequences
19//!
20//! ## Time Types
21//! - **Duration**: Protocol Buffers Duration type (represents time spans)
22//! - **Timestamp**: Protocol Buffers Timestamp type (represents points in time)
23//!
24//! ## Composite Types
25//! - **List**: Ordered collections of values (`Vec<Value>`)
26//! - **Map**: Key-value mappings (`HashMap<MapKey, Value>`)
27//! - **Struct**: Serialized message types (e.g. Protocol Buffers messages)
28//! - **Optional**: Wrapper for optional values
29//!
30//! ## Special Types
31//! - **Type**: Meta-type representing CEL types themselves
32//! - **Error**: Error values from failed operations
33//! - **Unknown**: Partially evaluated expressions (not yet implemented)
34//! - **Opaque**: Custom user-defined types
35//!
36//! # Type Conversion System
37//!
38//! The module provides a comprehensive type conversion system built on Generic
39//! Associated Types (GATs) for safe, zero-cost conversions between Rust and CEL types.
40//!
41//! ## Core Conversion Traits
42//!
43//! - [`TypedValue`]: Types that have a known CEL type
44//! - [`IntoValue`]: Convert Rust types to CEL values
45//! - [`FromValue`]: Convert CEL values to Rust types (with GATs)
46//! - [`IntoConstant`]: Convert to compile-time constants
47//!
48//! ## Map Key Conversion
49//!
50//! - [`TypedMapKey`]: Types that can be used as map keys
51//! - [`IntoMapKey`]: Convert to CEL map keys
52//! - [`FromMapKey`]: Convert from CEL map keys
53//!
54//! # Memory Management and Lifetimes
55//!
56//! The value system is designed for efficient memory usage:
57//! - **Zero-copy conversions** where possible (`&str` from `String` values)
58//! - **Controlled lifetime erasure** for safe reference handling
59//! - **Reference counting** for shared data structures
60//! - **Clone-on-write** semantics for expensive operations
61//!
62//! # Examples
63//!
64//! ## Basic Value Creation and Conversion
65//!
66//! ```rust
67//! use cel_cxx::{Value, IntoValue, FromValue};
68//!
69//! // Create values from Rust types
70//! let null_val = Value::Null;
71//! let bool_val = true.into_value();
72//! let int_val = 42i64.into_value();
73//! let string_val = "hello".into_value();
74//!
75//! // Convert back to Rust types
76//! let rust_bool: bool = bool_val.try_into()?;
77//! let rust_int: i64 = int_val.try_into()?;
78//! let rust_string: String = string_val.try_into()?;
79//! # Ok::<(), cel_cxx::Error>(())
80//! ```
81//!
82//! ## Working with Collections
83//!
84//! ```rust
85//! use cel_cxx::{Value, MapKey};
86//! use std::collections::HashMap;
87//!
88//! // Create a list
89//! let list = Value::List(vec![
90//!     Value::Int(1),
91//!     Value::Int(2),
92//!     Value::Int(3),
93//! ]);
94//!
95//! // Create a map
96//! let mut map = HashMap::new();
97//! map.insert(MapKey::String("name".to_string().into()), Value::String("Alice".to_string().into()));
98//! map.insert(MapKey::String("age".to_string().into()), Value::Int(30));
99//! let map_val = Value::Map(map);
100//! ```
101//!
102//! ## Reference Conversions with Lifetimes
103//!
104//! ```rust
105//! use cel_cxx::{Value, FromValue};
106//!
107//! let string_val = Value::String("hello world".to_string().into());
108//!
109//! // Convert to borrowed string slice (zero-copy)
110//! let borrowed_str = <&str>::from_value(&string_val)?;
111//! assert_eq!(borrowed_str, "hello world");
112//!
113//! // The original value owns the data
114//! drop(string_val); // borrowed_str is no longer valid after this
115//! # Ok::<(), cel_cxx::Error>(())
116//! ```
117//!
118//! ## Custom Type Integration
119//!
120//! For custom opaque types, use the derive macro instead of manual implementation:
121//!
122//! ```rust
123//! use cel_cxx::{Opaque, IntoValue, FromValue};
124//!
125//! #[derive(Opaque, Debug, Clone, PartialEq)]
126//! #[cel_cxx(display)]
127//! struct UserId(u64);
128//!
129//! // All necessary traits (TypedValue, IntoValue, FromValue) are automatically implemented
130//!
131//! // Usage
132//! let user_id = UserId(12345);
133//! let value = user_id.into_value();
134//! let converted_back = UserId::from_value(&value)?;
135//! # Ok::<(), cel_cxx::Error>(())
136//! ```
137//!
138//! # Error Handling
139//!
140//! The module provides comprehensive error handling through:
141//! - [`FromValueError`]: Conversion failures from CEL values
142//! - [`FromMapKeyError`]: Map key conversion failures
143//! - Detailed error messages with type information
144//!
145//! ## Error Example
146//!
147//! ```rust
148//! use cel_cxx::{Value, FromValue, FromValueError};
149//!
150//! let string_val = Value::String("not a number".to_string().into());
151//! let result = i64::from_value(&string_val);
152//!
153//! match result {
154//!     Ok(num) => println!("Converted: {}", num),
155//!     Err(e) => {
156//!         println!("{}", e);
157//!     }
158//! }
159//! ```
160//!
161//! # Performance Characteristics
162//!
163//! - **Conversion overhead**: Minimal for primitive types, optimized for references
164//! - **Memory usage**: Efficient representation, shared ownership where beneficial
165//! - **Type checking**: Compile-time where possible, fast runtime checks otherwise
166//! - **Collection operations**: Optimized for common access patterns
167//!
168//! # Thread Safety
169//!
170//! All value types are thread-safe:
171//! - Values can be shared across threads (`Send + Sync`)
172//! - Reference counting handles concurrent access safely
173//! - Conversion operations are atomic where required
174
175mod display;
176mod impls;
177mod opaque;
178mod optional;
179mod traits;
180
181use crate::types::*;
182use crate::{Error, Kind};
183use std::collections::HashMap;
184
185pub use opaque::*;
186pub use optional::*;
187pub use traits::*;
188
189/// CEL string value type.
190pub type StringValue = arc_slice::ArcStr;
191
192/// CEL bytes value type.
193pub type BytesValue = arc_slice::ArcBytes;
194
195/// CEL duration type.
196pub type Duration = chrono::Duration;
197
198/// CEL timestamp type.
199pub type Timestamp = chrono::DateTime<chrono::Utc>;
200
201/// CEL list value type.
202pub type ListValue = Vec<Value>;
203
204/// CEL map value type.
205pub type MapValue = HashMap<MapKey, Value>;
206
207/// CEL struct value representing a serialized message.
208///
209/// The message is stored as its fully-qualified type name plus serialized bytes.
210/// Deserialization into C++ `MessageValue` happens at the FFI boundary when the
211/// value is passed to cel-cpp for evaluation.
212#[derive(Clone, PartialEq)]
213pub struct StructValue {
214    type_name: String,
215    bytes: Vec<u8>,
216}
217
218impl StructValue {
219    /// Creates a new `StructValue` from a type name and serialized bytes.
220    pub fn from_bytes(type_name: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
221        Self {
222            type_name: type_name.into(),
223            bytes: bytes.into(),
224        }
225    }
226
227    /// Returns the fully qualified message type name (e.g. `"my.package.MyMessage"`).
228    pub fn type_name(&self) -> &str {
229        &self.type_name
230    }
231
232    /// Returns the serialized bytes of the message.
233    pub fn to_bytes(&self) -> &[u8] {
234        &self.bytes
235    }
236}
237
238impl std::fmt::Debug for StructValue {
239    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
240        f.debug_struct("StructValue")
241            .field("type_name", &self.type_name())
242            .field("bytes_len", &self.to_bytes().len())
243            .finish()
244    }
245}
246
247/// CEL opaque value type.
248pub type OpaqueValue = Box<dyn Opaque>;
249
250/// CEL optional value type.
251pub type OptionalValue = Optional<Value>;
252
253/// Main CEL value type.
254///
255/// `Value` is the core value type of the CEL expression system, supporting all data types
256/// defined by the CEL specification. Each variant corresponds to a CEL basic type or composite type.
257///
258/// # CEL Type Mapping
259///
260/// - `Null` → CEL null
261/// - `Bool` → CEL bool
262/// - `Int` → CEL int (64-bit signed integer)
263/// - `Uint` → CEL uint (64-bit unsigned integer)
264/// - `Double` → CEL double (64-bit floating point)
265/// - `String` → CEL string
266/// - `Bytes` → CEL bytes
267/// - `Duration` → CEL duration (Protocol Buffers Duration)
268/// - `Timestamp` → CEL timestamp (Protocol Buffers Timestamp)
269/// - `List` → CEL list
270/// - `Map` → CEL map
271/// - `Type` → CEL type (type value)
272/// - `Error` → CEL error
273/// - `Opaque` → Opaque custom types
274/// - `Optional` → Optional value type
275///
276/// # Examples
277///
278/// ```rust,no_run
279/// use cel_cxx::Value;
280///
281/// // Basic types
282/// let null_val = Value::Null;
283/// let bool_val = Value::Bool(true);
284/// let int_val = Value::Int(-42);
285/// let uint_val = Value::Uint(42u64);
286/// let double_val = Value::Double(3.14);
287/// let string_val = Value::String("hello".to_string().into());
288/// let bytes_val = Value::Bytes(vec![1, 2, 3].into());
289///
290/// // Time types
291/// let duration = Value::Duration(chrono::Duration::seconds(30));
292/// let timestamp = Value::Timestamp(chrono::Utc::now());
293///
294/// // Container types
295/// let list = Value::List(vec![Value::Int(1), Value::Int(2)]);
296/// ```
297#[derive(Clone, Debug, PartialEq, Default)]
298pub enum Value {
299    /// Null value
300    #[default]
301    Null,
302
303    /// Boolean value
304    Bool(bool),
305
306    /// Signed 64-bit integer
307    Int(i64),
308
309    /// Unsigned 64-bit integer
310    Uint(u64),
311
312    /// 64-bit floating point number
313    Double(f64),
314
315    /// UTF-8 string
316    String(StringValue),
317
318    /// Byte array
319    Bytes(BytesValue),
320
321    /// Struct (serialized message)
322    Struct(StructValue),
323
324    /// Duration (Protocol Buffers Duration)
325    Duration(Duration),
326
327    /// Timestamp (Protocol Buffers Timestamp)
328    Timestamp(Timestamp),
329
330    /// List of values
331    List(ListValue),
332
333    /// Key-value map
334    Map(MapValue),
335
336    /// Unknown type (not yet implemented)
337    Unknown(()),
338
339    /// CEL type value
340    Type(ValueType),
341
342    /// Error value
343    Error(Error),
344
345    /// Opaque custom type
346    Opaque(OpaqueValue),
347
348    /// Optional value type
349    Optional(OptionalValue),
350}
351
352impl Value {
353    /// Returns the kind of this value.
354    ///
355    /// Returns the corresponding [`Kind`] enum for fast type checking.
356    ///
357    /// # Examples
358    ///
359    /// ```rust,no_run
360    /// use cel_cxx::{Value, Kind};
361    ///
362    /// let val = Value::String("hello".to_string().into());
363    /// assert_eq!(val.kind(), Kind::String);
364    ///
365    /// let val = Value::List(vec![]);
366    /// assert_eq!(val.kind(), Kind::List);
367    /// ```
368    pub fn kind(&self) -> Kind {
369        match &self {
370            Value::Null => Kind::Null,
371            Value::Bool(_) => Kind::Bool,
372            Value::Int(_i) => Kind::Int,
373            Value::Uint(_u) => Kind::Uint,
374            Value::Double(_d) => Kind::Double,
375            Value::String(_s) => Kind::String,
376            Value::Bytes(_b) => Kind::Bytes,
377            Value::Struct(_s) => Kind::Struct,
378            Value::Duration(_d) => Kind::Duration,
379            Value::Timestamp(_t) => Kind::Timestamp,
380            Value::List(_l) => Kind::List,
381            Value::Map(_m) => Kind::Map,
382            Value::Unknown(_u) => Kind::Unknown,
383            Value::Type(_t) => Kind::Type,
384            Value::Error(_e) => Kind::Error,
385            Value::Opaque(_) | Value::Optional(_) => Kind::Opaque,
386        }
387    }
388
389    /// Returns the concrete type of this value.
390    ///
391    /// Returns detailed [`ValueType`] information including generic parameters.
392    /// For container types (List, Map), infers element or key-value types.
393    ///
394    /// # Type Inference Rules
395    ///
396    /// - **List**: Returns specific `List<T>` if all elements have the same type; otherwise `List<dyn>`
397    /// - **Map**: Infers key and value types; uses `dyn` types if inconsistent
398    /// - **Optional**: Infers type from contained value; uses `Optional<dyn>` for empty values
399    ///
400    /// # Examples
401    ///
402    /// ```rust,no_run
403    /// use cel_cxx::{Value, ValueType, ListType};
404    ///
405    /// let val = Value::String("hello".to_string().into());
406    /// assert_eq!(val.value_type(), ValueType::String);
407    ///
408    /// // Homogeneous list
409    /// let list = Value::List(vec![Value::Int(1), Value::Int(2)]);
410    /// assert_eq!(list.value_type(), ValueType::List(ListType::new(ValueType::Int)));
411    ///
412    /// // Heterogeneous list
413    /// let mixed_list = Value::List(vec![Value::Int(1), Value::String("hello".to_string().into())]);
414    /// assert_eq!(mixed_list.value_type(), ValueType::List(ListType::new(ValueType::Dyn)));
415    /// ```
416    pub fn value_type(&self) -> ValueType {
417        match &self {
418            Value::Null => ValueType::Null,
419            Value::Bool(_) => ValueType::Bool,
420            Value::Int(_) => ValueType::Int,
421            Value::Uint(_) => ValueType::Uint,
422            Value::Double(_) => ValueType::Double,
423            Value::String(_) => ValueType::String,
424            Value::Bytes(_) => ValueType::Bytes,
425            Value::Struct(s) => {
426                ValueType::Struct(crate::types::StructType::new(s.type_name()))
427            }
428            Value::Duration(_) => ValueType::Duration,
429            Value::Timestamp(_) => ValueType::Timestamp,
430            Value::List(list) => {
431                let mut iter = list.iter();
432                if let Some(v) = iter.next() {
433                    let elem_type = v.value_type();
434                    if elem_type == ValueType::Dyn {
435                        return ValueType::List(ListType::new(ValueType::Dyn));
436                    }
437                    for v in iter {
438                        if v.value_type() != elem_type {
439                            return ValueType::List(ListType::new(ValueType::Dyn));
440                        }
441                    }
442                    return ValueType::List(ListType::new(elem_type));
443                }
444                ValueType::List(ListType::new(ValueType::Dyn))
445            }
446            Value::Map(m) => {
447                let mut iter = m.iter();
448                if let Some((k, v)) = iter.next() {
449                    let mut key_type = Some(k.mapkey_type());
450                    let mut val_type = v.value_type();
451                    for (k, v) in iter {
452                        if let Some(prev_key_type) = key_type.clone() {
453                            if k.mapkey_type() != prev_key_type {
454                                key_type = None;
455                            }
456                        }
457                        if val_type != ValueType::Dyn && v.value_type() != val_type {
458                            val_type = ValueType::Dyn;
459                        }
460
461                        if key_type.is_none() && val_type == ValueType::Dyn {
462                            break;
463                        }
464                    }
465                    ValueType::Map(MapType::new(key_type.unwrap_or(MapKeyType::Dyn), val_type))
466                } else {
467                    ValueType::Map(MapType::new(MapKeyType::Dyn, ValueType::Dyn))
468                }
469            }
470            Value::Unknown(_u) => ValueType::Unknown,
471            Value::Opaque(o) => ValueType::Opaque(o.opaque_type()),
472            Value::Optional(opt) => {
473                if let Some(v) = opt.as_option() {
474                    return ValueType::Optional(OptionalType::new(v.value_type()));
475                }
476                ValueType::Optional(OptionalType::new(ValueType::Dyn))
477            }
478            Value::Type(_t) => ValueType::Type(TypeType::new(None)),
479            Value::Error(_e) => ValueType::Error,
480        }
481    }
482
483    /// Returns true if this value is a null value.
484    pub fn is_null(&self) -> bool {
485        matches!(self, Value::Null)
486    }
487
488    /// Returns true if this value is a boolean value.
489    pub fn is_bool(&self) -> bool {
490        matches!(self, Value::Bool(_))
491    }
492
493    /// Returns true if this value is a signed integer value.
494    pub fn is_int(&self) -> bool {
495        matches!(self, Value::Int(_))
496    }
497
498    /// Returns true if this value is an unsigned integer value.
499    pub fn is_uint(&self) -> bool {
500        matches!(self, Value::Uint(_))
501    }
502
503    /// Returns true if this value is a double value.
504    pub fn is_double(&self) -> bool {
505        matches!(self, Value::Double(_))
506    }
507
508    /// Returns true if this value is a string value.
509    pub fn is_string(&self) -> bool {
510        matches!(self, Value::String(_))
511    }
512
513    /// Returns true if this value is a byte array value.
514    pub fn is_bytes(&self) -> bool {
515        matches!(self, Value::Bytes(_))
516    }
517
518    /// Returns true if this value is a struct value.
519    pub fn is_struct(&self) -> bool {
520        matches!(self, Value::Struct(_))
521    }
522
523    /// Returns true if this value is a duration value.
524    pub fn is_duration(&self) -> bool {
525        matches!(self, Value::Duration(_))
526    }
527
528    /// Returns true if this value is a timestamp value.
529    pub fn is_timestamp(&self) -> bool {
530        matches!(self, Value::Timestamp(_))
531    }
532
533    /// Returns true if this value is a list value.
534    pub fn is_list(&self) -> bool {
535        matches!(self, Value::List(_))
536    }
537
538    /// Returns true if this value is a map value.
539    pub fn is_map(&self) -> bool {
540        matches!(self, Value::Map(_))
541    }
542
543    /// Returns true if this value is an unknown value.
544    pub fn is_unknown(&self) -> bool {
545        matches!(self, Value::Unknown(_))
546    }
547
548    /// Returns true if this value is a type value.
549    pub fn is_type(&self) -> bool {
550        matches!(self, Value::Type(_))
551    }
552
553    /// Returns true if this value is an error value.
554    pub fn is_error(&self) -> bool {
555        matches!(self, Value::Error(_))
556    }
557
558    /// Returns true if this value is an opaque value.
559    pub fn is_opaque(&self) -> bool {
560        matches!(self, Value::Opaque(_))
561    }
562
563    /// Returns true if this value is an optional value.
564    pub fn is_optional(&self) -> bool {
565        matches!(self, Value::Optional(_))
566    }
567
568    /// Returns the boolean value if this value is a boolean value.
569    pub fn as_bool(&self) -> Option<&bool> {
570        match self {
571            Value::Bool(b) => Some(b),
572            _ => None,
573        }
574    }
575
576    /// Returns the signed integer value if this value is a signed integer value.
577    pub fn as_int(&self) -> Option<&i64> {
578        match self {
579            Value::Int(i) => Some(i),
580            _ => None,
581        }
582    }
583
584    /// Returns the unsigned integer value if this value is an unsigned integer value.
585    pub fn as_uint(&self) -> Option<&u64> {
586        match self {
587            Value::Uint(u) => Some(u),
588            _ => None,
589        }
590    }
591
592    /// Returns the double value if this value is a double value.
593    pub fn as_double(&self) -> Option<&f64> {
594        match self {
595            Value::Double(d) => Some(d),
596            _ => None,
597        }
598    }
599
600    /// Returns the string value if this value is a string value.
601    pub fn as_string(&self) -> Option<&StringValue> {
602        match self {
603            Value::String(s) => Some(s),
604            _ => None,
605        }
606    }
607
608    /// Returns the byte array value if this value is a byte array value.
609    pub fn as_bytes(&self) -> Option<&BytesValue> {
610        match self {
611            Value::Bytes(b) => Some(b),
612            _ => None,
613        }
614    }
615
616    /// Returns the struct value if this value is a struct value.
617    pub fn as_struct(&self) -> Option<&StructValue> {
618        match self {
619            Value::Struct(s) => Some(s),
620            _ => None,
621        }
622    }
623
624    /// Returns the duration value if this value is a duration value.
625    pub fn as_duration(&self) -> Option<&Duration> {
626        match self {
627            Value::Duration(d) => Some(d),
628            _ => None,
629        }
630    }
631
632    /// Returns the timestamp value if this value is a timestamp value.
633    pub fn as_timestamp(&self) -> Option<&Timestamp> {
634        match self {
635            Value::Timestamp(t) => Some(t),
636            _ => None,
637        }
638    }
639
640    /// Returns the list value if this value is a list value.
641    pub fn as_list(&self) -> Option<&ListValue> {
642        match self {
643            Value::List(l) => Some(l),
644            _ => None,
645        }
646    }
647
648    /// Returns the map value if this value is a map value.
649    pub fn as_map(&self) -> Option<&MapValue> {
650        match self {
651            Value::Map(m) => Some(m),
652            _ => None,
653        }
654    }
655
656    /// Returns the unknown value if this value is an unknown value.
657    pub fn as_unknown(&self) -> Option<&()> {
658        match self {
659            Value::Unknown(u) => Some(u),
660            _ => None,
661        }
662    }
663
664    /// Returns the type value if this value is a type value.
665    pub fn as_type(&self) -> Option<&ValueType> {
666        match self {
667            Value::Type(t) => Some(t),
668            _ => None,
669        }
670    }
671
672    /// Returns the error value if this value is an error value.
673    pub fn as_error(&self) -> Option<&Error> {
674        match self {
675            Value::Error(e) => Some(e),
676            _ => None,
677        }
678    }
679
680    /// Returns the opaque value if this value is an opaque value.
681    pub fn as_opaque(&self) -> Option<&OpaqueValue> {
682        match self {
683            Value::Opaque(o) => Some(o),
684            _ => None,
685        }
686    }
687
688    /// Returns the optional value if this value is an optional value.
689    pub fn as_optional(&self) -> Option<&OptionalValue> {
690        match self {
691            Value::Optional(o) => Some(o),
692            _ => None,
693        }
694    }
695
696    /// Returns a mutable reference to the boolean value if this value is a boolean value.
697    pub fn as_bool_mut(&mut self) -> Option<&mut bool> {
698        match self {
699            Value::Bool(b) => Some(b),
700            _ => None,
701        }
702    }
703
704    /// Returns a mutable reference to the signed integer value if this value is a signed integer value.
705    pub fn as_int_mut(&mut self) -> Option<&mut i64> {
706        match self {
707            Value::Int(i) => Some(i),
708            _ => None,
709        }
710    }
711
712    /// Returns a mutable reference to the unsigned integer value if this value is an unsigned integer value.
713    pub fn as_uint_mut(&mut self) -> Option<&mut u64> {
714        match self {
715            Value::Uint(u) => Some(u),
716            _ => None,
717        }
718    }
719
720    /// Returns a mutable reference to the double value if this value is a double value.
721    pub fn as_double_mut(&mut self) -> Option<&mut f64> {
722        match self {
723            Value::Double(d) => Some(d),
724            _ => None,
725        }
726    }
727
728    /// Returns a mutable reference to the string value if this value is a string value.
729    pub fn as_string_mut(&mut self) -> Option<&mut StringValue> {
730        match self {
731            Value::String(s) => Some(s),
732            _ => None,
733        }
734    }
735
736    /// Returns a mutable reference to the byte array value if this value is a byte array value.
737    pub fn as_bytes_mut(&mut self) -> Option<&mut BytesValue> {
738        match self {
739            Value::Bytes(b) => Some(b),
740            _ => None,
741        }
742    }
743
744    /// Returns a mutable reference to the duration value if this value is a duration value.
745    pub fn as_duration_mut(&mut self) -> Option<&mut Duration> {
746        match self {
747            Value::Duration(d) => Some(d),
748            _ => None,
749        }
750    }
751
752    /// Returns a mutable reference to the timestamp value if this value is a timestamp value.
753    pub fn as_timestamp_mut(&mut self) -> Option<&mut Timestamp> {
754        match self {
755            Value::Timestamp(t) => Some(t),
756            _ => None,
757        }
758    }
759
760    /// Returns a mutable reference to the list value if this value is a list value.
761    pub fn as_list_mut(&mut self) -> Option<&mut ListValue> {
762        match self {
763            Value::List(l) => Some(l),
764            _ => None,
765        }
766    }
767
768    /// Returns a mutable reference to the map value if this value is a map value.
769    pub fn as_map_mut(&mut self) -> Option<&mut MapValue> {
770        match self {
771            Value::Map(m) => Some(m),
772            _ => None,
773        }
774    }
775
776    /// Returns a mutable reference to the unknown value if this value is an unknown value.
777    pub fn as_unknown_mut(&mut self) -> Option<&mut ()> {
778        match self {
779            Value::Unknown(u) => Some(u),
780            _ => None,
781        }
782    }
783
784    /// Returns a mutable reference to the type value if this value is a type value.
785    pub fn as_type_mut(&mut self) -> Option<&mut ValueType> {
786        match self {
787            Value::Type(t) => Some(t),
788            _ => None,
789        }
790    }
791
792    /// Returns a mutable reference to the error value if this value is an error value.
793    pub fn as_error_mut(&mut self) -> Option<&mut Error> {
794        match self {
795            Value::Error(e) => Some(e),
796            _ => None,
797        }
798    }
799
800    /// Returns a mutable reference to the opaque value if this value is an opaque value.
801    pub fn as_opaque_mut(&mut self) -> Option<&mut OpaqueValue> {
802        match self {
803            Value::Opaque(o) => Some(o),
804            _ => None,
805        }
806    }
807
808    /// Returns a mutable reference to the optional value if this value is an optional value.
809    pub fn as_optional_mut(&mut self) -> Option<&mut OptionalValue> {
810        match self {
811            Value::Optional(o) => Some(o),
812            _ => None,
813        }
814    }
815
816    /// Converts the value to a null value.
817    pub fn into_null(self) -> Option<()> {
818        match self {
819            Value::Null => Some(()),
820            _ => None,
821        }
822    }
823
824    /// Converts the value to a boolean value.
825    pub fn into_bool(self) -> Option<bool> {
826        match self {
827            Value::Bool(b) => Some(b),
828            _ => None,
829        }
830    }
831
832    /// Converts the value to a signed integer value.
833    pub fn into_int(self) -> Option<i64> {
834        match self {
835            Value::Int(i) => Some(i),
836            _ => None,
837        }
838    }
839
840    /// Converts the value to an unsigned integer value.
841    pub fn into_uint(self) -> Option<u64> {
842        match self {
843            Value::Uint(u) => Some(u),
844            _ => None,
845        }
846    }
847
848    /// Converts the value to a double value.
849    pub fn into_double(self) -> Option<f64> {
850        match self {
851            Value::Double(d) => Some(d),
852            _ => None,
853        }
854    }
855
856    /// Converts the value to a string value.
857    pub fn into_string(self) -> Option<StringValue> {
858        match self {
859            Value::String(s) => Some(s),
860            _ => None,
861        }
862    }
863
864    /// Converts the value to a byte array value.
865    pub fn into_bytes(self) -> Option<BytesValue> {
866        match self {
867            Value::Bytes(b) => Some(b),
868            _ => None,
869        }
870    }
871
872    /// Converts the value to a struct value.
873    pub fn into_struct(self) -> Option<StructValue> {
874        match self {
875            Value::Struct(s) => Some(s),
876            _ => None,
877        }
878    }
879
880    /// Converts the value to a duration value.
881    pub fn into_duration(self) -> Option<Duration> {
882        match self {
883            Value::Duration(d) => Some(d),
884            _ => None,
885        }
886    }
887
888    /// Converts the value to a timestamp value.
889    pub fn into_timestamp(self) -> Option<Timestamp> {
890        match self {
891            Value::Timestamp(t) => Some(t),
892            _ => None,
893        }
894    }
895
896    /// Converts the value to a list value.
897    pub fn into_list(self) -> Option<ListValue> {
898        match self {
899            Value::List(l) => Some(l),
900            _ => None,
901        }
902    }
903
904    /// Converts the value to a map value.
905    pub fn into_map(self) -> Option<MapValue> {
906        match self {
907            Value::Map(m) => Some(m),
908            _ => None,
909        }
910    }
911
912    /// Converts the value to an unknown value.
913    pub fn into_unknown(self) -> Option<()> {
914        match self {
915            Value::Unknown(u) => Some(u),
916            _ => None,
917        }
918    }
919
920    /// Converts the value to a type value.
921    pub fn into_type(self) -> Option<ValueType> {
922        match self {
923            Value::Type(t) => Some(t),
924            _ => None,
925        }
926    }
927
928    /// Converts the value to an error value.
929    pub fn into_error(self) -> Option<Error> {
930        match self {
931            Value::Error(e) => Some(e),
932            _ => None,
933        }
934    }
935
936    /// Converts the value to an opaque value.
937    pub fn into_opaque(self) -> Option<OpaqueValue> {
938        match self {
939            Value::Opaque(o) => Some(o),
940            _ => None,
941        }
942    }
943
944    /// Converts the value to an optional value.
945    pub fn into_optional(self) -> Option<OptionalValue> {
946        match self {
947            Value::Optional(o) => Some(o),
948            _ => None,
949        }
950    }
951
952    /// Converts the value to a null value and panics if the value is not a null value.
953    pub fn unwrap_null(self) {
954        match self {
955            Value::Null => (),
956            _ => panic!("called `Value::unwrap_null()` on a non-null value: {self:?}",),
957        }
958    }
959
960    /// Converts the value to a boolean value and panics if the value is not a boolean value.
961    pub fn unwrap_bool(self) -> bool {
962        match self {
963            Value::Bool(b) => b,
964            _ => panic!("called `Value::unwrap_bool()` on a non-bool value: {self:?}",),
965        }
966    }
967
968    /// Converts the value to a signed integer value and panics if the value is not a signed integer value.
969    pub fn unwrap_int(self) -> i64 {
970        match self {
971            Value::Int(i) => i,
972            _ => panic!("called `Value::unwrap_int()` on a non-int value: {self:?}",),
973        }
974    }
975
976    /// Converts the value to an unsigned integer value and panics if the value is not an unsigned integer value.
977    pub fn unwrap_uint(self) -> u64 {
978        match self {
979            Value::Uint(u) => u,
980            _ => panic!("called `Value::unwrap_uint()` on a non-uint value: {self:?}",),
981        }
982    }
983
984    /// Converts the value to a double value and panics if the value is not a double value.
985    pub fn unwrap_double(self) -> f64 {
986        match self {
987            Value::Double(d) => d,
988            _ => panic!("called `Value::unwrap_double()` on a non-double value: {self:?}",),
989        }
990    }
991
992    /// Converts the value to a string value and panics if the value is not a string value.
993    pub fn unwrap_string(self) -> StringValue {
994        match self {
995            Value::String(s) => s,
996            _ => panic!("called `Value::unwrap_string()` on a non-string value: {self:?}",),
997        }
998    }
999
1000    /// Converts the value to a byte array value and panics if the value is not a byte array value.
1001    pub fn unwrap_bytes(self) -> BytesValue {
1002        match self {
1003            Value::Bytes(b) => b,
1004            _ => panic!("called `Value::unwrap_bytes()` on a non-bytes value: {self:?}",),
1005        }
1006    }
1007
1008    /// Converts the value to a struct value and panics if the value is not a struct value.
1009    pub fn unwrap_struct(self) -> StructValue {
1010        match self {
1011            Value::Struct(s) => s,
1012            _ => panic!("called `Value::unwrap_struct()` on a non-struct value: {self:?}",),
1013        }
1014    }
1015
1016    /// Converts the value to a duration value and panics if the value is not a duration value.
1017    pub fn unwrap_duration(self) -> Duration {
1018        match self {
1019            Value::Duration(d) => d,
1020            _ => panic!("called `Value::unwrap_duration()` on a non-duration value: {self:?}",),
1021        }
1022    }
1023
1024    /// Converts the value to a timestamp value and panics if the value is not a timestamp value.
1025    pub fn unwrap_timestamp(self) -> Timestamp {
1026        match self {
1027            Value::Timestamp(t) => t,
1028            _ => panic!("called `Value::unwrap_timestamp()` on a non-timestamp value: {self:?}",),
1029        }
1030    }
1031
1032    /// Converts the value to a list value and panics if the value is not a list value.
1033    pub fn unwrap_list(self) -> ListValue {
1034        match self {
1035            Value::List(l) => l,
1036            _ => panic!("called `Value::unwrap_list()` on a non-list value: {self:?}",),
1037        }
1038    }
1039
1040    /// Converts the value to a map value and panics if the value is not a map value.
1041    pub fn unwrap_map(self) -> MapValue {
1042        match self {
1043            Value::Map(m) => m,
1044            _ => panic!("called `Value::unwrap_map()` on a non-map value: {self:?}",),
1045        }
1046    }
1047
1048    /// Converts the value to an unknown value and panics if the value is not an unknown value.
1049    pub fn unwrap_unknown(self) {
1050        match self {
1051            Value::Unknown(u) => u,
1052            _ => panic!("called `Value::unwrap_unknown()` on a non-unknown value: {self:?}",),
1053        }
1054    }
1055
1056    /// Converts the value to a type value and panics if the value is not a type value.
1057    pub fn unwrap_type(self) -> ValueType {
1058        match self {
1059            Value::Type(t) => t,
1060            _ => panic!("called `Value::unwrap_type()` on a non-type value: {self:?}",),
1061        }
1062    }
1063
1064    /// Converts the value to an error value and panics if the value is not an error value.
1065    pub fn unwrap_error(self) -> Error {
1066        match self {
1067            Value::Error(e) => e,
1068            _ => panic!("called `Value::unwrap_error()` on a non-error value: {self:?}",),
1069        }
1070    }
1071
1072    /// Converts the value to an opaque value and panics if the value is not an opaque value.
1073    pub fn unwrap_opaque(self) -> OpaqueValue {
1074        match self {
1075            Value::Opaque(o) => o,
1076            _ => panic!("called `Value::unwrap_opaque()` on a non-opaque value: {self:?}",),
1077        }
1078    }
1079
1080    /// Converts the value to an optional value and panics if the value is not an optional value.
1081    pub fn unwrap_optional(self) -> OptionalValue {
1082        match self {
1083            Value::Optional(o) => o,
1084            _ => panic!("called `Value::unwrap_optional()` on a non-optional value: {self:?}",),
1085        }
1086    }
1087
1088    /// Converts the value to a null value and panics if the value is not a null value.
1089    pub fn expect_null(self, msg: &str) {
1090        match self {
1091            Value::Null => (),
1092            _ => panic!("{msg}: {self:?}"),
1093        }
1094    }
1095
1096    /// Converts the value to a boolean value and panics if the value is not a boolean value.
1097    pub fn expect_bool(self, msg: &str) -> bool {
1098        match self {
1099            Value::Bool(b) => b,
1100            _ => panic!("{msg}: {self:?}"),
1101        }
1102    }
1103
1104    /// Converts the value to a signed integer value and panics if the value is not a signed integer value.
1105    pub fn expect_int(self, msg: &str) -> i64 {
1106        match self {
1107            Value::Int(i) => i,
1108            _ => panic!("{msg}: {self:?}"),
1109        }
1110    }
1111
1112    /// Converts the value to an unsigned integer value and panics if the value is not an unsigned integer value.
1113    pub fn expect_uint(self, msg: &str) -> u64 {
1114        match self {
1115            Value::Uint(u) => u,
1116            _ => panic!("{msg}: {self:?}"),
1117        }
1118    }
1119
1120    /// Converts the value to a double value and panics if the value is not a double value.
1121    pub fn expect_double(self, msg: &str) -> f64 {
1122        match self {
1123            Value::Double(d) => d,
1124            _ => panic!("{msg}: {self:?}"),
1125        }
1126    }
1127
1128    /// Converts the value to a string value and panics if the value is not a string value.
1129    pub fn expect_string(self, msg: &str) -> StringValue {
1130        match self {
1131            Value::String(s) => s,
1132            _ => panic!("{msg}: {self:?}"),
1133        }
1134    }
1135
1136    /// Converts the value to a byte array value and panics if the value is not a byte array value.
1137    pub fn expect_bytes(self, msg: &str) -> BytesValue {
1138        match self {
1139            Value::Bytes(b) => b,
1140            _ => panic!("{msg}: {self:?}"),
1141        }
1142    }
1143
1144    /// Converts the value to a struct value and panics if the value is not a struct value.
1145    pub fn expect_struct(self, msg: &str) -> StructValue {
1146        match self {
1147            Value::Struct(s) => s,
1148            _ => panic!("{msg}: {self:?}"),
1149        }
1150    }
1151
1152    /// Converts the value to a duration value and panics if the value is not a duration value.
1153    pub fn expect_duration(self, msg: &str) -> Duration {
1154        match self {
1155            Value::Duration(d) => d,
1156            _ => panic!("{msg}: {self:?}"),
1157        }
1158    }
1159
1160    /// Converts the value to a timestamp value and panics if the value is not a timestamp value.
1161    pub fn expect_timestamp(self, msg: &str) -> Timestamp {
1162        match self {
1163            Value::Timestamp(t) => t,
1164            _ => panic!("{msg}: {self:?}"),
1165        }
1166    }
1167
1168    /// Converts the value to a list value and panics if the value is not a list value.
1169    pub fn expect_list(self, msg: &str) -> ListValue {
1170        match self {
1171            Value::List(l) => l,
1172            _ => panic!("{msg}: {self:?}"),
1173        }
1174    }
1175
1176    /// Converts the value to a map value and panics if the value is not a map value.
1177    pub fn expect_map(self, msg: &str) -> MapValue {
1178        match self {
1179            Value::Map(m) => m,
1180            _ => panic!("{msg}: {self:?}"),
1181        }
1182    }
1183
1184    /// Converts the value to an unknown value and panics if the value is not an unknown value.
1185    pub fn expect_unknown(self, msg: &str) {
1186        match self {
1187            Value::Unknown(u) => u,
1188            _ => panic!("{msg}: {self:?}"),
1189        }
1190    }
1191
1192    /// Converts the value to a type value and panics if the value is not a type value.
1193    pub fn expect_type(self, msg: &str) -> ValueType {
1194        match self {
1195            Value::Type(t) => t,
1196            _ => panic!("{msg}: {self:?}"),
1197        }
1198    }
1199
1200    /// Converts the value to an error value and panics if the value is not an error value.
1201    pub fn expect_error(self, msg: &str) -> Error {
1202        match self {
1203            Value::Error(e) => e,
1204            _ => panic!("{msg}: {self:?}"),
1205        }
1206    }
1207
1208    /// Converts the value to an opaque value and panics if the value is not an opaque value.
1209    pub fn expect_opaque(self, msg: &str) -> OpaqueValue {
1210        match self {
1211            Value::Opaque(o) => o,
1212            _ => panic!("{msg}: {self:?}"),
1213        }
1214    }
1215
1216    /// Converts the value to an optional value and panics if the value is not an optional value.
1217    pub fn expect_optional(self, msg: &str) -> OptionalValue {
1218        match self {
1219            Value::Optional(o) => o,
1220            _ => panic!("{msg}: {self:?}"),
1221        }
1222    }
1223}
1224
1225impl From<MapKey> for Value {
1226    fn from(key: MapKey) -> Self {
1227        match key {
1228            MapKey::Bool(b) => Value::Bool(b),
1229            MapKey::Int(i) => Value::Int(i),
1230            MapKey::Uint(u) => Value::Uint(u),
1231            MapKey::String(s) => Value::String(s),
1232        }
1233    }
1234}
1235
1236impl TryFrom<Value> for MapKey {
1237    type Error = FromValueError;
1238
1239    fn try_from(value: Value) -> Result<Self, Self::Error> {
1240        match value {
1241            Value::Bool(b) => Ok(MapKey::Bool(b)),
1242            Value::Int(i) => Ok(MapKey::Int(i)),
1243            Value::Uint(u) => Ok(MapKey::Uint(u)),
1244            Value::String(s) => Ok(MapKey::String(s)),
1245            _ => Err(FromValueError::new(value, "MapKey")),
1246        }
1247    }
1248}
1249
1250/// CEL map key type.
1251///
1252/// `MapKey` represents value types that can be used as CEL map keys. According to the CEL
1253/// specification, only basic comparable types can be used as map keys.
1254///
1255/// # Supported Key Types
1256///
1257/// - `Bool`: Boolean keys
1258/// - `Int`: Signed integer keys
1259/// - `Uint`: Unsigned integer keys
1260/// - `String`: String keys
1261///
1262/// # Examples
1263///
1264/// ```rust,no_run
1265/// use cel_cxx::{MapKey, Value};
1266/// use std::collections::HashMap;
1267///
1268/// let mut map = HashMap::new();
1269///
1270/// // Different types of keys
1271/// map.insert(MapKey::String("name".to_string().into()), Value::String("Alice".to_string().into()));
1272/// map.insert(MapKey::Int(42), Value::String("answer".to_string().into()));
1273/// map.insert(MapKey::Bool(true), Value::String("yes".to_string().into()));
1274///
1275/// let map_value = Value::Map(map);
1276/// ```
1277#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1278pub enum MapKey {
1279    /// Boolean key
1280    Bool(bool),
1281    /// Signed integer key
1282    Int(i64),
1283    /// Unsigned integer key
1284    Uint(u64),
1285    /// String key
1286    String(StringValue),
1287}
1288
1289impl MapKey {
1290    /// Returns the kind of this map key.
1291    ///
1292    /// Returns the corresponding [`Kind`] enum.
1293    pub fn kind(&self) -> Kind {
1294        match self {
1295            MapKey::Bool(_) => Kind::Bool,
1296            MapKey::Int(_) => Kind::Int,
1297            MapKey::Uint(_) => Kind::Uint,
1298            MapKey::String(_) => Kind::String,
1299        }
1300    }
1301
1302    /// Returns the type of this map key.
1303    ///
1304    /// Returns the corresponding [`MapKeyType`] enum.
1305    pub fn mapkey_type(&self) -> MapKeyType {
1306        match self {
1307            MapKey::Bool(_) => MapKeyType::Bool,
1308            MapKey::Int(_) => MapKeyType::Int,
1309            MapKey::Uint(_) => MapKeyType::Uint,
1310            MapKey::String(_) => MapKeyType::String,
1311        }
1312    }
1313
1314    /// Creates a map key from a CEL value.
1315    ///
1316    /// Attempts to convert a [`Value`] to [`MapKey`]. Only supported basic types
1317    /// can be converted successfully.
1318    ///
1319    /// # Parameters
1320    ///
1321    /// - `value`: The CEL value to convert
1322    ///
1323    /// # Returns
1324    ///
1325    /// - `Ok(MapKey)`: Conversion successful
1326    /// - `Err(Value)`: Conversion failed, returns original value
1327    ///
1328    /// # Examples
1329    ///
1330    /// ```rust,no_run
1331    /// use cel_cxx::{Value, MapKey};
1332    ///
1333    /// // Successful conversion
1334    /// let key = MapKey::from_value(Value::String("key".to_string().into())).unwrap();
1335    /// assert_eq!(key, MapKey::String("key".to_string().into()));
1336    ///
1337    /// // Failed conversion
1338    /// let result = MapKey::from_value(Value::List(vec![]));
1339    /// assert!(result.is_err());
1340    /// ```
1341    pub fn from_value(value: Value) -> Result<Self, Value> {
1342        match value {
1343            Value::Bool(b) => Ok(MapKey::Bool(b)),
1344            Value::Int(i) => Ok(MapKey::Int(i)),
1345            Value::Uint(u) => Ok(MapKey::Uint(u)),
1346            Value::String(s) => Ok(MapKey::String(s)),
1347            _ => Err(value),
1348        }
1349    }
1350
1351    /// Converts this map key to a CEL value.
1352    ///
1353    /// Converts [`MapKey`] to the corresponding [`Value`].
1354    ///
1355    /// # Examples
1356    ///
1357    /// ```rust,no_run
1358    /// use cel_cxx::{MapKey, Value};
1359    ///
1360    /// let key = MapKey::String("hello".to_string().into());
1361    /// let value = key.into_value();
1362    /// assert_eq!(value, Value::String("hello".to_string().into()));
1363    /// ```
1364    pub fn into_value(self) -> Value {
1365        match self {
1366            MapKey::Bool(b) => Value::Bool(b),
1367            MapKey::Int(i) => Value::Int(i),
1368            MapKey::Uint(u) => Value::Uint(u),
1369            MapKey::String(s) => Value::String(s),
1370        }
1371    }
1372}
1373
1374/// CEL constant value.
1375///
1376/// `Constant` represents constant values known at compile time, supporting CEL's basic data types.
1377/// Constants can be used for compile-time optimization and type inference.
1378///
1379/// # Supported Types
1380///
1381/// - `Null`: Null value
1382/// - `Bool`: Boolean value
1383/// - `Int`: 64-bit signed integer
1384/// - `Uint`: 64-bit unsigned integer
1385/// - `Double`: 64-bit floating point number
1386/// - `String`: UTF-8 string
1387/// - `Bytes`: Byte array
1388/// - `Duration`: Time duration
1389/// - `Timestamp`: Timestamp
1390///
1391/// # Examples
1392///
1393/// ```rust,no_run
1394/// use cel_cxx::Constant;
1395///
1396/// let null_const = Constant::Null;
1397/// let bool_const = Constant::Bool(true);
1398/// let int_const = Constant::Int(42);
1399/// let string_const = Constant::String("hello".to_string().into());
1400/// ```
1401#[derive(Debug, Clone, Default, PartialEq)]
1402pub enum Constant {
1403    /// Null constant
1404    #[default]
1405    Null,
1406    /// Boolean constant
1407    Bool(bool),
1408    /// Signed integer constant
1409    Int(i64),
1410    /// Unsigned integer constant
1411    Uint(u64),
1412    /// Floating point constant
1413    Double(f64),
1414    /// Byte array constant
1415    Bytes(BytesValue),
1416    /// String constant
1417    String(StringValue),
1418    /// Duration constant
1419    Duration(chrono::Duration),
1420    /// Timestamp constant
1421    Timestamp(chrono::DateTime<chrono::Utc>),
1422}
1423
1424impl Constant {
1425    /// Returns the type of the constant.
1426    ///
1427    /// Returns the CEL type corresponding to the constant value.
1428    pub fn value_type(&self) -> ValueType {
1429        match self {
1430            Self::Null => ValueType::Null,
1431            Self::Bool(_) => ValueType::Bool,
1432            Self::Int(_) => ValueType::Int,
1433            Self::Uint(_) => ValueType::Uint,
1434            Self::Double(_) => ValueType::Double,
1435            Self::Bytes(_) => ValueType::Bytes,
1436            Self::String(_) => ValueType::String,
1437            Self::Duration(_) => ValueType::Duration,
1438            Self::Timestamp(_) => ValueType::Timestamp,
1439        }
1440    }
1441
1442    /// Converts the constant to a CEL value.
1443    ///
1444    /// Converts the constant to the corresponding [`Value`] type.
1445    ///
1446    /// [`Value`]: crate::Value
1447    pub fn value(&self) -> Value {
1448        match self {
1449            Self::Null => Value::Null,
1450            Self::Bool(value) => Value::Bool(*value),
1451            Self::Int(value) => Value::Int(*value),
1452            Self::Uint(value) => Value::Uint(*value),
1453            Self::Double(value) => Value::Double(*value),
1454            Self::Bytes(value) => Value::Bytes(value.clone()),
1455            Self::String(value) => Value::String(value.clone()),
1456            Self::Duration(value) => Value::Duration(*value),
1457            Self::Timestamp(value) => Value::Timestamp(*value),
1458        }
1459    }
1460}
1461
1462impl TryFrom<Value> for Constant {
1463    type Error = FromValueError;
1464
1465    fn try_from(value: Value) -> Result<Self, Self::Error> {
1466        match value {
1467            Value::Null => Ok(Constant::Null),
1468            Value::Bool(b) => Ok(Constant::Bool(b)),
1469            Value::Int(i) => Ok(Constant::Int(i)),
1470            Value::Uint(u) => Ok(Constant::Uint(u)),
1471            Value::Double(d) => Ok(Constant::Double(d)),
1472            Value::Bytes(b) => Ok(Constant::Bytes(b)),
1473            Value::String(s) => Ok(Constant::String(s)),
1474            Value::Duration(d) => Ok(Constant::Duration(d)),
1475            Value::Timestamp(t) => Ok(Constant::Timestamp(t)),
1476            _ => Err(FromValueError::new(value, "Constant")),
1477        }
1478    }
1479}
1480
1481impl From<&Constant> for cxx::UniquePtr<crate::ffi::Constant> {
1482    fn from(constant: &Constant) -> Self {
1483        use crate::ffi::Constant as FfiConstant;
1484        match constant {
1485            Constant::Null => FfiConstant::new_null(),
1486            Constant::Bool(value) => FfiConstant::new_bool(*value),
1487            Constant::Int(value) => FfiConstant::new_int(*value),
1488            Constant::Uint(value) => FfiConstant::new_uint(*value),
1489            Constant::Double(value) => FfiConstant::new_double(*value),
1490            Constant::Bytes(value) => FfiConstant::new_bytes(&value.as_ref()),
1491            Constant::String(value) => FfiConstant::new_string(&value.as_ref()),
1492            Constant::Duration(value) => FfiConstant::new_duration((*value).into()),
1493            Constant::Timestamp(value) => FfiConstant::new_timestamp((*value).into()),
1494        }
1495    }
1496}
1497
1498impl From<Constant> for cxx::UniquePtr<crate::ffi::Constant> {
1499    fn from(constant: Constant) -> Self {
1500        Self::from(&constant)
1501    }
1502}
1503
1504impl From<&crate::ffi::Constant> for Constant {
1505    fn from(constant: &crate::ffi::Constant) -> Self {
1506        use crate::ffi::ConstantKindCase;
1507        match constant.kind_case() {
1508            ConstantKindCase::Unspecified => Constant::Null,
1509            ConstantKindCase::Null => Constant::Null,
1510            ConstantKindCase::Bool => Constant::Bool(constant.bool_value()),
1511            ConstantKindCase::Int => Constant::Int(constant.int_value()),
1512            ConstantKindCase::Uint => Constant::Uint(constant.uint_value()),
1513            ConstantKindCase::Double => Constant::Double(constant.double_value()),
1514            ConstantKindCase::Bytes => Constant::Bytes(BytesValue::from(constant.bytes_value().as_bytes())),
1515            ConstantKindCase::String => Constant::String(StringValue::from(constant.string_value().to_string())),
1516            ConstantKindCase::Duration => Constant::Duration(constant.duration_value().into()),
1517            ConstantKindCase::Timestamp => Constant::Timestamp(constant.timestamp_value().into()),
1518        }
1519    }
1520}
1521
1522impl From<crate::ffi::Constant> for Constant {
1523    fn from(constant: crate::ffi::Constant) -> Self {
1524        Self::from(&constant)
1525    }
1526}
1527
1528#[cfg(test)]
1529mod test {
1530    use super::*;
1531
1532    #[test]
1533    fn test_value_kind() {
1534        let cases = vec![
1535            (Value::Null, Kind::Null),
1536            (Value::Bool(true), Kind::Bool),
1537            (Value::Int(1), Kind::Int),
1538            (Value::Uint(1), Kind::Uint),
1539            (Value::Double(1.0), Kind::Double),
1540            (Value::String("test".into()), Kind::String),
1541            (Value::Bytes(b"abc".into()), Kind::Bytes),
1542            (
1543                Value::Duration(chrono::Duration::seconds(1)),
1544                Kind::Duration,
1545            ),
1546            (Value::Timestamp(chrono::Utc::now()), Kind::Timestamp),
1547            (Value::List(vec![]), Kind::List),
1548            (Value::Map(HashMap::new()), Kind::Map),
1549            (Value::Type(ValueType::Null), Kind::Type),
1550            (
1551                Value::Error(Error::invalid_argument("invalid")),
1552                Kind::Error,
1553            ),
1554            (Value::Optional(Optional::none()), Kind::Opaque),
1555        ];
1556
1557        for (value, expected_kind) in cases {
1558            assert_eq!(value.kind(), expected_kind);
1559        }
1560    }
1561
1562    #[test]
1563    fn test_key_kind() {
1564        let cases = vec![
1565            (MapKey::Bool(true), Kind::Bool),
1566            (MapKey::Int(1), Kind::Int),
1567            (MapKey::Uint(1), Kind::Uint),
1568            (MapKey::String("test".into()), Kind::String),
1569        ];
1570
1571        for (key, expected_kind) in cases {
1572            assert_eq!(key.kind(), expected_kind);
1573        }
1574    }
1575
1576    #[test]
1577    fn test_value_type() {
1578        let cases = vec![
1579            (Value::Null, ValueType::Null),
1580            (Value::Bool(true), ValueType::Bool),
1581            (Value::Int(1), ValueType::Int),
1582            (Value::Uint(1), ValueType::Uint),
1583            (Value::Double(1.0), ValueType::Double),
1584            (Value::String("test".into()), ValueType::String),
1585            (Value::Bytes(b"abc".into()), ValueType::Bytes),
1586            (
1587                Value::Duration(chrono::Duration::seconds(1)),
1588                ValueType::Duration,
1589            ),
1590            (Value::Timestamp(chrono::Utc::now()), ValueType::Timestamp),
1591            (
1592                Value::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
1593                ValueType::List(ListType::new(ValueType::Int)),
1594            ),
1595            (
1596                Value::Map(HashMap::from([(
1597                    MapKey::String("test".into()),
1598                    Value::Int(1),
1599                )])),
1600                ValueType::Map(MapType::new(MapKeyType::String, ValueType::Int)),
1601            ),
1602            (
1603                Value::Type(ValueType::Double),
1604                ValueType::Type(TypeType::new(None)),
1605            ),
1606            (
1607                Value::Error(Error::invalid_argument("invalid")),
1608                ValueType::Error,
1609            ),
1610            (
1611                Value::Optional(Optional::new(Value::Int(5))),
1612                ValueType::Optional(OptionalType::new(ValueType::Int)),
1613            ),
1614        ];
1615
1616        for (i, (value, expected_type)) in cases.into_iter().enumerate() {
1617            assert_eq!(value.value_type(), expected_type, "case {i} failed");
1618        }
1619    }
1620}