Skip to main content

tonneau_cel/
lib.rs

1//! Currently this is a fully private api used by `tonneau` and `tonneau-build` to
2//! compile and execute [CEL](https://cel.dev/) expressions.
3#![cfg_attr(feature = "docs", doc = "## Feature flags")]
4#![cfg_attr(feature = "docs", doc = document_features::document_features!())]
5//! ## License
6//!
7//! This project is licensed under the MIT or Apache-2.0 license.
8//! You can choose between one of them if you use this work.
9//!
10//! `SPDX-License-Identifier: MIT OR Apache-2.0`
11#![cfg_attr(all(test, coverage_nightly), feature(coverage_attribute))]
12#![deny(missing_docs)]
13#![deny(unsafe_code)]
14#![deny(unreachable_pub)]
15#![deny(clippy::mod_module_files)]
16#![doc(hidden)]
17
18use std::borrow::Cow;
19use std::collections::{BTreeMap, HashMap};
20use std::hash::Hash;
21use std::sync::Arc;
22
23use bytes::Bytes;
24use float_cmp::ApproxEq;
25use num_traits::ToPrimitive;
26
27#[derive(Debug, thiserror::Error, PartialEq)]
28pub enum CelError<'a> {
29    #[error("index out of bounds: {0} is out of range for a list of length {1}")]
30    IndexOutOfBounds(usize, usize),
31    #[error("invalid type for indexing: {0}")]
32    IndexWithBadIndex(CelValue<'a>),
33    #[error("map key not found: {0:?}")]
34    MapKeyNotFound(CelValue<'a>),
35    #[error("bad operation: {left} {op} {right}")]
36    BadOperation {
37        left: CelValue<'a>,
38        right: CelValue<'a>,
39        op: &'static str,
40    },
41    #[error("bad unary operation: {op}{value}")]
42    BadUnaryOperation {
43        op: &'static str,
44        value: CelValue<'a>,
45    },
46    #[error("number out of range when performing {op}")]
47    NumberOutOfRange { op: &'static str },
48    #[error("bad access when trying to member {member} on {container}")]
49    BadAccess {
50        member: CelValue<'a>,
51        container: CelValue<'a>,
52    },
53}
54
55#[derive(Clone, Debug)]
56pub enum CelString<'a> {
57    Owned(Arc<str>),
58    Borrowed(&'a str),
59}
60
61impl PartialEq for CelString<'_> {
62    fn eq(&self, other: &Self) -> bool {
63        self.as_ref() == other.as_ref()
64    }
65}
66
67impl Eq for CelString<'_> {}
68
69impl<'a> From<&'a str> for CelString<'a> {
70    fn from(value: &'a str) -> Self {
71        CelString::Borrowed(value)
72    }
73}
74
75impl From<String> for CelString<'_> {
76    fn from(value: String) -> Self {
77        CelString::Owned(value.into())
78    }
79}
80
81impl<'a> From<&'a String> for CelString<'a> {
82    fn from(value: &'a String) -> Self {
83        CelString::Borrowed(value.as_str())
84    }
85}
86
87impl From<&Arc<str>> for CelString<'static> {
88    fn from(value: &Arc<str>) -> Self {
89        CelString::Owned(value.clone())
90    }
91}
92
93impl From<Arc<str>> for CelString<'static> {
94    fn from(value: Arc<str>) -> Self {
95        CelString::Owned(value)
96    }
97}
98
99impl AsRef<str> for CelString<'_> {
100    fn as_ref(&self) -> &str {
101        match self {
102            Self::Borrowed(s) => s,
103            Self::Owned(s) => s,
104        }
105    }
106}
107
108impl std::ops::Deref for CelString<'_> {
109    type Target = str;
110
111    fn deref(&self) -> &Self::Target {
112        self.as_ref()
113    }
114}
115
116#[derive(Clone, Debug)]
117pub enum CelBytes<'a> {
118    Owned(Bytes),
119    Borrowed(&'a [u8]),
120}
121
122impl PartialEq for CelBytes<'_> {
123    fn eq(&self, other: &Self) -> bool {
124        self.as_ref() == other.as_ref()
125    }
126}
127
128impl Eq for CelBytes<'_> {}
129
130impl<'a> From<&'a [u8]> for CelBytes<'a> {
131    fn from(value: &'a [u8]) -> Self {
132        CelBytes::Borrowed(value)
133    }
134}
135
136impl From<Bytes> for CelBytes<'_> {
137    fn from(value: Bytes) -> Self {
138        CelBytes::Owned(value)
139    }
140}
141
142impl From<&Bytes> for CelBytes<'_> {
143    fn from(value: &Bytes) -> Self {
144        CelBytes::Owned(value.clone())
145    }
146}
147
148impl From<Vec<u8>> for CelBytes<'static> {
149    fn from(value: Vec<u8>) -> Self {
150        CelBytes::Owned(value.into())
151    }
152}
153
154impl<'a> From<&'a Vec<u8>> for CelBytes<'a> {
155    fn from(value: &'a Vec<u8>) -> Self {
156        CelBytes::Borrowed(value.as_slice())
157    }
158}
159
160impl AsRef<[u8]> for CelBytes<'_> {
161    fn as_ref(&self) -> &[u8] {
162        match self {
163            Self::Borrowed(s) => s,
164            Self::Owned(s) => s,
165        }
166    }
167}
168
169#[derive(Clone, Debug)]
170pub enum CelValue<'a> {
171    Bool(bool),
172    Number(NumberTy),
173    String(CelString<'a>),
174    Bytes(CelBytes<'a>),
175    List(Arc<[CelValue<'a>]>),
176    Map(Arc<[(CelValue<'a>, CelValue<'a>)]>),
177    Duration(chrono::Duration),
178    Timestamp(chrono::DateTime<chrono::FixedOffset>),
179    Enum(CelEnum<'a>),
180    Null,
181}
182
183impl PartialOrd for CelValue<'_> {
184    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
185        match (self, other) {
186            (CelValue::Number(l), CelValue::Number(r)) => l.partial_cmp(r),
187            (
188                CelValue::String(_) | CelValue::Bytes(_),
189                CelValue::String(_) | CelValue::Bytes(_),
190            ) => {
191                let l = match self {
192                    CelValue::String(s) => s.as_ref().as_bytes(),
193                    CelValue::Bytes(b) => b.as_ref(),
194                    _ => unreachable!(),
195                };
196
197                let r = match other {
198                    CelValue::String(s) => s.as_ref().as_bytes(),
199                    CelValue::Bytes(b) => b.as_ref(),
200                    _ => unreachable!(),
201                };
202
203                Some(l.cmp(r))
204            }
205            _ => None,
206        }
207    }
208}
209
210impl<'a> CelValue<'a> {
211    pub fn cel_access<'b>(
212        container: impl CelValueConv<'a>,
213        key: impl CelValueConv<'b>,
214    ) -> Result<CelValue<'a>, CelError<'b>>
215    where
216        'a: 'b,
217    {
218        let key = key.conv();
219        match container.conv() {
220            CelValue::Map(map) => map
221                .iter()
222                .find(|(k, _)| k == &key)
223                .map(|(_, v)| v.clone())
224                .ok_or(CelError::MapKeyNotFound(key)),
225            CelValue::List(list) => {
226                if let Some(idx) = key.as_number().and_then(|n| n.to_usize()) {
227                    list.get(idx)
228                        .cloned()
229                        .ok_or(CelError::IndexOutOfBounds(idx, list.len()))
230                } else {
231                    Err(CelError::IndexWithBadIndex(key))
232                }
233            }
234            v => Err(CelError::BadAccess {
235                member: key,
236                container: v,
237            }),
238        }
239    }
240
241    pub fn cel_add(
242        left: impl CelValueConv<'a>,
243        right: impl CelValueConv<'a>,
244    ) -> Result<CelValue<'a>, CelError<'a>> {
245        match (left.conv(), right.conv()) {
246            (CelValue::Number(l), CelValue::Number(r)) => Ok(CelValue::Number(l.cel_add(r)?)),
247            (CelValue::String(l), CelValue::String(r)) => Ok(CelValue::String(CelString::Owned(
248                Arc::from(format!("{}{}", l.as_ref(), r.as_ref())),
249            ))),
250            (CelValue::Bytes(l), CelValue::Bytes(r)) => Ok(CelValue::Bytes(CelBytes::Owned({
251                let mut l = l.as_ref().to_vec();
252                l.extend_from_slice(r.as_ref());
253                Bytes::from(l)
254            }))),
255            (CelValue::List(l), CelValue::List(r)) => {
256                Ok(CelValue::List(l.iter().chain(r.iter()).cloned().collect()))
257            }
258            (CelValue::Map(l), CelValue::Map(r)) => {
259                Ok(CelValue::Map(l.iter().chain(r.iter()).cloned().collect()))
260            }
261            (left, right) => Err(CelError::BadOperation {
262                left,
263                right,
264                op: "+",
265            }),
266        }
267    }
268
269    pub fn cel_sub(
270        left: impl CelValueConv<'a>,
271        right: impl CelValueConv<'a>,
272    ) -> Result<CelValue<'static>, CelError<'a>> {
273        match (left.conv(), right.conv()) {
274            (CelValue::Number(l), CelValue::Number(r)) => Ok(CelValue::Number(l.cel_sub(r)?)),
275            (left, right) => Err(CelError::BadOperation {
276                left,
277                right,
278                op: "-",
279            }),
280        }
281    }
282
283    pub fn cel_mul(
284        left: impl CelValueConv<'a>,
285        right: impl CelValueConv<'a>,
286    ) -> Result<CelValue<'static>, CelError<'a>> {
287        match (left.conv(), right.conv()) {
288            (CelValue::Number(l), CelValue::Number(r)) => Ok(CelValue::Number(l.cel_mul(r)?)),
289            (left, right) => Err(CelError::BadOperation {
290                left,
291                right,
292                op: "*",
293            }),
294        }
295    }
296
297    pub fn cel_div(
298        left: impl CelValueConv<'a>,
299        right: impl CelValueConv<'a>,
300    ) -> Result<CelValue<'static>, CelError<'a>> {
301        match (left.conv(), right.conv()) {
302            (CelValue::Number(l), CelValue::Number(r)) => Ok(CelValue::Number(l.cel_div(r)?)),
303            (left, right) => Err(CelError::BadOperation {
304                left,
305                right,
306                op: "/",
307            }),
308        }
309    }
310
311    pub fn cel_rem(
312        left: impl CelValueConv<'a>,
313        right: impl CelValueConv<'a>,
314    ) -> Result<CelValue<'static>, CelError<'a>> {
315        match (left.conv(), right.conv()) {
316            (CelValue::Number(l), CelValue::Number(r)) => Ok(CelValue::Number(l.cel_rem(r)?)),
317            (left, right) => Err(CelError::BadOperation {
318                left,
319                right,
320                op: "%",
321            }),
322        }
323    }
324
325    fn as_number(&self) -> Option<NumberTy> {
326        match self {
327            CelValue::Number(n) => Some(*n),
328            _ => None,
329        }
330    }
331
332    // !self
333    pub fn cel_neg(input: impl CelValueConv<'a>) -> Result<CelValue<'static>, CelError<'a>> {
334        match input.conv() {
335            CelValue::Number(n) => Ok(CelValue::Number(n.cel_neg()?)),
336            value => Err(CelError::BadUnaryOperation { value, op: "-" }),
337        }
338    }
339
340    // left < right
341    pub fn cel_lt(
342        left: impl CelValueConv<'a>,
343        right: impl CelValueConv<'a>,
344    ) -> Result<bool, CelError<'a>> {
345        let left = left.conv();
346        let right = right.conv();
347        left.partial_cmp(&right)
348            .ok_or(CelError::BadOperation {
349                left,
350                right,
351                op: "<",
352            })
353            .map(|o| matches!(o, std::cmp::Ordering::Less))
354    }
355
356    // left <= right
357    pub fn cel_lte(
358        left: impl CelValueConv<'a>,
359        right: impl CelValueConv<'a>,
360    ) -> Result<bool, CelError<'a>> {
361        let left = left.conv();
362        let right = right.conv();
363        left.partial_cmp(&right)
364            .ok_or(CelError::BadOperation {
365                left,
366                right,
367                op: "<=",
368            })
369            .map(|o| matches!(o, std::cmp::Ordering::Less | std::cmp::Ordering::Equal))
370    }
371
372    // left > right
373    pub fn cel_gt(
374        left: impl CelValueConv<'a>,
375        right: impl CelValueConv<'a>,
376    ) -> Result<bool, CelError<'a>> {
377        let left = left.conv();
378        let right = right.conv();
379        left.partial_cmp(&right)
380            .ok_or(CelError::BadOperation {
381                left,
382                right,
383                op: ">",
384            })
385            .map(|o| matches!(o, std::cmp::Ordering::Greater))
386    }
387
388    // left >= right
389    pub fn cel_gte(
390        left: impl CelValueConv<'a>,
391        right: impl CelValueConv<'a>,
392    ) -> Result<bool, CelError<'a>> {
393        let left = left.conv();
394        let right = right.conv();
395        left.partial_cmp(&right)
396            .ok_or(CelError::BadOperation {
397                left,
398                right,
399                op: ">=",
400            })
401            .map(|o| matches!(o, std::cmp::Ordering::Greater | std::cmp::Ordering::Equal))
402    }
403
404    // left == right
405    pub fn cel_eq(
406        left: impl CelValueConv<'a>,
407        right: impl CelValueConv<'a>,
408    ) -> Result<bool, CelError<'a>> {
409        let left = left.conv();
410        let right = right.conv();
411        Ok(left == right)
412    }
413
414    // left != right
415    pub fn cel_neq(
416        left: impl CelValueConv<'a>,
417        right: impl CelValueConv<'a>,
418    ) -> Result<bool, CelError<'a>> {
419        let left = left.conv();
420        let right = right.conv();
421        Ok(left != right)
422    }
423
424    // left.contains(right)
425    pub fn cel_contains(
426        left: impl CelValueConv<'a>,
427        right: impl CelValueConv<'a>,
428    ) -> Result<bool, CelError<'a>> {
429        Self::cel_in(right, left).map_err(|err| match err {
430            CelError::BadOperation {
431                left,
432                right,
433                op: "in",
434            } => CelError::BadOperation {
435                left: right,
436                right: left,
437                op: "contains",
438            },
439            // I think this is unreachable
440            err => err,
441        })
442    }
443
444    // left in right
445    pub fn cel_in(
446        left: impl CelValueConv<'a>,
447        right: impl CelValueConv<'a>,
448    ) -> Result<bool, CelError<'a>> {
449        match (left.conv(), right.conv()) {
450            (left, CelValue::List(r)) => Ok(r.contains(&left)),
451            (left, CelValue::Map(r)) => Ok(r.iter().any(|(k, _)| k == &left)),
452            (
453                left @ (CelValue::Bytes(_) | CelValue::String(_)),
454                right @ (CelValue::Bytes(_) | CelValue::String(_)),
455            ) => {
456                let r = match &right {
457                    CelValue::Bytes(b) => b.as_ref(),
458                    CelValue::String(s) => s.as_ref().as_bytes(),
459                    _ => unreachable!(),
460                };
461
462                let l = match &left {
463                    CelValue::Bytes(b) => b.as_ref(),
464                    CelValue::String(s) => s.as_ref().as_bytes(),
465                    _ => unreachable!(),
466                };
467
468                Ok(r.windows(l.len()).any(|w| w == l))
469            }
470            (left, right) => Err(CelError::BadOperation {
471                left,
472                right,
473                op: "in",
474            }),
475        }
476    }
477
478    pub fn cel_starts_with(
479        left: impl CelValueConv<'a>,
480        right: impl CelValueConv<'a>,
481    ) -> Result<bool, CelError<'a>> {
482        match (left.conv(), right.conv()) {
483            (
484                left @ (CelValue::Bytes(_) | CelValue::String(_)),
485                right @ (CelValue::Bytes(_) | CelValue::String(_)),
486            ) => {
487                let r = match &right {
488                    CelValue::Bytes(b) => b.as_ref(),
489                    CelValue::String(s) => s.as_ref().as_bytes(),
490                    _ => unreachable!(),
491                };
492
493                let l = match &left {
494                    CelValue::Bytes(b) => b.as_ref(),
495                    CelValue::String(s) => s.as_ref().as_bytes(),
496                    _ => unreachable!(),
497                };
498
499                Ok(l.starts_with(r))
500            }
501            (left, right) => Err(CelError::BadOperation {
502                left,
503                right,
504                op: "startsWith",
505            }),
506        }
507    }
508
509    pub fn cel_ends_with(
510        left: impl CelValueConv<'a>,
511        right: impl CelValueConv<'a>,
512    ) -> Result<bool, CelError<'a>> {
513        match (left.conv(), right.conv()) {
514            (
515                left @ (CelValue::Bytes(_) | CelValue::String(_)),
516                right @ (CelValue::Bytes(_) | CelValue::String(_)),
517            ) => {
518                let r = match &right {
519                    CelValue::Bytes(b) => b.as_ref(),
520                    CelValue::String(s) => s.as_ref().as_bytes(),
521                    _ => unreachable!(),
522                };
523
524                let l = match &left {
525                    CelValue::Bytes(b) => b.as_ref(),
526                    CelValue::String(s) => s.as_ref().as_bytes(),
527                    _ => unreachable!(),
528                };
529
530                Ok(l.ends_with(r))
531            }
532            (left, right) => Err(CelError::BadOperation {
533                left,
534                right,
535                op: "startsWith",
536            }),
537        }
538    }
539
540    pub fn cel_matches(
541        value: impl CelValueConv<'a>,
542        regex: &regex::Regex,
543    ) -> Result<bool, CelError<'a>> {
544        match value.conv() {
545            value @ (CelValue::Bytes(_) | CelValue::String(_)) => {
546                let maybe_str = match &value {
547                    CelValue::Bytes(b) => std::str::from_utf8(b.as_ref()),
548                    CelValue::String(s) => Ok(s.as_ref()),
549                    _ => unreachable!(),
550                };
551
552                let Ok(input) = maybe_str else {
553                    return Ok(false);
554                };
555
556                Ok(regex.is_match(input))
557            }
558            value => Err(CelError::BadUnaryOperation {
559                op: "matches",
560                value,
561            }),
562        }
563    }
564
565    pub fn cel_is_ipv4(value: impl CelValueConv<'a>) -> Result<bool, CelError<'a>> {
566        match value.conv() {
567            CelValue::String(s) => Ok(s.parse::<std::net::Ipv4Addr>().is_ok()),
568            CelValue::Bytes(b) => {
569                if b.as_ref().len() == 4 {
570                    Ok(true)
571                } else if let Ok(s) = std::str::from_utf8(b.as_ref()) {
572                    Ok(s.parse::<std::net::Ipv4Addr>().is_ok())
573                } else {
574                    Ok(false)
575                }
576            }
577            value => Err(CelError::BadUnaryOperation {
578                op: "isIpv4",
579                value,
580            }),
581        }
582    }
583
584    pub fn cel_is_ipv6(value: impl CelValueConv<'a>) -> Result<bool, CelError<'a>> {
585        match value.conv() {
586            CelValue::String(s) => Ok(s.parse::<std::net::Ipv6Addr>().is_ok()),
587            CelValue::Bytes(b) => {
588                if b.as_ref().len() == 16 {
589                    Ok(true)
590                } else if let Ok(s) = std::str::from_utf8(b.as_ref()) {
591                    Ok(s.parse::<std::net::Ipv6Addr>().is_ok())
592                } else {
593                    Ok(false)
594                }
595            }
596            value => Err(CelError::BadUnaryOperation {
597                op: "isIpv6",
598                value,
599            }),
600        }
601    }
602
603    pub fn cel_is_uuid(value: impl CelValueConv<'a>) -> Result<bool, CelError<'a>> {
604        match value.conv() {
605            CelValue::String(s) => Ok(s.parse::<uuid::Uuid>().is_ok()),
606            CelValue::Bytes(b) => {
607                if b.as_ref().len() == 16 {
608                    Ok(true)
609                } else if let Ok(s) = std::str::from_utf8(b.as_ref()) {
610                    Ok(s.parse::<uuid::Uuid>().is_ok())
611                } else {
612                    Ok(false)
613                }
614            }
615            value => Err(CelError::BadUnaryOperation {
616                op: "isUuid",
617                value,
618            }),
619        }
620    }
621
622    pub fn cel_is_ulid(value: impl CelValueConv<'a>) -> Result<bool, CelError<'a>> {
623        match value.conv() {
624            CelValue::String(s) => Ok(s.parse::<ulid::Ulid>().is_ok()),
625            CelValue::Bytes(b) => {
626                if b.as_ref().len() == 16 {
627                    Ok(true)
628                } else if let Ok(s) = std::str::from_utf8(b.as_ref()) {
629                    Ok(s.parse::<ulid::Ulid>().is_ok())
630                } else {
631                    Ok(false)
632                }
633            }
634            value => Err(CelError::BadUnaryOperation {
635                op: "isUlid",
636                value,
637            }),
638        }
639    }
640
641    pub fn cel_is_hostname(value: impl CelValueConv<'a>) -> Result<bool, CelError<'a>> {
642        match value.conv() {
643            CelValue::String(s) => Ok(matches!(url::Host::parse(&s), Ok(url::Host::Domain(_)))),
644            CelValue::Bytes(b) => {
645                if let Ok(s) = std::str::from_utf8(b.as_ref()) {
646                    Ok(matches!(url::Host::parse(s), Ok(url::Host::Domain(_))))
647                } else {
648                    Ok(false)
649                }
650            }
651            value => Err(CelError::BadUnaryOperation {
652                op: "isHostname",
653                value,
654            }),
655        }
656    }
657
658    pub fn cel_is_uri(value: impl CelValueConv<'a>) -> Result<bool, CelError<'a>> {
659        match value.conv() {
660            CelValue::String(s) => Ok(url::Url::parse(&s).is_ok()),
661            CelValue::Bytes(b) => {
662                if let Ok(s) = std::str::from_utf8(b.as_ref()) {
663                    Ok(url::Url::parse(s).is_ok())
664                } else {
665                    Ok(false)
666                }
667            }
668            value => Err(CelError::BadUnaryOperation { op: "isUri", value }),
669        }
670    }
671
672    pub fn cel_is_email(value: impl CelValueConv<'a>) -> Result<bool, CelError<'a>> {
673        match value.conv() {
674            CelValue::String(s) => Ok(email_address::EmailAddress::is_valid(&s)),
675            CelValue::Bytes(b) => {
676                if let Ok(s) = std::str::from_utf8(b.as_ref()) {
677                    Ok(email_address::EmailAddress::is_valid(s))
678                } else {
679                    Ok(false)
680                }
681            }
682            value => Err(CelError::BadUnaryOperation {
683                op: "isEmail",
684                value,
685            }),
686        }
687    }
688
689    pub fn cel_is_nan(value: impl CelValueConv<'a>) -> Result<bool, CelError<'a>> {
690        match value.conv() {
691            CelValue::Number(n) => match n {
692                NumberTy::I64(_) => Ok(false),
693                NumberTy::U64(_) => Ok(false),
694                NumberTy::F64(f) => Ok(f.is_nan()),
695            },
696            value => Err(CelError::BadUnaryOperation { op: "isNaN", value }),
697        }
698    }
699
700    pub fn cel_is_inf(value: impl CelValueConv<'a>) -> Result<bool, CelError<'a>> {
701        match value.conv() {
702            CelValue::Number(n) => match n {
703                NumberTy::I64(_) => Ok(false),
704                NumberTy::U64(_) => Ok(false),
705                NumberTy::F64(f) => Ok(f.is_infinite()),
706            },
707            value => Err(CelError::BadUnaryOperation { op: "isInf", value }),
708        }
709    }
710
711    pub fn cel_size(item: impl CelValueConv<'a>) -> Result<u64, CelError<'a>> {
712        match item.conv() {
713            Self::Bytes(b) => Ok(b.as_ref().len() as u64),
714            Self::String(s) => Ok(s.as_ref().len() as u64),
715            Self::List(l) => Ok(l.len() as u64),
716            Self::Map(m) => Ok(m.len() as u64),
717            item => Err(CelError::BadUnaryOperation {
718                op: "size",
719                value: item,
720            }),
721        }
722    }
723
724    pub fn cel_map(
725        item: impl CelValueConv<'a>,
726        map_fn: impl Fn(CelValue<'a>) -> Result<CelValue<'a>, CelError<'a>>,
727    ) -> Result<CelValue<'a>, CelError<'a>> {
728        match item.conv() {
729            CelValue::List(items) => Ok(CelValue::List(
730                items
731                    .iter()
732                    .cloned()
733                    .map(map_fn)
734                    .collect::<Result<_, _>>()?,
735            )),
736            CelValue::Map(map) => Ok(CelValue::List(
737                map.iter()
738                    .map(|(key, _)| key)
739                    .cloned()
740                    .map(map_fn)
741                    .collect::<Result<_, _>>()?,
742            )),
743            value => Err(CelError::BadUnaryOperation { op: "map", value }),
744        }
745    }
746
747    pub fn cel_filter(
748        item: impl CelValueConv<'a>,
749        map_fn: impl Fn(CelValue<'a>) -> Result<bool, CelError<'a>>,
750    ) -> Result<CelValue<'a>, CelError<'a>> {
751        let filter_map = |item: CelValue<'a>| match map_fn(item.clone()) {
752            Ok(false) => None,
753            Ok(true) => Some(Ok(item)),
754            Err(err) => Some(Err(err)),
755        };
756
757        match item.conv() {
758            CelValue::List(items) => Ok(CelValue::List(
759                items
760                    .iter()
761                    .cloned()
762                    .filter_map(filter_map)
763                    .collect::<Result<_, _>>()?,
764            )),
765            CelValue::Map(map) => Ok(CelValue::List(
766                map.iter()
767                    .map(|(key, _)| key)
768                    .cloned()
769                    .filter_map(filter_map)
770                    .collect::<Result<_, _>>()?,
771            )),
772            value => Err(CelError::BadUnaryOperation {
773                op: "filter",
774                value,
775            }),
776        }
777    }
778
779    pub fn cel_all(
780        item: impl CelValueConv<'a>,
781        map_fn: impl Fn(CelValue<'a>) -> Result<bool, CelError<'a>>,
782    ) -> Result<bool, CelError<'a>> {
783        fn all<'a>(
784            mut iter: impl Iterator<Item = CelValue<'a>>,
785            map_fn: impl Fn(CelValue<'a>) -> Result<bool, CelError<'a>>,
786        ) -> Result<bool, CelError<'a>> {
787            loop {
788                let Some(item) = iter.next() else {
789                    break Ok(true);
790                };
791
792                if !map_fn(item)? {
793                    break Ok(false);
794                }
795            }
796        }
797
798        match item.conv() {
799            CelValue::List(items) => all(items.iter().cloned(), map_fn),
800            CelValue::Map(map) => all(map.iter().map(|(key, _)| key).cloned(), map_fn),
801            value => Err(CelError::BadUnaryOperation { op: "all", value }),
802        }
803    }
804
805    pub fn cel_exists(
806        item: impl CelValueConv<'a>,
807        map_fn: impl Fn(CelValue<'a>) -> Result<bool, CelError<'a>>,
808    ) -> Result<bool, CelError<'a>> {
809        fn exists<'a>(
810            mut iter: impl Iterator<Item = CelValue<'a>>,
811            map_fn: impl Fn(CelValue<'a>) -> Result<bool, CelError<'a>>,
812        ) -> Result<bool, CelError<'a>> {
813            loop {
814                let Some(item) = iter.next() else {
815                    break Ok(false);
816                };
817
818                if map_fn(item)? {
819                    break Ok(true);
820                }
821            }
822        }
823
824        match item.conv() {
825            CelValue::List(items) => exists(items.iter().cloned(), map_fn),
826            CelValue::Map(map) => exists(map.iter().map(|(key, _)| key).cloned(), map_fn),
827            value => Err(CelError::BadUnaryOperation {
828                op: "existsOne",
829                value,
830            }),
831        }
832    }
833
834    pub fn cel_exists_one(
835        item: impl CelValueConv<'a>,
836        map_fn: impl Fn(CelValue<'a>) -> Result<bool, CelError<'a>>,
837    ) -> Result<bool, CelError<'a>> {
838        fn exists_one<'a>(
839            mut iter: impl Iterator<Item = CelValue<'a>>,
840            map_fn: impl Fn(CelValue<'a>) -> Result<bool, CelError<'a>>,
841        ) -> Result<bool, CelError<'a>> {
842            let mut seen = false;
843            loop {
844                let Some(item) = iter.next() else {
845                    break Ok(seen);
846                };
847
848                if map_fn(item)? {
849                    if seen {
850                        break Ok(false);
851                    }
852
853                    seen = true;
854                }
855            }
856        }
857
858        match item.conv() {
859            CelValue::List(items) => exists_one(items.iter().cloned(), map_fn),
860            CelValue::Map(map) => exists_one(map.iter().map(|(key, _)| key).cloned(), map_fn),
861            value => Err(CelError::BadUnaryOperation {
862                op: "existsOne",
863                value,
864            }),
865        }
866    }
867
868    pub fn cel_to_string(item: impl CelValueConv<'a>) -> CelValue<'a> {
869        match item.conv() {
870            item @ CelValue::String(_) => item,
871            CelValue::Bytes(CelBytes::Owned(bytes)) => CelValue::String(CelString::Owned(
872                String::from_utf8_lossy(bytes.as_ref()).into(),
873            )),
874            CelValue::Bytes(CelBytes::Borrowed(b)) => match String::from_utf8_lossy(b) {
875                Cow::Borrowed(b) => CelValue::String(CelString::Borrowed(b)),
876                Cow::Owned(o) => CelValue::String(CelString::Owned(o.into())),
877            },
878            item => CelValue::String(CelString::Owned(item.to_string().into())),
879        }
880    }
881
882    pub fn cel_to_bytes(item: impl CelValueConv<'a>) -> Result<CelValue<'a>, CelError<'a>> {
883        match item.conv() {
884            item @ CelValue::Bytes(_) => Ok(item.clone()),
885            CelValue::String(CelString::Owned(s)) => Ok(CelValue::Bytes(CelBytes::Owned(
886                s.as_bytes().to_vec().into(),
887            ))),
888            CelValue::String(CelString::Borrowed(s)) => {
889                Ok(CelValue::Bytes(CelBytes::Borrowed(s.as_bytes())))
890            }
891            value => Err(CelError::BadUnaryOperation { op: "bytes", value }),
892        }
893    }
894
895    pub fn cel_to_int(item: impl CelValueConv<'a>) -> Result<CelValue<'a>, CelError<'a>> {
896        match item.conv() {
897            CelValue::String(s) => {
898                if let Ok(number) = s.as_ref().parse() {
899                    Ok(CelValue::Number(NumberTy::I64(number)))
900                } else {
901                    Ok(CelValue::Null)
902                }
903            }
904            CelValue::Number(number) => {
905                if let Ok(number) = number.to_int() {
906                    Ok(CelValue::Number(number))
907                } else {
908                    Ok(CelValue::Null)
909                }
910            }
911            value => Err(CelError::BadUnaryOperation { op: "int", value }),
912        }
913    }
914
915    pub fn cel_to_uint(item: impl CelValueConv<'a>) -> Result<CelValue<'a>, CelError<'a>> {
916        match item.conv() {
917            CelValue::String(s) => {
918                if let Ok(number) = s.as_ref().parse() {
919                    Ok(CelValue::Number(NumberTy::U64(number)))
920                } else {
921                    Ok(CelValue::Null)
922                }
923            }
924            CelValue::Number(number) => {
925                if let Ok(number) = number.to_uint() {
926                    Ok(CelValue::Number(number))
927                } else {
928                    Ok(CelValue::Null)
929                }
930            }
931            value => Err(CelError::BadUnaryOperation { op: "uint", value }),
932        }
933    }
934
935    pub fn cel_to_double(item: impl CelValueConv<'a>) -> Result<CelValue<'a>, CelError<'a>> {
936        match item.conv() {
937            CelValue::String(s) => {
938                if let Ok(number) = s.as_ref().parse() {
939                    Ok(CelValue::Number(NumberTy::F64(number)))
940                } else {
941                    Ok(CelValue::Null)
942                }
943            }
944            CelValue::Number(number) => {
945                if let Ok(number) = number.to_double() {
946                    Ok(CelValue::Number(number))
947                } else {
948                    // I think this is unreachable as well
949                    Ok(CelValue::Null)
950                }
951            }
952            value => Err(CelError::BadUnaryOperation {
953                op: "double",
954                value,
955            }),
956        }
957    }
958
959    pub fn cel_to_enum(
960        item: impl CelValueConv<'a>,
961        path: impl CelValueConv<'a>,
962    ) -> Result<CelValue<'a>, CelError<'a>> {
963        match (item.conv(), path.conv()) {
964            (CelValue::Number(number), CelValue::String(tag)) => {
965                let Some(value) = number.to_i32() else {
966                    return Ok(CelValue::Null);
967                };
968
969                Ok(CelValue::Enum(CelEnum { tag, value }))
970            }
971            (CelValue::Enum(CelEnum { value, .. }), CelValue::String(tag)) => {
972                Ok(CelValue::Enum(CelEnum { tag, value }))
973            }
974            (value, path) => Err(CelError::BadOperation {
975                op: "enum",
976                left: value,
977                right: path,
978            }),
979        }
980    }
981}
982
983impl PartialEq for CelValue<'_> {
984    fn eq(&self, other: &Self) -> bool {
985        match (self, other) {
986            (CelValue::Bool(left), CelValue::Bool(right)) => left == right,
987            (
988                left @ (CelValue::Bytes(_) | CelValue::String(_)),
989                right @ (CelValue::Bytes(_) | CelValue::String(_)),
990            ) => {
991                let left = match left {
992                    CelValue::String(s) => s.as_bytes(),
993                    CelValue::Bytes(b) => b.as_ref(),
994                    _ => unreachable!(),
995                };
996
997                let right = match right {
998                    CelValue::String(s) => s.as_bytes(),
999                    CelValue::Bytes(b) => b.as_ref(),
1000                    _ => unreachable!(),
1001                };
1002
1003                left == right
1004            }
1005            (CelValue::Duration(left), CelValue::Duration(right)) => left == right,
1006            (CelValue::Duration(dur), CelValue::Number(seconds))
1007            | (CelValue::Number(seconds), CelValue::Duration(dur)) => {
1008                (dur.num_seconds() as f64) + dur.subsec_nanos() as f64 / 1_000_000_000.0 == *seconds
1009            }
1010            (CelValue::Timestamp(left), CelValue::Timestamp(right)) => left == right,
1011            (CelValue::Enum(left), CelValue::Enum(right)) => left == right,
1012            (CelValue::Enum(enum_), CelValue::Number(value))
1013            | (CelValue::Number(value), CelValue::Enum(enum_)) => enum_.value == *value,
1014            (CelValue::List(left), CelValue::List(right)) => left == right,
1015            (CelValue::Map(left), CelValue::Map(right)) => left == right,
1016            (CelValue::Number(left), CelValue::Number(right)) => left == right,
1017            (CelValue::Null, CelValue::Null) => true,
1018            _ => false,
1019        }
1020    }
1021}
1022
1023pub trait CelValueConv<'a> {
1024    fn conv(self) -> CelValue<'a>;
1025}
1026
1027impl CelValueConv<'_> for () {
1028    fn conv(self) -> CelValue<'static> {
1029        CelValue::Null
1030    }
1031}
1032
1033impl CelValueConv<'_> for bool {
1034    fn conv(self) -> CelValue<'static> {
1035        CelValue::Bool(self)
1036    }
1037}
1038
1039impl CelValueConv<'_> for i32 {
1040    fn conv(self) -> CelValue<'static> {
1041        CelValue::Number(NumberTy::I64(self as i64))
1042    }
1043}
1044
1045impl CelValueConv<'_> for u32 {
1046    fn conv(self) -> CelValue<'static> {
1047        CelValue::Number(NumberTy::U64(self as u64))
1048    }
1049}
1050
1051impl CelValueConv<'_> for i64 {
1052    fn conv(self) -> CelValue<'static> {
1053        CelValue::Number(NumberTy::I64(self))
1054    }
1055}
1056
1057impl CelValueConv<'_> for u64 {
1058    fn conv(self) -> CelValue<'static> {
1059        CelValue::Number(NumberTy::U64(self))
1060    }
1061}
1062
1063impl CelValueConv<'_> for f32 {
1064    fn conv(self) -> CelValue<'static> {
1065        CelValue::Number(NumberTy::F64(self as f64))
1066    }
1067}
1068
1069impl CelValueConv<'_> for f64 {
1070    fn conv(self) -> CelValue<'static> {
1071        CelValue::Number(NumberTy::F64(self))
1072    }
1073}
1074
1075impl<'a> CelValueConv<'a> for &'a str {
1076    fn conv(self) -> CelValue<'a> {
1077        CelValue::String(CelString::Borrowed(self))
1078    }
1079}
1080
1081impl CelValueConv<'_> for Bytes {
1082    fn conv(self) -> CelValue<'static> {
1083        CelValue::Bytes(CelBytes::Owned(self.clone()))
1084    }
1085}
1086
1087impl<'a> CelValueConv<'a> for &'a [u8] {
1088    fn conv(self) -> CelValue<'a> {
1089        CelValue::Bytes(CelBytes::Borrowed(self))
1090    }
1091}
1092
1093impl<'a, const N: usize> CelValueConv<'a> for &'a [u8; N] {
1094    fn conv(self) -> CelValue<'a> {
1095        (self as &[u8]).conv()
1096    }
1097}
1098
1099impl<'a> CelValueConv<'a> for &'a Vec<u8> {
1100    fn conv(self) -> CelValue<'a> {
1101        CelValue::Bytes(CelBytes::Borrowed(self))
1102    }
1103}
1104
1105impl<'a, T> CelValueConv<'a> for &'a [T]
1106where
1107    &'a T: CelValueConv<'a>,
1108{
1109    fn conv(self) -> CelValue<'a> {
1110        CelValue::List(self.iter().map(CelValueConv::conv).collect())
1111    }
1112}
1113
1114impl<'a, T, const N: usize> CelValueConv<'a> for &'a [T; N]
1115where
1116    &'a T: CelValueConv<'a>,
1117{
1118    fn conv(self) -> CelValue<'a> {
1119        (self as &[T]).conv()
1120    }
1121}
1122
1123impl<'a, T> CelValueConv<'a> for &'a Vec<T>
1124where
1125    &'a T: CelValueConv<'a>,
1126{
1127    fn conv(self) -> CelValue<'a> {
1128        self.as_slice().conv()
1129    }
1130}
1131
1132impl<'a> CelValueConv<'a> for &'a String {
1133    fn conv(self) -> CelValue<'a> {
1134        self.as_str().conv()
1135    }
1136}
1137
1138impl<'a, T> CelValueConv<'a> for &T
1139where
1140    T: CelValueConv<'a> + Copy,
1141{
1142    fn conv(self) -> CelValue<'a> {
1143        CelValueConv::conv(*self)
1144    }
1145}
1146
1147impl<'a> CelValueConv<'a> for &CelValue<'a> {
1148    fn conv(self) -> CelValue<'a> {
1149        self.clone()
1150    }
1151}
1152
1153impl std::fmt::Display for CelValue<'_> {
1154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1155        match self {
1156            CelValue::Bool(b) => std::fmt::Display::fmt(b, f),
1157            CelValue::Number(n) => std::fmt::Display::fmt(n, f),
1158            CelValue::String(s) => std::fmt::Display::fmt(s.as_ref(), f),
1159            CelValue::Bytes(b) => std::fmt::Debug::fmt(b.as_ref(), f),
1160            CelValue::List(l) => {
1161                let mut list = f.debug_list();
1162                for item in l.iter() {
1163                    list.entry(&fmtools::fmt(|fmt| item.fmt(fmt)));
1164                }
1165                list.finish()
1166            }
1167            CelValue::Map(m) => {
1168                let mut map = f.debug_map();
1169                for (key, value) in m.iter() {
1170                    map.entry(
1171                        &fmtools::fmt(|fmt| key.fmt(fmt)),
1172                        &fmtools::fmt(|fmt| value.fmt(fmt)),
1173                    );
1174                }
1175                map.finish()
1176            }
1177            CelValue::Null => std::fmt::Display::fmt("null", f),
1178            CelValue::Duration(d) => std::fmt::Display::fmt(d, f),
1179            CelValue::Timestamp(t) => std::fmt::Display::fmt(t, f),
1180            #[cfg(feature = "runtime")]
1181            CelValue::Enum(e) => e.into_string().fmt(f),
1182            #[cfg(not(feature = "runtime"))]
1183            CelValue::Enum(_) => panic!("enum to string called during build-time"),
1184        }
1185    }
1186}
1187
1188impl CelValue<'_> {
1189    pub fn to_bool(&self) -> bool {
1190        match self {
1191            CelValue::Bool(b) => *b,
1192            CelValue::Number(n) => *n != 0,
1193            CelValue::String(s) => !s.as_ref().is_empty(),
1194            CelValue::Bytes(b) => !b.as_ref().is_empty(),
1195            CelValue::List(l) => !l.is_empty(),
1196            CelValue::Map(m) => !m.is_empty(),
1197            CelValue::Null => false,
1198            CelValue::Duration(d) => !d.is_zero(),
1199            CelValue::Timestamp(t) => t.timestamp_nanos_opt().unwrap_or_default() != 0,
1200            #[cfg(feature = "runtime")]
1201            CelValue::Enum(t) => t.is_valid(),
1202            #[cfg(not(feature = "runtime"))]
1203            CelValue::Enum(_) => panic!("enum to bool called during build-time"),
1204        }
1205    }
1206}
1207
1208#[derive(Clone, Copy, Debug)]
1209pub enum NumberTy {
1210    I64(i64),
1211    U64(u64),
1212    F64(f64),
1213}
1214
1215impl PartialOrd for NumberTy {
1216    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1217        NumberTy::promote(*self, *other).and_then(|(l, r)| match (l, r) {
1218            (NumberTy::I64(l), NumberTy::I64(r)) => Some(l.cmp(&r)),
1219            (NumberTy::U64(l), NumberTy::U64(r)) => Some(l.cmp(&r)),
1220            (NumberTy::F64(l), NumberTy::F64(r)) => {
1221                Some(if l.approx_eq(r, float_cmp::F64Margin::default()) {
1222                    std::cmp::Ordering::Equal
1223                } else {
1224                    l.partial_cmp(&r).unwrap_or(std::cmp::Ordering::Equal)
1225                })
1226            }
1227            // I think this is unreachable
1228            _ => None,
1229        })
1230    }
1231}
1232
1233impl NumberTy {
1234    pub fn cel_add(self, other: Self) -> Result<Self, CelError<'static>> {
1235        const ERROR: CelError<'static> = CelError::NumberOutOfRange { op: "addition" };
1236        match NumberTy::promote(self, other).ok_or(ERROR)? {
1237            (NumberTy::I64(l), NumberTy::I64(r)) => {
1238                Ok(NumberTy::I64(l.checked_add(r).ok_or(ERROR)?))
1239            }
1240            (NumberTy::U64(l), NumberTy::U64(r)) => {
1241                Ok(NumberTy::U64(l.checked_add(r).ok_or(ERROR)?))
1242            }
1243            (NumberTy::F64(l), NumberTy::F64(r)) => Ok(NumberTy::F64(l + r)),
1244            // I think this is unreachable
1245            _ => Err(ERROR),
1246        }
1247    }
1248
1249    pub fn cel_sub(self, other: Self) -> Result<Self, CelError<'static>> {
1250        const ERROR: CelError<'static> = CelError::NumberOutOfRange { op: "subtraction" };
1251        match NumberTy::promote(self, other).ok_or(ERROR)? {
1252            (NumberTy::I64(l), NumberTy::I64(r)) => {
1253                Ok(NumberTy::I64(l.checked_sub(r).ok_or(ERROR)?))
1254            }
1255            (NumberTy::U64(l), NumberTy::U64(r)) => {
1256                Ok(NumberTy::U64(l.checked_sub(r).ok_or(ERROR)?))
1257            }
1258            (NumberTy::F64(l), NumberTy::F64(r)) => Ok(NumberTy::F64(l - r)),
1259            // I think this is unreachable
1260            _ => Err(ERROR),
1261        }
1262    }
1263
1264    pub fn cel_mul(self, other: Self) -> Result<Self, CelError<'static>> {
1265        const ERROR: CelError<'static> = CelError::NumberOutOfRange {
1266            op: "multiplication",
1267        };
1268        match NumberTy::promote(self, other).ok_or(ERROR)? {
1269            (NumberTy::I64(l), NumberTy::I64(r)) => {
1270                Ok(NumberTy::I64(l.checked_mul(r).ok_or(ERROR)?))
1271            }
1272            (NumberTy::U64(l), NumberTy::U64(r)) => {
1273                Ok(NumberTy::U64(l.checked_mul(r).ok_or(ERROR)?))
1274            }
1275            (NumberTy::F64(l), NumberTy::F64(r)) => Ok(NumberTy::F64(l * r)),
1276            // I think this is unreachable
1277            _ => Err(ERROR),
1278        }
1279    }
1280
1281    pub fn cel_div(self, other: Self) -> Result<Self, CelError<'static>> {
1282        if other == 0 {
1283            return Err(CelError::NumberOutOfRange {
1284                op: "division by zero",
1285            });
1286        }
1287
1288        const ERROR: CelError<'static> = CelError::NumberOutOfRange { op: "division" };
1289        match NumberTy::promote(self, other).ok_or(ERROR)? {
1290            (NumberTy::I64(l), NumberTy::I64(r)) => {
1291                Ok(NumberTy::I64(l.checked_div(r).ok_or(ERROR)?))
1292            }
1293            (NumberTy::U64(l), NumberTy::U64(r)) => {
1294                Ok(NumberTy::U64(l.checked_div(r).ok_or(ERROR)?))
1295            }
1296            (NumberTy::F64(l), NumberTy::F64(r)) => Ok(NumberTy::F64(l / r)),
1297            // I think this is unreachable
1298            _ => Err(ERROR),
1299        }
1300    }
1301
1302    pub fn cel_rem(self, other: Self) -> Result<Self, CelError<'static>> {
1303        if other == 0 {
1304            return Err(CelError::NumberOutOfRange {
1305                op: "remainder by zero",
1306            });
1307        }
1308
1309        const ERROR: CelError<'static> = CelError::NumberOutOfRange { op: "remainder" };
1310        match NumberTy::promote(self, other).ok_or(ERROR)? {
1311            (NumberTy::I64(l), NumberTy::I64(r)) => {
1312                Ok(NumberTy::I64(l.checked_rem(r).ok_or(ERROR)?))
1313            }
1314            (NumberTy::U64(l), NumberTy::U64(r)) => {
1315                Ok(NumberTy::U64(l.checked_rem(r).ok_or(ERROR)?))
1316            }
1317            _ => Err(ERROR),
1318        }
1319    }
1320
1321    pub fn cel_neg(self) -> Result<NumberTy, CelError<'static>> {
1322        const ERROR: CelError<'static> = CelError::NumberOutOfRange { op: "negation" };
1323        match self {
1324            NumberTy::I64(n) => Ok(NumberTy::I64(n.checked_neg().ok_or(ERROR)?)),
1325            NumberTy::U64(n) => Ok(NumberTy::I64(
1326                n.to_i64().ok_or(ERROR)?.checked_neg().ok_or(ERROR)?,
1327            )),
1328            NumberTy::F64(n) => Ok(NumberTy::F64(-n)),
1329        }
1330    }
1331
1332    pub fn to_int(self) -> Result<NumberTy, CelError<'static>> {
1333        const ERROR: CelError<'static> = CelError::NumberOutOfRange { op: "int" };
1334        match self {
1335            NumberTy::I64(n) => Ok(NumberTy::I64(n)),
1336            NumberTy::U64(n) => Ok(NumberTy::I64(n.to_i64().ok_or(ERROR)?)),
1337            NumberTy::F64(n) => Ok(NumberTy::I64(n.to_i64().ok_or(ERROR)?)),
1338        }
1339    }
1340
1341    pub fn to_uint(self) -> Result<NumberTy, CelError<'static>> {
1342        const ERROR: CelError<'static> = CelError::NumberOutOfRange { op: "int" };
1343        match self {
1344            NumberTy::I64(n) => Ok(NumberTy::U64(n.to_u64().ok_or(ERROR)?)),
1345            NumberTy::U64(n) => Ok(NumberTy::U64(n)),
1346            NumberTy::F64(n) => Ok(NumberTy::U64(n.to_u64().ok_or(ERROR)?)),
1347        }
1348    }
1349
1350    pub fn to_double(self) -> Result<NumberTy, CelError<'static>> {
1351        const ERROR: CelError<'static> = CelError::NumberOutOfRange { op: "int" };
1352        match self {
1353            NumberTy::I64(n) => Ok(NumberTy::F64(n.to_f64().ok_or(ERROR)?)),
1354            NumberTy::U64(n) => Ok(NumberTy::F64(n.to_f64().ok_or(ERROR)?)),
1355            NumberTy::F64(n) => Ok(NumberTy::F64(n)),
1356        }
1357    }
1358}
1359
1360impl std::fmt::Display for NumberTy {
1361    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1362        match self {
1363            NumberTy::I64(n) => std::fmt::Display::fmt(n, f),
1364            NumberTy::U64(n) => std::fmt::Display::fmt(n, f),
1365            NumberTy::F64(n) => write!(f, "{n:.2}"), // limit to 2 decimal places
1366        }
1367    }
1368}
1369
1370impl PartialEq for NumberTy {
1371    fn eq(&self, other: &Self) -> bool {
1372        NumberTy::promote(*self, *other)
1373            .map(|(l, r)| match (l, r) {
1374                (NumberTy::I64(l), NumberTy::I64(r)) => l == r,
1375                (NumberTy::U64(l), NumberTy::U64(r)) => l == r,
1376                (NumberTy::F64(l), NumberTy::F64(r)) => {
1377                    l.approx_eq(r, float_cmp::F64Margin::default())
1378                }
1379                // I think this is unreachable
1380                _ => false,
1381            })
1382            .unwrap_or(false)
1383    }
1384}
1385
1386macro_rules! impl_eq_number {
1387    ($ty:ty) => {
1388        impl PartialEq<$ty> for NumberTy {
1389            fn eq(&self, other: &$ty) -> bool {
1390                NumberTy::from(*other) == *self
1391            }
1392        }
1393
1394        impl PartialEq<NumberTy> for $ty {
1395            fn eq(&self, other: &NumberTy) -> bool {
1396                other == self
1397            }
1398        }
1399    };
1400}
1401
1402impl_eq_number!(i32);
1403impl_eq_number!(u32);
1404impl_eq_number!(i64);
1405impl_eq_number!(u64);
1406impl_eq_number!(f64);
1407
1408impl From<i32> for NumberTy {
1409    fn from(value: i32) -> Self {
1410        Self::I64(value as i64)
1411    }
1412}
1413
1414impl From<u32> for NumberTy {
1415    fn from(value: u32) -> Self {
1416        Self::U64(value as u64)
1417    }
1418}
1419
1420impl From<i64> for NumberTy {
1421    fn from(value: i64) -> Self {
1422        Self::I64(value)
1423    }
1424}
1425
1426impl From<u64> for NumberTy {
1427    fn from(value: u64) -> Self {
1428        Self::U64(value)
1429    }
1430}
1431
1432impl From<f64> for NumberTy {
1433    fn from(value: f64) -> Self {
1434        Self::F64(value)
1435    }
1436}
1437
1438impl From<f32> for NumberTy {
1439    fn from(value: f32) -> Self {
1440        Self::F64(value as f64)
1441    }
1442}
1443
1444impl CelValueConv<'_> for NumberTy {
1445    fn conv(self) -> CelValue<'static> {
1446        CelValue::Number(self)
1447    }
1448}
1449
1450impl<'a> CelValueConv<'a> for CelValue<'a> {
1451    fn conv(self) -> CelValue<'a> {
1452        self
1453    }
1454}
1455
1456macro_rules! impl_to_primitive_number {
1457    ($fn:ident, $ty:ty) => {
1458        fn $fn(&self) -> Option<$ty> {
1459            match self {
1460                NumberTy::I64(i) => i.$fn(),
1461                NumberTy::U64(u) => u.$fn(),
1462                NumberTy::F64(f) => f.$fn(),
1463            }
1464        }
1465    };
1466}
1467
1468impl num_traits::ToPrimitive for NumberTy {
1469    impl_to_primitive_number!(to_f32, f32);
1470
1471    impl_to_primitive_number!(to_f64, f64);
1472
1473    impl_to_primitive_number!(to_i128, i128);
1474
1475    impl_to_primitive_number!(to_i16, i16);
1476
1477    impl_to_primitive_number!(to_i32, i32);
1478
1479    impl_to_primitive_number!(to_i64, i64);
1480
1481    impl_to_primitive_number!(to_i8, i8);
1482
1483    impl_to_primitive_number!(to_u128, u128);
1484
1485    impl_to_primitive_number!(to_u16, u16);
1486
1487    impl_to_primitive_number!(to_u32, u32);
1488
1489    impl_to_primitive_number!(to_u64, u64);
1490}
1491
1492impl NumberTy {
1493    pub fn promote(left: Self, right: Self) -> Option<(Self, Self)> {
1494        match (left, right) {
1495            (NumberTy::I64(l), NumberTy::I64(r)) => Some((NumberTy::I64(l), NumberTy::I64(r))),
1496            (NumberTy::U64(l), NumberTy::U64(r)) => Some((NumberTy::U64(l), NumberTy::U64(r))),
1497            (NumberTy::F64(_), _) | (_, NumberTy::F64(_)) => {
1498                Some((Self::F64(left.to_f64()?), Self::F64(right.to_f64()?)))
1499            }
1500            (NumberTy::I64(_), _) | (_, NumberTy::I64(_)) => {
1501                Some((Self::I64(left.to_i64()?), Self::I64(right.to_i64()?)))
1502            }
1503        }
1504    }
1505}
1506
1507pub fn array_access<'a, 'b, T>(
1508    array: &'a [T],
1509    idx: impl CelValueConv<'b>,
1510) -> Result<&'a T, CelError<'b>> {
1511    let idx = idx.conv();
1512    match idx.as_number().and_then(|n| n.to_usize()) {
1513        Some(idx) => array
1514            .get(idx)
1515            .ok_or(CelError::IndexOutOfBounds(idx, array.len())),
1516        _ => Err(CelError::IndexWithBadIndex(idx)),
1517    }
1518}
1519
1520macro_rules! impl_partial_eq {
1521    ($($ty:ty),*$(,)?) => {
1522        $(
1523            impl PartialEq<$ty> for CelValue<'_> {
1524                fn eq(&self, other: &$ty) -> bool {
1525                    self == &other.conv()
1526                }
1527            }
1528
1529            impl PartialEq<CelValue<'_>> for $ty {
1530                fn eq(&self, other: &CelValue<'_>) -> bool {
1531                    other == self
1532                }
1533            }
1534        )*
1535    };
1536}
1537
1538impl_partial_eq!(String, i32, i64, f64, f32, Vec<u8>, u32, u64);
1539
1540impl PartialEq<Bytes> for CelValue<'_> {
1541    fn eq(&self, other: &Bytes) -> bool {
1542        self == &other.clone().conv()
1543    }
1544}
1545
1546impl PartialEq<CelValue<'_>> for Bytes {
1547    fn eq(&self, other: &CelValue<'_>) -> bool {
1548        other == self
1549    }
1550}
1551
1552pub fn array_contains<'a, 'b, T: PartialEq<CelValue<'b>>>(
1553    array: &'a [T],
1554    value: impl CelValueConv<'b>,
1555) -> bool {
1556    let value = value.conv();
1557    array.iter().any(|v| v == &value)
1558}
1559
1560trait MapKeyCast {
1561    type Borrow: ToOwned + ?Sized;
1562
1563    fn make_key<'a>(key: &'a CelValue<'a>) -> Option<Cow<'a, Self::Borrow>>
1564    where
1565        Self::Borrow: ToOwned;
1566}
1567
1568macro_rules! impl_map_key_cast_number {
1569    ($ty:ty, $fn:ident) => {
1570        impl MapKeyCast for $ty {
1571            type Borrow = Self;
1572
1573            fn make_key<'a>(key: &'a CelValue<'a>) -> Option<Cow<'a, Self>> {
1574                match key {
1575                    CelValue::Number(number) => number.$fn().map(Cow::Owned),
1576                    _ => None,
1577                }
1578            }
1579        }
1580    };
1581}
1582
1583impl_map_key_cast_number!(i32, to_i32);
1584impl_map_key_cast_number!(u32, to_u32);
1585impl_map_key_cast_number!(i64, to_i64);
1586impl_map_key_cast_number!(u64, to_u64);
1587
1588impl MapKeyCast for String {
1589    type Borrow = str;
1590
1591    fn make_key<'a>(key: &'a CelValue<'a>) -> Option<Cow<'a, Self::Borrow>> {
1592        match key {
1593            CelValue::String(s) => Some(Cow::Borrowed(s.as_ref())),
1594            _ => None,
1595        }
1596    }
1597}
1598
1599trait Map<K, V> {
1600    fn get<Q>(&self, key: &Q) -> Option<&V>
1601    where
1602        K: std::borrow::Borrow<Q>,
1603        Q: std::hash::Hash + std::cmp::Ord + ?Sized;
1604}
1605
1606impl<K, V, S> Map<K, V> for HashMap<K, V, S>
1607where
1608    K: std::hash::Hash + std::cmp::Eq,
1609    S: std::hash::BuildHasher,
1610{
1611    fn get<Q>(&self, key: &Q) -> Option<&V>
1612    where
1613        K: std::borrow::Borrow<Q>,
1614        Q: std::hash::Hash + std::cmp::Eq + ?Sized,
1615    {
1616        HashMap::get(self, key)
1617    }
1618}
1619
1620impl<K, V> Map<K, V> for BTreeMap<K, V>
1621where
1622    K: std::cmp::Ord,
1623{
1624    fn get<Q>(&self, key: &Q) -> Option<&V>
1625    where
1626        K: std::borrow::Borrow<Q>,
1627        Q: std::cmp::Ord + ?Sized,
1628    {
1629        BTreeMap::get(self, key)
1630    }
1631}
1632
1633#[allow(private_bounds)]
1634pub fn map_access<'a, 'b, K, V>(
1635    map: &'a impl Map<K, V>,
1636    key: impl CelValueConv<'b>,
1637) -> Result<&'a V, CelError<'b>>
1638where
1639    K: Ord + Hash + MapKeyCast,
1640    K: std::borrow::Borrow<K::Borrow>,
1641    K::Borrow: std::cmp::Eq + std::hash::Hash + std::cmp::Ord,
1642{
1643    let key = key.conv();
1644    K::make_key(&key)
1645        .and_then(|key| map.get(&key))
1646        .ok_or(CelError::MapKeyNotFound(key))
1647}
1648
1649#[allow(private_bounds)]
1650pub fn map_contains<'a, 'b, K, V>(map: &'a impl Map<K, V>, key: impl CelValueConv<'b>) -> bool
1651where
1652    K: Ord + Hash + MapKeyCast,
1653    K: std::borrow::Borrow<K::Borrow>,
1654    K::Borrow: std::cmp::Eq + std::hash::Hash + std::cmp::Ord,
1655{
1656    let key = key.conv();
1657    K::make_key(&key).and_then(|key| map.get(&key)).is_some()
1658}
1659
1660pub trait CelBooleanConv {
1661    fn to_bool(&self) -> bool;
1662}
1663
1664impl CelBooleanConv for bool {
1665    fn to_bool(&self) -> bool {
1666        *self
1667    }
1668}
1669
1670impl CelBooleanConv for CelValue<'_> {
1671    fn to_bool(&self) -> bool {
1672        CelValue::to_bool(self)
1673    }
1674}
1675
1676impl<T: CelBooleanConv> CelBooleanConv for Option<T> {
1677    fn to_bool(&self) -> bool {
1678        self.as_ref().map(CelBooleanConv::to_bool).unwrap_or(false)
1679    }
1680}
1681
1682impl<T> CelBooleanConv for Vec<T> {
1683    fn to_bool(&self) -> bool {
1684        !self.is_empty()
1685    }
1686}
1687
1688impl<K, V> CelBooleanConv for BTreeMap<K, V> {
1689    fn to_bool(&self) -> bool {
1690        !self.is_empty()
1691    }
1692}
1693
1694impl<K, V> CelBooleanConv for HashMap<K, V> {
1695    fn to_bool(&self) -> bool {
1696        !self.is_empty()
1697    }
1698}
1699
1700impl<T> CelBooleanConv for &T
1701where
1702    T: CelBooleanConv,
1703{
1704    fn to_bool(&self) -> bool {
1705        CelBooleanConv::to_bool(*self)
1706    }
1707}
1708
1709impl CelBooleanConv for str {
1710    fn to_bool(&self) -> bool {
1711        !self.is_empty()
1712    }
1713}
1714
1715impl CelBooleanConv for String {
1716    fn to_bool(&self) -> bool {
1717        !self.is_empty()
1718    }
1719}
1720
1721impl<T: CelBooleanConv> CelBooleanConv for [T] {
1722    fn to_bool(&self) -> bool {
1723        !self.is_empty()
1724    }
1725}
1726
1727impl CelBooleanConv for Bytes {
1728    fn to_bool(&self) -> bool {
1729        !self.is_empty()
1730    }
1731}
1732
1733pub fn to_bool(value: impl CelBooleanConv) -> bool {
1734    value.to_bool()
1735}
1736
1737#[cfg(feature = "runtime")]
1738#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1739pub enum CelMode {
1740    Proto,
1741    Serde,
1742}
1743
1744#[cfg(feature = "runtime")]
1745thread_local! {
1746    static CEL_MODE: std::cell::Cell<CelMode> = const { std::cell::Cell::new(CelMode::Proto) };
1747}
1748
1749#[cfg(feature = "runtime")]
1750impl CelMode {
1751    pub fn set(self) {
1752        CEL_MODE.set(self);
1753    }
1754
1755    pub fn current() -> CelMode {
1756        CEL_MODE.get()
1757    }
1758
1759    pub fn is_json(self) -> bool {
1760        matches!(self, Self::Serde)
1761    }
1762
1763    pub fn is_proto(self) -> bool {
1764        matches!(self, Self::Proto)
1765    }
1766}
1767
1768#[derive(Debug, PartialEq, Clone)]
1769pub struct CelEnum<'a> {
1770    pub tag: CelString<'a>,
1771    pub value: i32,
1772}
1773
1774impl<'a> CelEnum<'a> {
1775    pub fn new(tag: CelString<'a>, value: i32) -> CelEnum<'a> {
1776        CelEnum { tag, value }
1777    }
1778
1779    #[cfg(feature = "runtime")]
1780    pub fn into_string(&self) -> CelValue<'static> {
1781        EnumVtable::from_tag(self.tag.as_ref())
1782            .map(|vt| match CEL_MODE.get() {
1783                CelMode::Serde => (vt.to_serde)(self.value),
1784                CelMode::Proto => (vt.to_proto)(self.value),
1785            })
1786            .unwrap_or(CelValue::Number(NumberTy::I64(self.value as i64)))
1787    }
1788
1789    #[cfg(feature = "runtime")]
1790    pub fn is_valid(&self) -> bool {
1791        EnumVtable::from_tag(self.tag.as_ref()).is_some_and(|vt| (vt.is_valid)(self.value))
1792    }
1793}
1794
1795#[cfg(feature = "runtime")]
1796#[derive(Debug, Copy, Clone)]
1797pub struct EnumVtable {
1798    pub proto_path: &'static str,
1799    pub is_valid: fn(i32) -> bool,
1800    pub to_serde: fn(i32) -> CelValue<'static>,
1801    pub to_proto: fn(i32) -> CelValue<'static>,
1802}
1803
1804#[cfg(feature = "runtime")]
1805impl EnumVtable {
1806    pub fn from_tag(tag: &str) -> Option<&'static EnumVtable> {
1807        static LOOKUP: std::sync::LazyLock<HashMap<&'static str, &'static EnumVtable>> =
1808            std::sync::LazyLock::new(|| {
1809                TONNEAU_CEL_ENUM_VTABLE
1810                    .into_iter()
1811                    .map(|item| (item.proto_path, item))
1812                    .collect()
1813            });
1814
1815        LOOKUP.get(tag).copied()
1816    }
1817}
1818
1819#[cfg(feature = "runtime")]
1820#[linkme::distributed_slice]
1821pub static TONNEAU_CEL_ENUM_VTABLE: [EnumVtable];
1822
1823#[cfg(test)]
1824#[cfg_attr(all(test, coverage_nightly), coverage(off))]
1825mod tests {
1826    use std::borrow::Cow;
1827    use std::cmp::Ordering;
1828    use std::collections::{BTreeMap, HashMap};
1829    use std::sync::Arc;
1830
1831    use bytes::Bytes;
1832    use chrono::{DateTime, Duration, FixedOffset};
1833    use num_traits::ToPrimitive;
1834    use regex::Regex;
1835    use uuid::Uuid;
1836
1837    use super::CelString;
1838    use crate::{
1839        CelBooleanConv, CelBytes, CelEnum, CelError, CelValue, CelValueConv, MapKeyCast, NumberTy,
1840        array_access, array_contains, map_access, map_contains,
1841    };
1842
1843    #[test]
1844    fn celstring_eq() {
1845        // borrowed vs borrowed
1846        let b1 = CelString::Borrowed("foo");
1847        let b2 = CelString::Borrowed("foo");
1848        assert_eq!(b1, b2);
1849
1850        // owned vs owned
1851        let o1 = CelString::Owned(Arc::from("foo"));
1852        let o2 = CelString::Owned(Arc::from("foo"));
1853        assert_eq!(o1, o2);
1854
1855        // borrowed vs owned (both directions)
1856        let b = CelString::Borrowed("foo");
1857        let o = CelString::Owned(Arc::from("foo"));
1858        assert_eq!(b, o.clone());
1859        assert_eq!(o, b);
1860
1861        // inequality
1862        let bar_b = CelString::Borrowed("bar");
1863        let bar_o = CelString::Owned(Arc::from("bar"));
1864        assert_ne!(b1, bar_b);
1865        assert_ne!(o1, bar_o);
1866    }
1867
1868    #[test]
1869    fn celstring_borrowed() {
1870        let original = String::from("hello");
1871        let cs: CelString = (&original).into();
1872
1873        match cs {
1874            CelString::Borrowed(s) => {
1875                assert_eq!(s, "hello");
1876                // ensure it really is a borrow, not an owned Arc
1877                let orig_ptr = original.as_ptr();
1878                let borrow_ptr = s.as_ptr();
1879                assert_eq!(orig_ptr, borrow_ptr);
1880            }
1881            _ => panic!("expected CelString::Borrowed"),
1882        }
1883    }
1884
1885    #[test]
1886    fn celstring_owned() {
1887        let arc: Arc<str> = Arc::from("world");
1888        let cs: CelString<'static> = (&arc).into();
1889
1890        match cs {
1891            CelString::Owned(o) => {
1892                assert_eq!(o.as_ref(), "world");
1893                assert!(Arc::ptr_eq(&o, &arc));
1894                assert_eq!(Arc::strong_count(&arc), 2);
1895            }
1896            _ => panic!("expected CelString::Owned"),
1897        }
1898    }
1899
1900    #[test]
1901    fn borrowed_eq_borrowed() {
1902        let slice1: &[u8] = &[1, 2, 3];
1903        let slice2: &[u8] = &[1, 2, 3];
1904        let b1: CelBytes = slice1.into();
1905        let b2: CelBytes = slice2.into();
1906        assert_eq!(b1, b2);
1907    }
1908
1909    #[test]
1910    fn owned_eq_owned() {
1911        let data = vec![10, 20, 30];
1912        let o1: CelBytes<'static> = Bytes::from(data.clone()).into();
1913        let o2: CelBytes<'static> = Bytes::from(data.clone()).into();
1914        assert_eq!(o1, o2);
1915    }
1916
1917    #[test]
1918    fn borrowed_eq_owned() {
1919        let v = vec![5, 6, 7];
1920        let owned: CelBytes<'static> = Bytes::from(v.clone()).into();
1921        let borrowed: CelBytes = v.as_slice().into();
1922
1923        // Owned vs Borrowed
1924        assert_eq!(owned, borrowed);
1925        // Borrowed vs Owned
1926        assert_eq!(borrowed, owned);
1927    }
1928
1929    #[test]
1930    fn celbytes_neq() {
1931        let b1: CelBytes = (&[1, 2, 3][..]).into();
1932        let b2: CelBytes = (&[4, 5, 6][..]).into();
1933        assert_ne!(b1, b2);
1934
1935        let o1: CelBytes<'static> = Bytes::from(vec![1, 2, 3]).into();
1936        let o2: CelBytes<'static> = Bytes::from(vec![7, 8, 9]).into();
1937        assert_ne!(o1, o2);
1938    }
1939
1940    #[test]
1941    fn celbytes_borrowed_slice() {
1942        let arr: [u8; 4] = [9, 8, 7, 6];
1943        let cb: CelBytes = arr.as_slice().into();
1944        match cb {
1945            CelBytes::Borrowed(s) => {
1946                assert_eq!(s, arr.as_slice());
1947                // pointer equality check
1948                assert_eq!(s.as_ptr(), arr.as_ptr());
1949            }
1950            _ => panic!("Expected CelBytes::Borrowed from slice"),
1951        }
1952    }
1953
1954    #[test]
1955    fn celbytes_bstr_owned() {
1956        let bytes = Bytes::from_static(b"rust");
1957        let cb: CelBytes = bytes.clone().into();
1958        match cb {
1959            CelBytes::Owned(b) => {
1960                assert_eq!(b, bytes);
1961            }
1962            _ => panic!("Expected CelBytes::Owned from Bytes"),
1963        }
1964    }
1965
1966    #[test]
1967    fn celbytes_vec_owned() {
1968        let data = vec![0x10, 0x20, 0x30];
1969        let cb: CelBytes<'static> = data.clone().into();
1970
1971        match cb {
1972            CelBytes::Owned(bytes) => {
1973                assert_eq!(bytes.as_ref(), &[0x10, 0x20, 0x30]);
1974                assert_eq!(bytes, Bytes::from(data));
1975            }
1976            _ => panic!("Expected CelBytes::Owned variant"),
1977        }
1978    }
1979
1980    #[test]
1981    fn celbytes_vec_borrowed() {
1982        let data = vec![4u8, 5, 6];
1983        let cb: CelBytes = (&data).into();
1984
1985        match cb {
1986            CelBytes::Borrowed(slice) => {
1987                assert_eq!(slice, data.as_slice());
1988
1989                let data_ptr = data.as_ptr();
1990                let slice_ptr = slice.as_ptr();
1991                assert_eq!(data_ptr, slice_ptr);
1992            }
1993            _ => panic!("Expected CelBytes::Borrowed variant"),
1994        }
1995    }
1996
1997    #[test]
1998    fn celvalue_partial_cmp() {
1999        let one = 1i32.conv();
2000        let two = 2i32.conv();
2001        assert_eq!(one.partial_cmp(&two), Some(Ordering::Less));
2002        assert_eq!(two.partial_cmp(&one), Some(Ordering::Greater));
2003        assert_eq!(one.partial_cmp(&1i32.conv()), Some(Ordering::Equal));
2004    }
2005
2006    #[test]
2007    fn celvalue_str_byte_partial_cmp() {
2008        let s1 = "abc".conv();
2009        let s2 = "abd".conv();
2010        assert_eq!(s1.partial_cmp(&s2), Some(Ordering::Less));
2011
2012        let b1 = Bytes::from_static(b"abc").conv();
2013        let b2 = Bytes::from_static(b"abd").conv();
2014        assert_eq!(b1.partial_cmp(&b2), Some(Ordering::Less));
2015
2016        // cross: string vs bytes
2017        assert_eq!(s1.partial_cmp(&b1), Some(Ordering::Equal));
2018        assert_eq!(b1.partial_cmp(&s2), Some(Ordering::Less));
2019    }
2020
2021    #[test]
2022    fn celvalue_mismatched_partial_cmp() {
2023        let num = 1i32.conv();
2024        let strv = "a".conv();
2025        assert_eq!(num.partial_cmp(&strv), None);
2026        assert_eq!(strv.partial_cmp(&num), None);
2027
2028        let binding = Vec::<i32>::new();
2029        let list = (&binding).conv();
2030        let map = CelValue::Map(Arc::from(vec![]));
2031        assert_eq!(list.partial_cmp(&map), None);
2032    }
2033
2034    // Helpers to build list and map CelValues
2035    fn make_list(vals: &[i32]) -> CelValue<'static> {
2036        let items: Vec<_> = vals.iter().map(|&n| n.conv()).collect();
2037        CelValue::List(Arc::from(items))
2038    }
2039
2040    fn make_map(pairs: &[(i32, i32)]) -> CelValue<'static> {
2041        let items: Vec<_> = pairs.iter().map(|&(k, v)| (k.conv(), v.conv())).collect();
2042        CelValue::Map(Arc::from(items))
2043    }
2044
2045    #[test]
2046    fn celvalue_pos_neg_ints() {
2047        let num = CelValue::Number(NumberTy::I64(42));
2048        assert_eq!(num.as_number(), Some(NumberTy::I64(42)));
2049
2050        let neg = CelValue::cel_neg(5i32);
2051        assert_eq!(neg.unwrap(), CelValue::Number(NumberTy::I64(-5)));
2052
2053        let err = CelValue::cel_neg("foo").unwrap_err();
2054        matches!(err, CelError::BadUnaryOperation { op: "-", .. });
2055    }
2056
2057    #[test]
2058    fn celvalue_map_keys() {
2059        let map = make_map(&[(1, 10), (2, 20)]);
2060        let v = CelValue::cel_access(map.clone(), 2i32).unwrap();
2061        assert_eq!(v, 20i32.conv());
2062
2063        let err = CelValue::cel_access(map, 3i32).unwrap_err();
2064        matches!(err, CelError::MapKeyNotFound(k) if k == 3i32.conv());
2065    }
2066
2067    #[test]
2068    fn celvalue_list_access() {
2069        let list = make_list(&[100, 200, 300]);
2070        let v = CelValue::cel_access(list.clone(), 1u32).unwrap();
2071        assert_eq!(v, 200i32.conv());
2072
2073        let err = CelValue::cel_access(list.clone(), 5i32).unwrap_err();
2074        matches!(err, CelError::IndexOutOfBounds(5, 3));
2075
2076        let err2 = CelValue::cel_access(list, "not_index").unwrap_err();
2077        matches!(err2, CelError::IndexWithBadIndex(k) if k == "not_index".conv());
2078    }
2079
2080    #[test]
2081    fn celvalue_bad_access() {
2082        let s = "hello".conv();
2083        let err = CelValue::cel_access(s.clone(), 0i32).unwrap_err();
2084        matches!(err, CelError::BadAccess { member, container } if member == 0i32.conv() && container == s);
2085    }
2086
2087    #[test]
2088    fn celvalue_add() {
2089        // number
2090        assert_eq!(CelValue::cel_add(3i32, 4i32).unwrap(), 7i32.conv());
2091        // string
2092        let s = CelValue::cel_add("foo", "bar").unwrap();
2093        assert_eq!(s, CelValue::String(CelString::Owned(Arc::from("foobar"))));
2094        // bytes
2095        let b = CelValue::cel_add(Bytes::from_static(b"ab"), Bytes::from_static(b"cd")).unwrap();
2096        assert_eq!(
2097            b,
2098            CelValue::Bytes(CelBytes::Owned(Bytes::from_static(b"abcd")))
2099        );
2100        // list
2101        let l = CelValue::cel_add(make_list(&[1, 2]), make_list(&[3])).unwrap();
2102        assert_eq!(l, make_list(&[1, 2, 3]));
2103        // map
2104        let m1 = make_map(&[(1, 1)]);
2105        let m2 = make_map(&[(2, 2)]);
2106        let m3 = CelValue::cel_add(m1.clone(), m2.clone()).unwrap();
2107        assert_eq!(m3, make_map(&[(1, 1), (2, 2)]));
2108        // bad operation
2109        let err = CelValue::cel_add(1i32, "x").unwrap_err();
2110        matches!(err, CelError::BadOperation { op: "+", .. });
2111    }
2112
2113    #[test]
2114    fn celvalue_sub_mul_div_rem() {
2115        // sub
2116        assert_eq!(CelValue::cel_sub(10i32, 3i32).unwrap(), 7i32.conv());
2117        assert!(matches!(
2118            CelValue::cel_sub(1i32, "x").unwrap_err(),
2119            CelError::BadOperation { op: "-", .. }
2120        ));
2121        // mul
2122        assert_eq!(CelValue::cel_mul(6i32, 7i32).unwrap(), 42i32.conv());
2123        assert!(matches!(
2124            CelValue::cel_mul("a", 2i32).unwrap_err(),
2125            CelError::BadOperation { op: "*", .. }
2126        ));
2127        // div
2128        assert_eq!(CelValue::cel_div(8i32, 2i32).unwrap(), 4i32.conv());
2129        assert!(matches!(
2130            CelValue::cel_div(8i32, "x").unwrap_err(),
2131            CelError::BadOperation { op: "/", .. }
2132        ));
2133        // rem
2134        assert_eq!(CelValue::cel_rem(9i32, 4i32).unwrap(), 1i32.conv());
2135        assert!(matches!(
2136            CelValue::cel_rem("a", 1i32).unwrap_err(),
2137            CelError::BadOperation { op: "%", .. }
2138        ));
2139    }
2140
2141    // helper to build a map CelValue from &[(K, V)]
2142    fn as_map(pairs: &[(i32, i32)]) -> CelValue<'static> {
2143        let items: Vec<_> = pairs.iter().map(|&(k, v)| (k.conv(), v.conv())).collect();
2144        CelValue::Map(Arc::from(items))
2145    }
2146
2147    #[test]
2148    fn celvalue_neq() {
2149        assert!(CelValue::cel_neq(1i32, 2i32).unwrap());
2150        assert!(!CelValue::cel_neq("foo", "foo").unwrap());
2151    }
2152
2153    #[test]
2154    fn celvalue_in_and_contains_ints() {
2155        let list = [1, 2, 3].conv();
2156        assert!(CelValue::cel_in(2i32, &list).unwrap());
2157        assert!(!CelValue::cel_in(4i32, &list).unwrap());
2158
2159        let map = as_map(&[(10, 100), (20, 200)]);
2160        assert!(CelValue::cel_in(10i32, &map).unwrap());
2161        assert!(!CelValue::cel_in(30i32, &map).unwrap());
2162
2163        // contains flips in
2164        assert!(CelValue::cel_contains(&list, 3i32).unwrap());
2165        assert!(!CelValue::cel_contains(&map, 30i32).unwrap());
2166    }
2167
2168    #[test]
2169    fn celvalue_contains_bad_operation() {
2170        let err = CelValue::cel_contains(1i32, "foo").unwrap_err();
2171        if let CelError::BadOperation { left, right, op } = err {
2172            assert_eq!(op, "contains");
2173            assert_eq!(left, 1i32.conv());
2174            assert_eq!(right, "foo".conv());
2175        } else {
2176            panic!("expected CelError::BadOperation with op=\"contains\"");
2177        }
2178    }
2179
2180    #[test]
2181    fn celvalue_in_and_contains_bytes() {
2182        let s = "hello world";
2183        let b = Bytes::from_static(b"hello world");
2184        let b_again = Bytes::from_static(b"hello world");
2185
2186        // substring
2187        assert!(CelValue::cel_in("world", s).unwrap());
2188        assert!(CelValue::cel_in(Bytes::from_static(b"wor"), b).unwrap());
2189
2190        // contains
2191        assert!(CelValue::cel_contains(s, "lo wo").unwrap());
2192        assert!(CelValue::cel_contains(b_again, Bytes::from_static(b"lo")).unwrap());
2193
2194        // not found
2195        assert!(!CelValue::cel_in("abc", s).unwrap());
2196        assert!(!CelValue::cel_contains(s, "xyz").unwrap());
2197    }
2198
2199    #[test]
2200    fn celvalue_in_and_contains_bad_operations() {
2201        let err = CelValue::cel_in(1i32, "foo").unwrap_err();
2202        match err {
2203            CelError::BadOperation { op, .. } => assert_eq!(op, "in"),
2204            _ => panic!("Expected BadOperation"),
2205        }
2206
2207        let err2 = CelValue::cel_contains(1i32, "foo").unwrap_err();
2208        match err2 {
2209            CelError::BadOperation { op, .. } => assert_eq!(op, "contains"),
2210            _ => panic!("Expected BadOperation contains"),
2211        }
2212    }
2213
2214    #[test]
2215    fn celvalue_starts_with_and_ends_with() {
2216        // starts_with & ends_with string
2217        assert!(CelValue::cel_starts_with("rustacean", "rust").unwrap());
2218        assert!(CelValue::cel_ends_with("rustacean", "acean").unwrap());
2219
2220        // bytes
2221        let b = Bytes::from_static(b"0123456");
2222        let b_again = Bytes::from_static(b"0123456");
2223        assert!(CelValue::cel_starts_with(b, Bytes::from_static(b"01")).unwrap());
2224        assert!(CelValue::cel_ends_with(b_again, Bytes::from_static(b"56")).unwrap());
2225
2226        // type errors
2227        let e1 = CelValue::cel_starts_with(123i32, "1").unwrap_err();
2228        assert!(matches!(e1, CelError::BadOperation { op, .. } if op=="startsWith"));
2229        let e2 = CelValue::cel_ends_with(123i32, "1").unwrap_err();
2230        assert!(matches!(e2, CelError::BadOperation { op, .. } if op=="startsWith"));
2231    }
2232
2233    #[test]
2234    fn celvalue_matches() {
2235        let re = Regex::new(r"^a.*z$").unwrap();
2236        assert!(CelValue::cel_matches("abcz", &re).unwrap());
2237
2238        let b = Bytes::from_static(b"abcz");
2239        assert!(CelValue::cel_matches(b, &re).unwrap());
2240
2241        // non-utf8 bytes -> Ok(false)
2242        let bad = CelValue::cel_matches(
2243            Bytes::from_static(&[0xff, 0xfe]),
2244            &Regex::new(".*").unwrap(),
2245        )
2246        .unwrap();
2247        assert!(!bad);
2248
2249        let err = CelValue::cel_matches(1i32, &re).unwrap_err();
2250        assert!(matches!(err, CelError::BadUnaryOperation { op, .. } if op=="matches"));
2251    }
2252
2253    #[test]
2254    fn celvalue_ip_and_uuid_hostname_uri_email() {
2255        // IPv4
2256        assert!(CelValue::cel_is_ipv4("127.0.0.1").unwrap());
2257        assert!(CelValue::cel_is_ipv4(Bytes::from_static(&[127, 0, 0, 1])).unwrap());
2258        assert!(!CelValue::cel_is_ipv4(Bytes::from_static(b"notip")).unwrap());
2259        assert!(matches!(
2260            CelValue::cel_is_ipv4(true).unwrap_err(),
2261            CelError::BadUnaryOperation { op, .. } if op == "isIpv4"
2262        ));
2263
2264        // IPv6
2265        assert!(CelValue::cel_is_ipv6("::1").unwrap());
2266        let octets = [0u8; 16];
2267        assert!(CelValue::cel_is_ipv6(&octets).unwrap());
2268        assert!(!CelValue::cel_is_ipv6(Bytes::from_static(b"bad")).unwrap());
2269        assert!(matches!(
2270            CelValue::cel_is_ipv6(1i32).unwrap_err(),
2271            CelError::BadUnaryOperation { op, .. } if op == "isIpv6"
2272        ));
2273
2274        // UUID
2275        let uuid_str_nil = Uuid::nil().to_string();
2276        assert!(CelValue::cel_is_uuid(&uuid_str_nil).unwrap());
2277        let uuid_str_max = Uuid::max().to_string();
2278        assert!(CelValue::cel_is_uuid(&uuid_str_max).unwrap());
2279
2280        let mut bytes16 = [0u8; 16];
2281        bytes16[0] = 1;
2282        assert!(CelValue::cel_is_uuid(&bytes16).unwrap());
2283        assert!(!CelValue::cel_is_uuid(Bytes::from_static(b"short")).unwrap());
2284        assert!(matches!(
2285            CelValue::cel_is_uuid(1i32).unwrap_err(),
2286            CelError::BadUnaryOperation { op, .. } if op == "isUuid"
2287        ));
2288
2289        // hostname
2290        assert!(CelValue::cel_is_hostname("example.com").unwrap());
2291        assert!(!CelValue::cel_is_hostname("not valid!").unwrap());
2292        assert!(matches!(
2293            CelValue::cel_is_hostname(1i32).unwrap_err(),
2294            CelError::BadUnaryOperation { op, .. } if op == "isHostname"
2295        ));
2296
2297        // URI str
2298        assert!(CelValue::cel_is_uri("https://rust-lang.org").unwrap());
2299        assert!(!CelValue::cel_is_uri(Bytes::from_static(b":bad")).unwrap());
2300        assert!(matches!(
2301            CelValue::cel_is_uri(1i32).unwrap_err(),
2302            CelError::BadUnaryOperation { op, .. } if op == "isUri"
2303        ));
2304
2305        // email str
2306        assert!(CelValue::cel_is_email("user@example.com").unwrap());
2307        assert!(!CelValue::cel_is_email(Bytes::from_static(b"noatsign")).unwrap());
2308        assert!(matches!(
2309            CelValue::cel_is_email(1i32).unwrap_err(),
2310            CelError::BadUnaryOperation { op, .. } if op == "isEmail"
2311        ));
2312    }
2313
2314    #[test]
2315    fn celvalue_ipv4_invalid() {
2316        let invalid = Bytes::from_static(&[0xff, 0xfe, 0xff, 0xff, 0xff]);
2317        let result = CelValue::cel_is_ipv4(invalid).unwrap();
2318        assert!(!result, "Expected false for non-UTF8, non-4-byte input");
2319    }
2320
2321    #[test]
2322    fn celvalue_ipv6_invalid() {
2323        let invalid = Bytes::from_static(&[0xff, 0xfe, 0xff]);
2324        let result = CelValue::cel_is_ipv6(invalid).unwrap();
2325        assert!(!result, "Expected false for non-UTF8, non-16-byte input");
2326    }
2327
2328    #[test]
2329    fn celvalue_uuid_invalid() {
2330        // length != 16 and invalid UTF-8 → should hit the final `Ok(false)` branch
2331        let invalid = Bytes::from_static(&[0xff, 0xfe, 0xff]);
2332        let result = CelValue::cel_is_uuid(invalid).unwrap();
2333        assert!(!result, "Expected false for non-UTF8, non-16-byte input");
2334    }
2335
2336    #[test]
2337    fn celvalue_hostname_invalid() {
2338        let valid = CelValue::cel_is_hostname(Bytes::from_static(b"example.com")).unwrap();
2339        assert!(valid, "Expected true for valid hostname bytes");
2340
2341        let invalid = CelValue::cel_is_hostname(Bytes::from_static(&[0xff, 0xfe, 0xff])).unwrap();
2342        assert!(!invalid, "Expected false for invalid UTF-8 bytes");
2343    }
2344
2345    #[test]
2346    fn celvalue_uri_invalid() {
2347        let invalid = Bytes::from_static(&[0xff, 0xfe, 0xff]);
2348        let result = CelValue::cel_is_uri(invalid).unwrap();
2349        assert!(!result, "Expected false for invalid UTF-8 uri bytes");
2350    }
2351
2352    #[test]
2353    fn celvalue_email_invalid() {
2354        let invalid = Bytes::from_static(&[0xff, 0xfe, 0xff]);
2355        let result = CelValue::cel_is_email(invalid).unwrap();
2356        assert!(!result, "Expected false for invalid UTF-8 email bytes");
2357    }
2358
2359    #[test]
2360    fn celvalue_is_nan() {
2361        assert!(
2362            !CelValue::cel_is_nan(NumberTy::from(2.0)).unwrap(),
2363            "Expected false for valid number"
2364        );
2365        assert!(
2366            !CelValue::cel_is_nan(NumberTy::from(5)).unwrap(),
2367            "Expected false for valid number"
2368        );
2369        assert!(
2370            !CelValue::cel_is_nan(NumberTy::from(13u64)).unwrap(),
2371            "Expected false for valid number"
2372        );
2373        assert!(
2374            !CelValue::cel_is_nan(NumberTy::from(f64::INFINITY)).unwrap(),
2375            "Expected false for infinity"
2376        );
2377        assert!(
2378            !CelValue::cel_is_nan(NumberTy::from(f64::NEG_INFINITY)).unwrap(),
2379            "Expected false for neg infinity"
2380        );
2381        assert!(
2382            CelValue::cel_is_nan(NumberTy::from(f64::NAN)).unwrap(),
2383            "Expected true for nan"
2384        );
2385        assert!(matches!(
2386            CelValue::cel_is_nan("str").unwrap_err(),
2387            CelError::BadUnaryOperation { op, .. } if op == "isNaN"
2388        ));
2389    }
2390
2391    #[test]
2392    fn celvalue_is_inf() {
2393        assert!(
2394            !CelValue::cel_is_inf(NumberTy::from(2.0)).unwrap(),
2395            "Expected false for valid number"
2396        );
2397        assert!(
2398            !CelValue::cel_is_inf(NumberTy::from(5)).unwrap(),
2399            "Expected false for valid number"
2400        );
2401        assert!(
2402            !CelValue::cel_is_nan(NumberTy::from(13u64)).unwrap(),
2403            "Expected false for valid number"
2404        );
2405        assert!(
2406            CelValue::cel_is_inf(NumberTy::from(f64::INFINITY)).unwrap(),
2407            "Expected true for infinity"
2408        );
2409        assert!(
2410            CelValue::cel_is_inf(NumberTy::from(f64::NEG_INFINITY)).unwrap(),
2411            "Expected true for neg infinity"
2412        );
2413        assert!(
2414            !CelValue::cel_is_inf(NumberTy::from(f64::NAN)).unwrap(),
2415            "Expected false for nan"
2416        );
2417        assert!(matches!(
2418            CelValue::cel_is_inf("str").unwrap_err(),
2419            CelError::BadUnaryOperation { op, .. } if op == "isInf"
2420        ));
2421    }
2422
2423    #[test]
2424    fn celvalue_size() {
2425        assert_eq!(CelValue::cel_size(Bytes::from_static(b"abc")).unwrap(), 3);
2426        assert_eq!(CelValue::cel_size("hello").unwrap(), 5);
2427        assert_eq!(CelValue::cel_size([1, 2, 3].conv()).unwrap(), 3);
2428        assert_eq!(CelValue::cel_size(as_map(&[(1, 1), (2, 2)])).unwrap(), 2);
2429
2430        let err = CelValue::cel_size(123i32).unwrap_err();
2431        assert!(matches!(err, CelError::BadUnaryOperation { op, .. } if op=="size"));
2432    }
2433
2434    #[test]
2435    fn celvalue_map_and_filter() {
2436        // map: double each number
2437        let m = CelValue::cel_map([1, 2, 3].conv(), |v| {
2438            let n = v.as_number().unwrap().to_i64().unwrap();
2439            Ok((n * 2).conv())
2440        })
2441        .unwrap();
2442        assert_eq!(m, [2, 4, 6].conv());
2443
2444        // map over map produces list of keys
2445        let keys = CelValue::cel_map(as_map(&[(10, 100), (20, 200)]), Ok).unwrap();
2446        assert_eq!(keys, [10, 20].conv());
2447
2448        // filter: keep evens
2449        let f = CelValue::cel_filter([1, 2, 3, 4].conv(), |v| {
2450            Ok(v.as_number().unwrap().to_i64().unwrap() % 2 == 0)
2451        })
2452        .unwrap();
2453        assert_eq!(f, [2, 4].conv());
2454
2455        // filter on map => list of keys
2456        let fk = CelValue::cel_filter(as_map(&[(7, 70), (8, 80)]), |v| {
2457            Ok(v.as_number().unwrap().to_i64().unwrap() == 8)
2458        })
2459        .unwrap();
2460        assert_eq!(fk, [8].conv());
2461
2462        // error on wrong type
2463        let err_map = CelValue::cel_map(1i32, |_| Ok(1i32.conv())).unwrap_err();
2464        assert!(matches!(err_map, CelError::BadUnaryOperation { op, .. } if op=="map"));
2465        let err_filter = CelValue::cel_filter(1i32, |_| Ok(true)).unwrap_err();
2466        assert!(matches!(err_filter, CelError::BadUnaryOperation { op, .. } if op=="filter"));
2467    }
2468
2469    #[test]
2470    fn celvalue_list_and_filter() {
2471        let list = [1i32, 2, 3].conv();
2472
2473        let err = CelValue::cel_filter(list, |v| {
2474            if v == 2i32.conv() {
2475                Err(CelError::BadUnaryOperation {
2476                    op: "test",
2477                    value: v,
2478                })
2479            } else {
2480                Ok(true)
2481            }
2482        })
2483        .unwrap_err();
2484
2485        if let CelError::BadUnaryOperation { op, value } = err {
2486            assert_eq!(op, "test");
2487            assert_eq!(value, 2i32.conv());
2488        } else {
2489            panic!("expected BadUnaryOperation from map_fn");
2490        }
2491    }
2492
2493    #[test]
2494    fn celvalue_list_and_map_all() {
2495        let list = [1, 2, 3].conv();
2496        let all_pos = CelValue::cel_all(list.clone(), |v| {
2497            Ok(v.as_number().unwrap().to_i64().unwrap() > 0)
2498        })
2499        .unwrap();
2500        assert!(all_pos);
2501
2502        let list2 = [1, 0, 3].conv();
2503        let any_zero =
2504            CelValue::cel_all(list2, |v| Ok(v.as_number().unwrap().to_i64().unwrap() > 0)).unwrap();
2505        assert!(!any_zero);
2506
2507        let map = as_map(&[(2, 20), (4, 40)]);
2508        let all_keys = CelValue::cel_all(map.clone(), |v| {
2509            Ok(v.as_number().unwrap().to_i64().unwrap() < 5)
2510        })
2511        .unwrap();
2512        assert!(all_keys);
2513
2514        let map2 = as_map(&[(2, 20), (6, 60)]);
2515        let some_ge5 =
2516            CelValue::cel_all(map2, |v| Ok(v.as_number().unwrap().to_i64().unwrap() < 5)).unwrap();
2517        assert!(!some_ge5);
2518    }
2519
2520    #[test]
2521    fn celvalue_list_error_propagation() {
2522        let list = [1, 2, 3].conv();
2523        let err = CelValue::cel_all(list, |v| {
2524            if v == 2i32.conv() {
2525                Err(CelError::BadUnaryOperation {
2526                    op: "all_test",
2527                    value: v,
2528                })
2529            } else {
2530                Ok(true)
2531            }
2532        })
2533        .unwrap_err();
2534
2535        if let CelError::BadUnaryOperation { op, value } = err {
2536            assert_eq!(op, "all_test");
2537            assert_eq!(value, 2i32.conv());
2538        } else {
2539            panic!("Expected BadUnaryOperation from map_fn");
2540        }
2541    }
2542
2543    #[test]
2544    fn celvalue_all_bad_operation() {
2545        let err = CelValue::cel_all(42i32, |_| Ok(true)).unwrap_err();
2546        if let CelError::BadUnaryOperation { op, value } = err {
2547            assert_eq!(op, "all");
2548            assert_eq!(value, 42i32.conv());
2549        } else {
2550            panic!("Expected BadUnaryOperation with op=\"all\"");
2551        }
2552    }
2553
2554    #[test]
2555    fn celvalue_exists() {
2556        let list = [1, 2, 3].conv();
2557        let result = CelValue::cel_exists(list, |v| Ok(v == 2i32.conv())).unwrap();
2558        assert!(result);
2559    }
2560
2561    #[test]
2562    fn celvalue_exists_list_false() {
2563        let list = [1, 2, 3].conv();
2564        let result = CelValue::cel_exists(list, |_| Ok(false)).unwrap();
2565        assert!(!result);
2566    }
2567
2568    #[test]
2569    fn celvalue_exists_map_true() {
2570        let map = as_map(&[(10, 100), (20, 200)]);
2571        let result = CelValue::cel_exists(map, |v| Ok(v == 20i32.conv())).unwrap();
2572        assert!(result);
2573    }
2574
2575    #[test]
2576    fn celvalue_exists_map_false() {
2577        let map = as_map(&[(10, 100), (20, 200)]);
2578        let result = CelValue::cel_exists(map, |_| Ok(false)).unwrap();
2579        assert!(!result);
2580    }
2581
2582    #[test]
2583    fn celvalue_exists_list_propagates_error() {
2584        let list = [1, 2, 3].conv();
2585        let err = CelValue::cel_exists(list, |v| {
2586            if v == 2i32.conv() {
2587                Err(CelError::BadUnaryOperation {
2588                    op: "exists_test",
2589                    value: v,
2590                })
2591            } else {
2592                Ok(false)
2593            }
2594        })
2595        .unwrap_err();
2596
2597        if let CelError::BadUnaryOperation { op, value } = err {
2598            assert_eq!(op, "exists_test");
2599            assert_eq!(value, 2i32.conv());
2600        } else {
2601            panic!("Expected BadUnaryOperation from map_fn");
2602        }
2603    }
2604
2605    #[test]
2606    fn celvalue_exists_non_collection_error() {
2607        let err = CelValue::cel_exists(42i32, |_| Ok(true)).unwrap_err();
2608        if let CelError::BadUnaryOperation { op, value } = err {
2609            assert_eq!(op, "existsOne");
2610            assert_eq!(value, 42i32.conv());
2611        } else {
2612            panic!("Expected BadUnaryOperation with op=\"existsOne\"");
2613        }
2614    }
2615
2616    #[test]
2617    fn celvalue_exists_one_list() {
2618        let list = [1, 2, 3].conv();
2619        let result = CelValue::cel_exists_one(list, |v| Ok(v == 2i32.conv())).unwrap();
2620        assert!(result);
2621    }
2622
2623    #[test]
2624    fn celvalue_exists_one_list_zero() {
2625        let list = [1, 2, 3].conv();
2626        let result = CelValue::cel_exists_one(list, |_| Ok(false)).unwrap();
2627        assert!(!result);
2628    }
2629
2630    #[test]
2631    fn celvalue_exists_one_list_multiple() {
2632        let list = [1, 2, 2, 3].conv();
2633        let result = CelValue::cel_exists_one(list, |v| Ok(v == 2i32.conv())).unwrap();
2634        assert!(!result);
2635    }
2636
2637    #[test]
2638    fn celvalue_exists_one_map() {
2639        let map = as_map(&[(10, 100), (20, 200)]);
2640        let result = CelValue::cel_exists_one(map, |v| Ok(v == 20i32.conv())).unwrap();
2641        assert!(result);
2642    }
2643
2644    #[test]
2645    fn celvalue_exists_one_map_zero() {
2646        let map = as_map(&[(10, 100), (20, 200)]);
2647        let result = CelValue::cel_exists_one(map, |_| Ok(false)).unwrap();
2648        assert!(!result);
2649    }
2650
2651    #[test]
2652    fn celvalue_exists_one_map_multiple() {
2653        let map = as_map(&[(1, 10), (1, 20), (2, 30)]);
2654        let result = CelValue::cel_exists_one(map, |v| Ok(v == 1i32.conv())).unwrap();
2655        assert!(!result);
2656    }
2657
2658    #[test]
2659    fn celvalue_exists_one_propagates_error() {
2660        let list = [1, 2, 3].conv();
2661        let err = CelValue::cel_exists_one(list, |v| {
2662            if v == 2i32.conv() {
2663                Err(CelError::BadUnaryOperation {
2664                    op: "test_one",
2665                    value: v,
2666                })
2667            } else {
2668                Ok(false)
2669            }
2670        })
2671        .unwrap_err();
2672
2673        if let CelError::BadUnaryOperation { op, value } = err {
2674            assert_eq!(op, "test_one");
2675            assert_eq!(value, 2i32.conv());
2676        } else {
2677            panic!("Expected BadUnaryOperation from map_fn");
2678        }
2679    }
2680
2681    #[test]
2682    fn celvalue_exists_one_non_collection_error() {
2683        let err = CelValue::cel_exists_one(42i32, |_| Ok(true)).unwrap_err();
2684        if let CelError::BadUnaryOperation { op, value } = err {
2685            assert_eq!(op, "existsOne");
2686            assert_eq!(value, 42i32.conv());
2687        } else {
2688            panic!("Expected BadUnaryOperation with op=\"existsOne\"");
2689        }
2690    }
2691
2692    #[test]
2693    fn celvalue_to_string_variant_passthrough() {
2694        let original = "hello";
2695        let cv = original.conv();
2696        let out = CelValue::cel_to_string(cv.clone());
2697
2698        assert!(matches!(out, CelValue::String(_)));
2699        assert_eq!(out, cv);
2700    }
2701
2702    #[test]
2703    fn celvalue_to_string_owned_bytes() {
2704        let bytes = Bytes::from_static(b"foo");
2705        let out = CelValue::cel_to_string(bytes.clone());
2706
2707        assert_eq!(out, CelValue::String(CelString::Owned(Arc::from("foo"))));
2708    }
2709
2710    #[test]
2711    fn celvalue_to_string_borrowed_bytes() {
2712        let slice: &[u8] = b"bar";
2713        let out = CelValue::cel_to_string(slice);
2714
2715        match out {
2716            CelValue::String(CelString::Borrowed(s)) => assert_eq!(s, "bar"),
2717            _ => panic!("expected Borrowed variant"),
2718        }
2719    }
2720
2721    #[test]
2722    fn celvalue_to_string_borrowed_bytes_invalid_utf8_to_owned() {
2723        let slice: &[u8] = &[0xff, 0xfe];
2724        let out = CelValue::cel_to_string(slice);
2725
2726        match out {
2727            CelValue::String(CelString::Owned(o)) => {
2728                assert_eq!(o.as_ref(), "\u{FFFD}\u{FFFD}");
2729            }
2730            _ => panic!("expected Owned variant"),
2731        }
2732    }
2733
2734    #[test]
2735    fn celvalue_to_string_num_and_bool() {
2736        let out_num = CelValue::cel_to_string(42i32);
2737        assert_eq!(out_num, CelValue::String(CelString::Owned(Arc::from("42"))));
2738
2739        let out_bool = CelValue::cel_to_string(true);
2740        assert_eq!(
2741            out_bool,
2742            CelValue::String(CelString::Owned(Arc::from("true")))
2743        );
2744    }
2745
2746    #[test]
2747    fn celvalue_to_bytes_variant_passthrough() {
2748        let bytes = Bytes::from_static(b"xyz");
2749        let cv = CelValue::cel_to_bytes(bytes.clone()).unwrap();
2750        match cv {
2751            CelValue::Bytes(CelBytes::Owned(b)) => assert_eq!(b, bytes),
2752            _ => panic!("expected Owned bytes passthrough"),
2753        }
2754    }
2755
2756    #[test]
2757    fn celvalue_to_bytes_from_owned_string() {
2758        let owned_str = CelString::Owned(Arc::from("hello"));
2759        let cv_in = CelValue::String(owned_str.clone());
2760        let cv = CelValue::cel_to_bytes(cv_in).unwrap();
2761        match cv {
2762            CelValue::Bytes(CelBytes::Owned(b)) => {
2763                assert_eq!(b.as_ref(), b"hello");
2764            }
2765            _ => panic!("expected Owned bytes from Owned string"),
2766        }
2767    }
2768
2769    #[test]
2770    fn celvalue_to_bytes_from_borrowed_string() {
2771        let s = "world";
2772        let cv = CelValue::cel_to_bytes(s).unwrap();
2773        match cv {
2774            CelValue::Bytes(CelBytes::Borrowed(b)) => {
2775                assert_eq!(b, b"world");
2776            }
2777            _ => panic!("expected Borrowed bytes from Borrowed string"),
2778        }
2779    }
2780
2781    #[test]
2782    fn celvalue_error_on_non_string_bytes() {
2783        let err = CelValue::cel_to_bytes(123i32).unwrap_err();
2784        if let CelError::BadUnaryOperation { op, value } = err {
2785            assert_eq!(op, "bytes");
2786            assert_eq!(value, 123i32.conv());
2787        } else {
2788            panic!("expected BadUnaryOperation for non-bytes/string");
2789        }
2790    }
2791
2792    #[test]
2793    fn celvalue_to_int_from_string() {
2794        let result = CelValue::cel_to_int("123").unwrap();
2795        assert_eq!(result, CelValue::Number(NumberTy::I64(123)));
2796    }
2797
2798    #[test]
2799    fn celvalue_to_int_from_nan() {
2800        let result = CelValue::cel_to_int("not_a_number").unwrap();
2801        assert_eq!(result, CelValue::Null);
2802    }
2803
2804    #[test]
2805    fn celvalue_to_int_from_float() {
2806        let result = CelValue::cel_to_int(3.99f64).unwrap();
2807        assert_eq!(result, CelValue::Number(NumberTy::I64(3)));
2808    }
2809
2810    #[test]
2811    fn celvalue_to_int_too_large() {
2812        let large = u64::MAX.conv();
2813        let result = CelValue::cel_to_int(large).unwrap();
2814        assert_eq!(result, CelValue::Null);
2815    }
2816
2817    #[test]
2818    fn celvalue_to_int_from_bytes_bad_operation() {
2819        let err = CelValue::cel_to_int(&[1, 2, 3][..]).unwrap_err();
2820        if let CelError::BadUnaryOperation { op, value } = err {
2821            assert_eq!(op, "int");
2822            assert_eq!(value, (&[1, 2, 3][..]).conv());
2823        } else {
2824            panic!("Expected BadUnaryOperation for non-string/number");
2825        }
2826    }
2827
2828    #[test]
2829    fn celvalue_to_uint_from_string() {
2830        let result = CelValue::cel_to_uint("456").unwrap();
2831        assert_eq!(result, CelValue::Number(NumberTy::U64(456)));
2832    }
2833
2834    #[test]
2835    fn celvalue_to_uint_from_nan() {
2836        let result = CelValue::cel_to_uint("not_uint").unwrap();
2837        assert_eq!(result, CelValue::Null);
2838    }
2839
2840    #[test]
2841    fn celvalue_to_uint_from_int_float_uint() {
2842        let result_i = CelValue::cel_to_uint(42i32).unwrap();
2843        assert_eq!(result_i, CelValue::Number(NumberTy::U64(42)));
2844
2845        let result_f = CelValue::cel_to_uint(3.7f64).unwrap();
2846        assert_eq!(result_f, CelValue::Number(NumberTy::U64(3)));
2847
2848        let result_u = CelValue::cel_to_uint(100u64).unwrap();
2849        assert_eq!(result_u, CelValue::Number(NumberTy::U64(100)));
2850    }
2851
2852    #[test]
2853    fn celvalue_to_uint_neg_and_too_large() {
2854        let result_neg = CelValue::cel_to_uint(-5i32).unwrap();
2855        assert_eq!(result_neg, CelValue::Null);
2856
2857        let big = f64::INFINITY;
2858        let result_inf = CelValue::cel_to_uint(big).unwrap();
2859        assert_eq!(result_inf, CelValue::Null);
2860    }
2861
2862    #[test]
2863    fn celvalue_to_uint_from_bytes_bad_operation() {
2864        let err = CelValue::cel_to_uint(&[1, 2, 3][..]).unwrap_err();
2865        if let CelError::BadUnaryOperation { op, value } = err {
2866            assert_eq!(op, "uint");
2867            assert_eq!(value, (&[1, 2, 3][..]).conv());
2868        } else {
2869            panic!("Expected BadUnaryOperation for non-string/number");
2870        }
2871    }
2872
2873    #[test]
2874    fn celvalue_to_double_from_string_valid() {
2875        let result = CelValue::cel_to_double("3.141592653589793").unwrap();
2876        assert_eq!(
2877            result,
2878            CelValue::Number(NumberTy::F64(std::f64::consts::PI))
2879        );
2880    }
2881
2882    #[test]
2883    fn celvalue_to_double_from_string_invalid_returns_null() {
2884        let result = CelValue::cel_to_double("not_a_double").unwrap();
2885        assert_eq!(result, CelValue::Null);
2886    }
2887
2888    #[test]
2889    fn celvalue_to_double_from_integer_number() {
2890        let result = CelValue::cel_to_double(42i32).unwrap();
2891        assert_eq!(result, CelValue::Number(NumberTy::F64(42.0)));
2892    }
2893
2894    #[test]
2895    fn celvalue_to_double_from_f64_number() {
2896        let result = CelValue::cel_to_double(std::f64::consts::PI).unwrap();
2897        assert_eq!(
2898            result,
2899            CelValue::Number(NumberTy::F64(std::f64::consts::PI))
2900        );
2901    }
2902
2903    #[test]
2904    fn celvalue_to_double_from_nan() {
2905        let err = CelValue::cel_to_double(&[1, 2, 3][..]).unwrap_err();
2906        if let CelError::BadUnaryOperation { op, value } = err {
2907            assert_eq!(op, "double");
2908            assert_eq!(value, (&[1, 2, 3][..]).conv());
2909        } else {
2910            panic!("Expected BadUnaryOperation for non-string/number");
2911        }
2912    }
2913
2914    #[test]
2915    fn celvalue_to_enum_from_number_and_string() {
2916        let v = CelValue::cel_to_enum(10i32, "MyEnum").unwrap();
2917        assert_eq!(v, CelValue::Enum(CelEnum::new("MyEnum".into(), 10)));
2918    }
2919
2920    #[test]
2921    fn celvalue_to_enum_number_out_of_range() {
2922        let overflow = i32::MAX as i64 + 1;
2923        let v = CelValue::cel_to_enum(overflow, "Tag").unwrap();
2924        assert_eq!(v, CelValue::Null);
2925    }
2926
2927    #[test]
2928    fn celvalue_to_enum_from_enum_and_string() {
2929        let original = CelValue::Enum(CelEnum::new("Orig".into(), 42));
2930        let v = CelValue::cel_to_enum(original.clone(), "NewTag").unwrap();
2931        assert_eq!(v, CelValue::Enum(CelEnum::new("NewTag".into(), 42)));
2932    }
2933
2934    #[test]
2935    fn celvalue_to_enum_bad_operation_for_invalid_inputs() {
2936        let err = CelValue::cel_to_enum(true, 123i32).unwrap_err();
2937        if let CelError::BadOperation { op, left, right } = err {
2938            assert_eq!(op, "enum");
2939            assert_eq!(left, true.conv());
2940            assert_eq!(right, 123i32.conv());
2941        } else {
2942            panic!("Expected BadOperation for invalid cel_to_enum inputs");
2943        }
2944    }
2945
2946    #[test]
2947    fn celvalue_eq_bool_variants() {
2948        assert_eq!(CelValue::Bool(true), CelValue::Bool(true));
2949        assert_ne!(CelValue::Bool(true), CelValue::Bool(false));
2950    }
2951
2952    #[test]
2953    fn celvalue_eq_string_and_bytes_variants() {
2954        let s1 = "abc".conv();
2955        let s2 = "abc".conv();
2956        let b1 = Bytes::from_static(b"abc").conv();
2957        let b2 = Bytes::from_static(b"abc").conv();
2958        assert_eq!(s1, s2);
2959        assert_eq!(b1, b2);
2960
2961        assert_eq!(s1.clone(), b1.clone());
2962        assert_eq!(b1, s2);
2963    }
2964
2965    #[test]
2966    fn celvalue_eq_duration_and_number() {
2967        let dur = CelValue::Duration(chrono::Duration::seconds(5));
2968        let num = 5i32.conv();
2969
2970        assert_eq!(dur.clone(), num.clone());
2971        assert_eq!(num, dur);
2972    }
2973
2974    #[test]
2975    fn celvalue_eq_duration_variants() {
2976        use chrono::Duration;
2977
2978        let d1 = CelValue::Duration(Duration::seconds(42));
2979        let d2 = CelValue::Duration(Duration::seconds(42));
2980        let d3 = CelValue::Duration(Duration::seconds(43));
2981
2982        assert_eq!(d1, d2, "Two identical Durations should be equal");
2983        assert_ne!(d1, d3, "Different Durations should not be equal");
2984    }
2985
2986    #[test]
2987    fn celvalue_eq_timestamp_variants() {
2988        use chrono::{DateTime, FixedOffset};
2989
2990        let dt1: DateTime<FixedOffset> =
2991            DateTime::parse_from_rfc3339("2021-01-01T12:00:00+00:00").unwrap();
2992        let dt2: DateTime<FixedOffset> =
2993            DateTime::parse_from_rfc3339("2021-01-01T12:00:00+00:00").unwrap();
2994
2995        let t1 = CelValue::Timestamp(dt1);
2996        let t2 = CelValue::Timestamp(dt2);
2997        assert_eq!(t1, t2);
2998    }
2999
3000    #[test]
3001    fn celvalue_eq_enum_and_number_variants() {
3002        let e = CelValue::Enum(CelEnum::new("Tag".into(), 42));
3003        let n = 42i32.conv();
3004
3005        assert_eq!(e.clone(), n.clone());
3006        assert_eq!(n, e);
3007    }
3008
3009    #[test]
3010    fn celvalue_eq_list_and_map_variants() {
3011        let list1 = (&[1, 2, 3][..]).conv();
3012        let list2 = (&[1, 2, 3][..]).conv();
3013        assert_eq!(list1, list2);
3014
3015        let map1 = CelValue::Map(Arc::from(vec![
3016            (1i32.conv(), 10i32.conv()),
3017            (2i32.conv(), 20i32.conv()),
3018        ]));
3019        let map2 = CelValue::Map(Arc::from(vec![
3020            (1i32.conv(), 10i32.conv()),
3021            (2i32.conv(), 20i32.conv()),
3022        ]));
3023        assert_eq!(map1, map2);
3024    }
3025
3026    #[test]
3027    fn celvalue_eq_number_and_null_variants() {
3028        assert_eq!(1i32.conv(), 1i32.conv());
3029        assert_ne!(1i32.conv(), 2i32.conv());
3030        assert_eq!(CelValue::Null, CelValue::Null);
3031    }
3032
3033    #[test]
3034    fn celvalue_eq_mismatched_variants() {
3035        assert_ne!(CelValue::Bool(true), 1i32.conv());
3036        assert_ne!(
3037            CelValue::List(Arc::from(vec![].into_boxed_slice())),
3038            CelValue::Map(Arc::from(vec![].into_boxed_slice()))
3039        );
3040    }
3041
3042    #[test]
3043    fn celvalue_conv_unit_conv() {
3044        let v: CelValue = ().conv();
3045        assert_eq!(v, CelValue::Null);
3046    }
3047
3048    #[test]
3049    fn celvalue_display() {
3050        let ts: DateTime<FixedOffset> =
3051            DateTime::parse_from_rfc3339("2025-05-04T00:00:00+00:00").unwrap();
3052
3053        // Build a simple map: {1: "x", 2: "y"}
3054        let map_val = CelValue::Map(Arc::from(vec![
3055            (1i32.conv(), "x".conv()),
3056            (2i32.conv(), "y".conv()),
3057        ]));
3058
3059        let outputs = [
3060            format!("{}", CelValue::Bool(false)),
3061            format!("{}", 42i32.conv()),
3062            format!("{}", "foo".conv()),
3063            format!("{}", Bytes::from_static(b"bar").conv()),
3064            format!("{}", (&[1, 2, 3][..]).conv()),
3065            format!("{}", CelValue::Null),
3066            format!("{}", CelValue::Duration(Duration::seconds(5))),
3067            format!("{}", CelValue::Timestamp(ts)),
3068            format!("{}", map_val),
3069        ]
3070        .join("\n");
3071
3072        insta::assert_snapshot!(outputs, @r###"
3073        false
3074        42
3075        foo
3076        [98, 97, 114]
3077        [1, 2, 3]
3078        null
3079        PT5S
3080        2025-05-04 00:00:00 +00:00
3081        {1: x, 2: y}
3082        "###);
3083    }
3084
3085    #[cfg(feature = "runtime")]
3086    #[test]
3087    fn celvalue_display_enum_runtime() {
3088        use crate::CelMode;
3089
3090        CelMode::set(CelMode::Proto);
3091
3092        let enum_val = CelValue::Enum(CelEnum::new(CelString::Owned("MyTag".into()), 123));
3093        assert_eq!(format!("{enum_val}"), "123");
3094
3095        CelMode::set(CelMode::Serde);
3096        let enum_val_json = CelValue::Enum(CelEnum::new(CelString::Owned("MyTag".into()), 456));
3097        assert_eq!(format!("{enum_val_json}"), "456");
3098    }
3099
3100    #[test]
3101    fn celvalue_to_bool_all_variants() {
3102        // Bool
3103        assert!(CelValue::Bool(true).to_bool());
3104        assert!(!CelValue::Bool(false).to_bool());
3105
3106        // Number
3107        assert!(42i32.conv().to_bool());
3108        assert!(!0i32.conv().to_bool());
3109
3110        // String
3111        assert!(CelValue::String(CelString::Borrowed("hello")).to_bool());
3112        assert!(!CelValue::String(CelString::Borrowed("")).to_bool());
3113
3114        // Bytes
3115        assert!(Bytes::from_static(b"x").conv().to_bool());
3116        assert!(!Bytes::from_static(b"").conv().to_bool());
3117
3118        // List
3119        let non_empty_list = (&[1, 2, 3][..]).conv();
3120        assert!(non_empty_list.to_bool());
3121        let empty_list = CelValue::List(Arc::from(Vec::<CelValue>::new().into_boxed_slice()));
3122        assert!(!empty_list.to_bool());
3123
3124        // Map
3125        let non_empty_map = CelValue::Map(Arc::from(vec![(1i32.conv(), 2i32.conv())]));
3126        assert!(non_empty_map.to_bool());
3127        let empty_map = CelValue::Map(Arc::from(
3128            Vec::<(CelValue, CelValue)>::new().into_boxed_slice(),
3129        ));
3130        assert!(!empty_map.to_bool());
3131
3132        // Null
3133        assert!(!CelValue::Null.to_bool());
3134
3135        // Duration
3136        assert!(CelValue::Duration(Duration::seconds(5)).to_bool());
3137        assert!(!CelValue::Duration(Duration::zero()).to_bool());
3138
3139        // Timestamp
3140        let epoch: DateTime<FixedOffset> =
3141            DateTime::parse_from_rfc3339("1970-01-01T00:00:00+00:00").unwrap();
3142        assert!(!CelValue::Timestamp(epoch).to_bool());
3143        let later: DateTime<FixedOffset> =
3144            DateTime::parse_from_rfc3339("2025-05-04T00:00:00+00:00").unwrap();
3145        assert!(CelValue::Timestamp(later).to_bool());
3146    }
3147
3148    #[test]
3149    fn numberty_partial_cmp_i64_variants() {
3150        let a = NumberTy::I64(1);
3151        let b = NumberTy::I64(2);
3152        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
3153        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
3154        assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
3155    }
3156
3157    #[test]
3158    fn numberty_partial_cmp_u64_variants() {
3159        let a = NumberTy::U64(10);
3160        let b = NumberTy::U64(20);
3161        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
3162        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
3163        assert_eq!(b.partial_cmp(&b), Some(Ordering::Equal));
3164    }
3165
3166    #[test]
3167    fn numberty_partial_cmp_mixed_i64_u64() {
3168        let a = NumberTy::I64(3);
3169        let b = NumberTy::U64(4);
3170        // promoted to I64 comparison
3171        assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
3172        assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
3173
3174        let c = NumberTy::I64(5);
3175        let d = NumberTy::U64(5);
3176        assert_eq!(c.partial_cmp(&d), Some(Ordering::Equal));
3177    }
3178
3179    #[test]
3180    fn numberty_partial_cmp_f64_exact_and_order() {
3181        let x = NumberTy::F64(1.23);
3182        let y = NumberTy::F64(1.23);
3183        let z = NumberTy::F64(4.56);
3184
3185        assert_eq!(x.partial_cmp(&y), Some(Ordering::Equal));
3186        assert_eq!(x.partial_cmp(&z), Some(Ordering::Less));
3187        assert_eq!(z.partial_cmp(&x), Some(Ordering::Greater));
3188    }
3189
3190    #[test]
3191    fn numberty_partial_cmp_mixed_f64_and_integer() {
3192        let f = NumberTy::F64(2.0);
3193        let i = NumberTy::I64(2);
3194        // promoted to F64 and compared
3195        assert_eq!(f.partial_cmp(&i), Some(Ordering::Equal));
3196        assert_eq!(i.partial_cmp(&f), Some(Ordering::Equal));
3197    }
3198
3199    #[test]
3200    fn numberty_cel_add_i64_success() {
3201        let a = NumberTy::I64(5);
3202        let b = NumberTy::I64(7);
3203        assert_eq!(a.cel_add(b).unwrap(), NumberTy::I64(12));
3204    }
3205
3206    #[test]
3207    fn numberty_cel_add_i64_overflow_errors() {
3208        let a = NumberTy::I64(i64::MAX);
3209        let b = NumberTy::I64(1);
3210        let err = a.cel_add(b).unwrap_err();
3211        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="addition"));
3212    }
3213
3214    #[test]
3215    fn numberty_cel_add_u64_success() {
3216        let a = NumberTy::U64(10);
3217        let b = NumberTy::U64(20);
3218        assert_eq!(a.cel_add(b).unwrap(), NumberTy::U64(30));
3219    }
3220
3221    #[test]
3222    fn numberty_cel_add_f64_success() {
3223        let a = NumberTy::F64(1.5);
3224        let b = NumberTy::F64(2.25);
3225        assert_eq!(a.cel_add(b).unwrap(), NumberTy::F64(3.75));
3226    }
3227
3228    #[test]
3229    fn numberty_cel_sub_i64_underflow_errors() {
3230        let a = NumberTy::I64(i64::MIN);
3231        let b = NumberTy::I64(1);
3232        let err = a.cel_sub(b).unwrap_err();
3233        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="subtraction"));
3234    }
3235
3236    #[test]
3237    fn numberty_cel_sub_u64_underflow_errors() {
3238        let a = NumberTy::U64(0);
3239        let b = NumberTy::U64(1);
3240        let err = a.cel_sub(b).unwrap_err();
3241        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="subtraction"));
3242    }
3243
3244    #[test]
3245    fn numberty_cel_sub_f64_success() {
3246        let a = NumberTy::F64(5.5);
3247        let b = NumberTy::F64(2.25);
3248        assert_eq!(a.cel_sub(b).unwrap(), NumberTy::F64(3.25));
3249    }
3250
3251    #[test]
3252    fn numberty_cel_mul_i64_overflow_errors() {
3253        let a = NumberTy::I64(i64::MAX / 2 + 1);
3254        let b = NumberTy::I64(2);
3255        let err = a.cel_mul(b).unwrap_err();
3256        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="multiplication"));
3257    }
3258
3259    #[test]
3260    fn numberty_cel_mul_u64_overflow_errors() {
3261        let a = NumberTy::U64(u64::MAX / 2 + 1);
3262        let b = NumberTy::U64(2);
3263        let err = a.cel_mul(b).unwrap_err();
3264        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="multiplication"));
3265    }
3266
3267    #[test]
3268    fn numberty_cel_mul_f64_success() {
3269        let a = NumberTy::F64(3.0);
3270        let b = NumberTy::F64(2.5);
3271        assert_eq!(a.cel_mul(b).unwrap(), NumberTy::F64(7.5));
3272    }
3273
3274    #[test]
3275    fn numberty_cel_div_by_zero_errors() {
3276        let a = NumberTy::I64(10);
3277        let b = NumberTy::I64(0);
3278        let err = a.cel_div(b).unwrap_err();
3279        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="division by zero"));
3280    }
3281
3282    #[test]
3283    fn numberty_cel_div_i64_success() {
3284        let a = NumberTy::I64(10);
3285        let b = NumberTy::I64(2);
3286        assert_eq!(a.cel_div(b).unwrap(), NumberTy::I64(5));
3287    }
3288
3289    #[test]
3290    fn numberty_cel_div_u64_success() {
3291        let a = NumberTy::U64(20);
3292        let b = NumberTy::U64(5);
3293        assert_eq!(a.cel_div(b).unwrap(), NumberTy::U64(4));
3294    }
3295
3296    #[test]
3297    fn numberty_cel_div_f64_success() {
3298        let a = NumberTy::F64(9.0);
3299        let b = NumberTy::F64(2.0);
3300        assert_eq!(a.cel_div(b).unwrap(), NumberTy::F64(4.5));
3301    }
3302
3303    #[test]
3304    fn numberty_cel_rem_by_zero_errors() {
3305        let a = NumberTy::I64(10);
3306        let b = NumberTy::I64(0);
3307        let err = a.cel_rem(b).unwrap_err();
3308        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="remainder by zero"));
3309    }
3310
3311    #[test]
3312    fn numberty_cel_rem_i64_success() {
3313        let a = NumberTy::I64(10);
3314        let b = NumberTy::I64(3);
3315        assert_eq!(a.cel_rem(b).unwrap(), NumberTy::I64(1));
3316    }
3317
3318    #[test]
3319    fn numberty_cel_rem_u64_success() {
3320        let a = NumberTy::U64(10);
3321        let b = NumberTy::U64(3);
3322        assert_eq!(a.cel_rem(b).unwrap(), NumberTy::U64(1));
3323    }
3324
3325    #[test]
3326    fn numberty_cel_rem_f64_errors() {
3327        let a = NumberTy::F64(10.0);
3328        let b = NumberTy::F64(3.0);
3329        let err = a.cel_rem(b).unwrap_err();
3330        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="remainder"));
3331    }
3332
3333    #[test]
3334    fn numberty_cel_neg_i64_success() {
3335        let a = NumberTy::I64(5);
3336        assert_eq!(a.cel_neg().unwrap(), NumberTy::I64(-5));
3337    }
3338
3339    #[test]
3340    fn numberty_cel_neg_i64_overflow_errors() {
3341        let a = NumberTy::I64(i64::MIN);
3342        let err = a.cel_neg().unwrap_err();
3343        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="negation"));
3344    }
3345
3346    #[test]
3347    fn numberty_cel_neg_u64_success() {
3348        let a = NumberTy::U64(5);
3349        assert_eq!(a.cel_neg().unwrap(), NumberTy::I64(-5));
3350    }
3351
3352    #[test]
3353    fn numberty_cel_neg_u64_overflow_errors() {
3354        let a = NumberTy::U64(1 << 63); // too large for i64
3355        let err = a.cel_neg().unwrap_err();
3356        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="negation"));
3357    }
3358
3359    #[test]
3360    fn numberty_cel_neg_f64_success() {
3361        let a = NumberTy::F64(2.5);
3362        assert_eq!(a.cel_neg().unwrap(), NumberTy::F64(-2.5));
3363    }
3364
3365    #[test]
3366    fn numberty_to_int_success_and_error() {
3367        assert_eq!(NumberTy::I64(42).to_int().unwrap(), NumberTy::I64(42));
3368        let err = NumberTy::F64(f64::INFINITY).to_int().unwrap_err();
3369        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="int"));
3370    }
3371
3372    #[test]
3373    fn numberty_to_uint_success_and_error() {
3374        assert_eq!(NumberTy::I64(42).to_uint().unwrap(), NumberTy::U64(42));
3375        let err = NumberTy::I64(-1).to_uint().unwrap_err();
3376        assert!(matches!(err, CelError::NumberOutOfRange { op } if op=="int"));
3377    }
3378
3379    #[test]
3380    fn numberty_to_double_always_success() {
3381        assert_eq!(NumberTy::I64(3).to_double().unwrap(), NumberTy::F64(3.0));
3382        assert_eq!(NumberTy::U64(4).to_double().unwrap(), NumberTy::F64(4.0));
3383        assert_eq!(NumberTy::F64(2.5).to_double().unwrap(), NumberTy::F64(2.5));
3384    }
3385
3386    #[test]
3387    fn numberty_from_u32_creates_u64_variant() {
3388        let input: u32 = 123;
3389        let nt: NumberTy = input.into();
3390        assert_eq!(nt, NumberTy::U64(123));
3391    }
3392
3393    #[test]
3394    fn numberty_from_i64_creates_i64_variant() {
3395        let input: i64 = -42;
3396        let nt: NumberTy = input.into();
3397        assert_eq!(nt, NumberTy::I64(-42));
3398    }
3399
3400    #[test]
3401    fn numberty_from_u64_creates_u64_variant() {
3402        let input: u64 = 9876543210;
3403        let nt: NumberTy = input.into();
3404        assert_eq!(nt, NumberTy::U64(9876543210));
3405    }
3406
3407    #[test]
3408    fn numberty_from_f32_matches_raw_cast_to_f64() {
3409        let input: f32 = 1.23;
3410        let expected = input as f64;
3411        let nt: NumberTy = input.into();
3412        match nt {
3413            NumberTy::F64(val) => assert_eq!(val, expected),
3414            _ => panic!("Expected F64 variant"),
3415        }
3416    }
3417
3418    #[test]
3419    fn numberty_conv_wraps_into_celvalue_number() {
3420        let nt = NumberTy::I64(-5);
3421        let cv: CelValue = nt.conv();
3422        assert_eq!(cv, CelValue::Number(NumberTy::I64(-5)));
3423    }
3424
3425    #[test]
3426    fn array_access_valid_index_returns_element() {
3427        let arr = [10, 20, 30];
3428        // using u32 index
3429        let v = array_access(&arr, 1u32).unwrap();
3430        assert_eq!(*v, 20);
3431
3432        // using i64 index
3433        let v2 = array_access(&arr, 2i64).unwrap();
3434        assert_eq!(*v2, 30);
3435    }
3436
3437    #[test]
3438    fn array_access_index_out_of_bounds_errors() {
3439        let arr = [1, 2];
3440        let err = array_access(&arr, 5i32).unwrap_err();
3441        if let CelError::IndexOutOfBounds(idx, len) = err {
3442            assert_eq!(idx, 5);
3443            assert_eq!(len, 2);
3444        } else {
3445            panic!("Expected IndexOutOfBounds, got {err:?}");
3446        }
3447    }
3448
3449    #[test]
3450    fn array_access_non_numeric_index_errors() {
3451        let arr = [100, 200];
3452        let err = array_access(&arr, "not_a_number").unwrap_err();
3453        if let CelError::IndexWithBadIndex(value) = err {
3454            assert_eq!(value, "not_a_number".conv());
3455        } else {
3456            panic!("Expected IndexWithBadIndex, got {err:?}");
3457        }
3458    }
3459
3460    #[test]
3461    fn celvalue_eq_string_and_string_conv() {
3462        let cv = CelValue::String(CelString::Owned(Arc::from("hello")));
3463        let s = "hello".to_string();
3464        assert_eq!(cv, s);
3465        assert_eq!(s, cv);
3466    }
3467
3468    #[test]
3469    fn celvalue_eq_i32_and_conv() {
3470        let cv = 42i32.conv();
3471        assert_eq!(cv, 42i32);
3472        assert_eq!(42i32, cv);
3473    }
3474
3475    #[test]
3476    fn celvalue_eq_i64_and_conv() {
3477        let cv = 123i64.conv();
3478        assert_eq!(cv, 123i64);
3479        assert_eq!(123i64, cv);
3480    }
3481
3482    #[test]
3483    fn celvalue_eq_u32_and_conv() {
3484        let cv = 7u32.conv();
3485        assert_eq!(cv, 7u32);
3486        assert_eq!(7u32, cv);
3487    }
3488
3489    #[test]
3490    fn celvalue_eq_u64_and_conv() {
3491        let cv = 99u64.conv();
3492        assert_eq!(cv, 99u64);
3493        assert_eq!(99u64, cv);
3494    }
3495
3496    #[test]
3497    fn celvalue_eq_f32_and_conv() {
3498        let cv = 1.5f32.conv();
3499        assert!(cv == 1.5f32);
3500        assert!(1.5f32 == cv);
3501    }
3502
3503    #[test]
3504    fn celvalue_eq_f64_and_conv() {
3505        let cv = 2.75f64.conv();
3506        assert_eq!(cv, 2.75f64);
3507        assert_eq!(2.75f64, cv);
3508    }
3509
3510    #[test]
3511    fn celvalue_eq_vec_u8_and_conv() {
3512        let vec = vec![10u8, 20, 30];
3513        let cv = (&vec).conv();
3514        assert_eq!(cv, vec);
3515        assert_eq!(vec, cv);
3516    }
3517
3518    #[test]
3519    fn celvalue_eq_bytes_variant() {
3520        let b = Bytes::from_static(b"xyz");
3521        let cv = CelValue::Bytes(CelBytes::Owned(b.clone()));
3522        assert_eq!(cv, b);
3523    }
3524
3525    #[test]
3526    fn bytes_eq_celvalue_variant() {
3527        let b = Bytes::from_static(b"hello");
3528        let cv = CelValue::Bytes(CelBytes::Owned(b.clone()));
3529        assert_eq!(b, cv);
3530    }
3531
3532    #[test]
3533    fn array_contains_with_integers() {
3534        let arr = [1i32, 2, 3];
3535        assert!(array_contains(&arr, 2i32));
3536        assert!(!array_contains(&arr, 4i32));
3537    }
3538
3539    #[test]
3540    fn array_contains_with_bytes() {
3541        let b1 = Bytes::from_static(b"a");
3542        let b2 = Bytes::from_static(b"b");
3543        let arr = [b1.clone(), b2.clone()];
3544        assert!(array_contains(&arr, b2.clone()));
3545        assert!(!array_contains(&arr, Bytes::from_static(b"c")));
3546    }
3547
3548    #[test]
3549    fn map_access_and_contains_with_hashmap_i32_key() {
3550        let mut hm: HashMap<i32, &str> = HashMap::new();
3551        hm.insert(5, "five");
3552
3553        let v = map_access(&hm, 5i32).unwrap();
3554        assert_eq!(*v, "five");
3555
3556        assert!(map_contains(&hm, 5i32));
3557        assert!(!map_contains(&hm, 6i32));
3558    }
3559
3560    #[test]
3561    fn map_access_and_contains_with_btreemap_u32_key() {
3562        let mut bt: BTreeMap<u32, &str> = BTreeMap::new();
3563        bt.insert(10, "ten");
3564
3565        let v = map_access(&bt, 10u32).unwrap();
3566        assert_eq!(*v, "ten");
3567
3568        assert!(map_contains(&bt, 10u32));
3569        assert!(!map_contains(&bt, 11u32));
3570    }
3571
3572    #[test]
3573    fn map_access_key_not_found_errors() {
3574        let mut hm: HashMap<i32, &str> = HashMap::new();
3575        hm.insert(1, "one");
3576
3577        let err = map_access(&hm, 2i32).unwrap_err();
3578        if let CelError::MapKeyNotFound(k) = err {
3579            assert_eq!(k, 2i32.conv());
3580        } else {
3581            panic!("Expected MapKeyNotFound");
3582        }
3583    }
3584
3585    #[test]
3586    fn map_key_cast_string_some_for_borrowed() {
3587        let cv = "hello".conv();
3588        let key: Option<Cow<str>> = <String as MapKeyCast>::make_key(&cv);
3589        match key {
3590            Some(Cow::Borrowed(s)) => assert_eq!(s, "hello"),
3591            _ => panic!("Expected Some(Cow::Borrowed)"),
3592        }
3593    }
3594
3595    #[test]
3596    fn map_key_cast_string_some_for_owned() {
3597        let arc: Arc<str> = Arc::from("world");
3598        let cv = CelValue::String(CelString::Owned(arc.clone()));
3599        let key: Option<Cow<str>> = <String as MapKeyCast>::make_key(&cv);
3600        match key {
3601            Some(Cow::Borrowed(s)) => assert_eq!(s, "world"),
3602            _ => panic!("Expected Some(Cow::Borrowed)"),
3603        }
3604    }
3605
3606    #[test]
3607    fn map_key_cast_string_none_for_non_string() {
3608        let cv = 42i32.conv();
3609        assert!(<String as MapKeyCast>::make_key(&cv).is_none());
3610    }
3611
3612    #[test]
3613    fn map_key_cast_number_none_for_non_number_value() {
3614        let cv = "not_a_number".conv();
3615        let result: Option<Cow<'_, i32>> = <i32 as MapKeyCast>::make_key(&cv);
3616        assert!(result.is_none(), "Expected None for non-Number CelValue");
3617    }
3618
3619    #[test]
3620    fn option_to_bool() {
3621        assert!(Some(true).to_bool(), "Some(true) should be true");
3622        assert!(!Some(false).to_bool(), "Some(false) should be false");
3623        let none: Option<bool> = None;
3624        assert!(!none.to_bool(), "None should be false");
3625    }
3626
3627    #[test]
3628    fn vec_to_bool() {
3629        let empty: Vec<i32> = Vec::new();
3630        assert!(!empty.to_bool(), "Empty Vec should be false");
3631        let non_empty = vec![1, 2, 3];
3632        assert!(non_empty.to_bool(), "Non-empty Vec should be true");
3633    }
3634
3635    #[test]
3636    fn btreemap_to_bool() {
3637        let mut map: BTreeMap<i32, i32> = BTreeMap::new();
3638        assert!(!map.to_bool(), "Empty BTreeMap should be false");
3639        map.insert(1, 10);
3640        assert!(map.to_bool(), "Non-empty BTreeMap should be true");
3641    }
3642
3643    #[test]
3644    fn hashmap_to_bool() {
3645        let mut map: HashMap<&str, i32> = HashMap::new();
3646        assert!(!map.to_bool(), "Empty HashMap should be false");
3647        map.insert("key", 42);
3648        assert!(map.to_bool(), "Non-empty HashMap should be true");
3649    }
3650
3651    #[test]
3652    fn str_and_string_to_bool() {
3653        assert!("hello".to_bool(), "Non-empty &str should be true");
3654        assert!(!"".to_bool(), "Empty &str should be false");
3655        let s = String::from("world");
3656        assert!(s.to_bool(), "Non-empty String should be true");
3657        let empty = String::new();
3658        assert!(!empty.to_bool(), "Empty String should be false");
3659    }
3660
3661    #[test]
3662    fn array_slice_to_bool() {
3663        let empty: [bool; 0] = [];
3664        assert!(!empty.to_bool(), "Empty [T] slice should be false");
3665        let non_empty = [true, false];
3666        assert!(non_empty.to_bool(), "Non-empty [T] slice should be true");
3667    }
3668
3669    #[test]
3670    fn bytes_to_bool() {
3671        let empty = Bytes::new();
3672        assert!(!empty.to_bool(), "Empty Bytes should be false");
3673        let non_empty = Bytes::from_static(b"x");
3674        assert!(non_empty.to_bool(), "Non-empty Bytes should be true");
3675    }
3676
3677    #[cfg(feature = "runtime")]
3678    #[test]
3679    fn celmode_json_and_proto_flags() {
3680        use crate::CelMode;
3681
3682        CelMode::set(CelMode::Serde);
3683        let current = CelMode::current();
3684        assert!(
3685            current.is_json(),
3686            "CelMode should report JSON when set to Json"
3687        );
3688        assert!(
3689            !current.is_proto(),
3690            "CelMode should not report Proto when set to Json"
3691        );
3692
3693        CelMode::set(CelMode::Proto);
3694        let current = CelMode::current();
3695        assert!(
3696            current.is_proto(),
3697            "CelMode should report Proto when set to Proto"
3698        );
3699        assert!(
3700            !current.is_json(),
3701            "CelMode should not report JSON when set to Proto"
3702        );
3703    }
3704}