tonneau_build/codegen/cel/functions/
size.rs1use syn::parse_quote;
2use tonneau_cel::CelValue;
3
4use super::Function;
5use crate::codegen::cel::compiler::{
6 CompileError, CompiledExpr, CompilerCtx, ConstantCompiledExpr, RuntimeCompiledExpr,
7};
8use crate::codegen::cel::types::CelType;
9use crate::types::{ProtoModifiedValueType, ProtoType, ProtoValueType};
10
11#[derive(Debug, Clone, Default)]
12pub(crate) struct Size;
13
14impl Function for Size {
15 fn name(&self) -> &'static str {
16 "size"
17 }
18
19 fn syntax(&self) -> &'static str {
20 "<this>.size()"
21 }
22
23 fn compile(&self, ctx: CompilerCtx) -> Result<CompiledExpr, CompileError> {
24 let Some(this) = ctx.this else {
25 return Err(CompileError::syntax("missing this", self));
26 };
27
28 if !ctx.args.is_empty() {
29 return Err(CompileError::syntax("takes no arguments", self));
30 }
31
32 if let CompiledExpr::Runtime(RuntimeCompiledExpr {
33 expr,
34 ty:
35 CelType::Proto(ProtoType::Modified(
36 ProtoModifiedValueType::Repeated(_) | ProtoModifiedValueType::Map(_, _),
37 )),
38 }) = &this
39 {
40 return Ok(CompiledExpr::runtime(
41 CelType::Proto(ProtoType::Value(ProtoValueType::UInt64)),
42 parse_quote! {
43 ((#expr).len() as u64)
44 },
45 ));
46 }
47
48 match this.into_cel()? {
49 CompiledExpr::Constant(ConstantCompiledExpr { value }) => {
50 Ok(CompiledExpr::constant(CelValue::cel_size(value)?))
51 }
52 CompiledExpr::Runtime(RuntimeCompiledExpr { expr, .. }) => Ok(CompiledExpr::runtime(
53 CelType::Proto(ProtoType::Value(ProtoValueType::UInt64)),
54 parse_quote!(::tonneau::__private::cel::CelValue::cel_size(#expr)?),
55 )),
56 }
57 }
58}
59
60#[cfg(test)]
61#[cfg(feature = "prost")]
62#[cfg_attr(coverage_nightly, coverage(off))]
63mod tests {
64 use syn::parse_quote;
65 use tonneau_cel::CelValue;
66
67 use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
68 use crate::codegen::cel::functions::{Function, Size};
69 use crate::codegen::cel::types::CelType;
70 use crate::extern_paths::ExternPaths;
71 use crate::path_set::PathSet;
72 use crate::types::{ProtoModifiedValueType, ProtoType, ProtoTypeRegistry, ProtoValueType};
73
74 #[test]
75 fn test_size_syntax() {
76 let registry = ProtoTypeRegistry::new(
77 crate::Mode::Prost,
78 ExternPaths::new(crate::Mode::Prost),
79 PathSet::default(),
80 );
81 let compiler = Compiler::new(®istry);
82 insta::assert_debug_snapshot!(Size.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
83 Err(
84 InvalidSyntax {
85 message: "missing this",
86 syntax: "<this>.size()",
87 },
88 )
89 "#);
90
91 insta::assert_debug_snapshot!(Size.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("13".into()))), &[])), @r"
92 Ok(
93 Constant(
94 ConstantCompiledExpr {
95 value: Number(
96 U64(
97 2,
98 ),
99 ),
100 },
101 ),
102 )
103 ");
104
105 insta::assert_debug_snapshot!(Size.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::List(Default::default()))), &[
106 cel_parser::parse("1 + 1").unwrap(), ])), @r#"
108 Err(
109 InvalidSyntax {
110 message: "takes no arguments",
111 syntax: "<this>.size()",
112 },
113 )
114 "#);
115 }
116
117 #[test]
118 #[cfg(not(valgrind))]
119 fn test_size_runtime() {
120 let registry = ProtoTypeRegistry::new(
121 crate::Mode::Prost,
122 ExternPaths::new(crate::Mode::Prost),
123 PathSet::default(),
124 );
125 let compiler = Compiler::new(®istry);
126
127 let string_value = CompiledExpr::runtime(
128 CelType::Proto(ProtoType::Value(ProtoValueType::String)),
129 parse_quote!(input),
130 );
131
132 let output = Size
133 .compile(CompilerCtx::new(compiler.child(), Some(string_value), &[]))
134 .unwrap();
135
136 insta::assert_snapshot!(postcompile::compile_str!(
137 postcompile::config! {
138 test: true,
139 dependencies: vec![
140 postcompile::Dependency::path("tonneau", "../tonneau"),
141 ],
142 },
143 quote::quote! {
144 fn size(input: &str) -> Result<u64, ::tonneau::__private::cel::CelError<'_>> {
145 Ok(#output)
146 }
147
148 #[test]
149 fn test_size() {
150 assert_eq!(size("55").unwrap(), 2);
151 }
152 },
153 ));
154 }
155
156 #[test]
157 #[cfg(not(valgrind))]
158 fn test_size_runtime_map() {
159 let registry = ProtoTypeRegistry::new(
160 crate::Mode::Prost,
161 ExternPaths::new(crate::Mode::Prost),
162 PathSet::default(),
163 );
164 let compiler = Compiler::new(®istry);
165
166 let input = CompiledExpr::runtime(
167 CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Map(
168 ProtoValueType::String,
169 ProtoValueType::Bool,
170 ))),
171 parse_quote!(input),
172 );
173
174 let output = Size
175 .compile(CompilerCtx::new(compiler.child(), Some(input), &[]))
176 .unwrap();
177
178 insta::assert_snapshot!(postcompile::compile_str!(
179 postcompile::config! {
180 test: true,
181 dependencies: vec![
182 postcompile::Dependency::path("tonneau", "../tonneau"),
183 ],
184 },
185 quote::quote! {
186 #![allow(unused_parens)]
187
188 fn size(input: &std::collections::HashMap<String, bool>) -> Result<u64, ::tonneau::__private::cel::CelError<'_>> {
189 Ok(#output)
190 }
191
192 #[test]
193 fn test_contains() {
194 assert_eq!(size(&{
195 let mut map = std::collections::HashMap::new();
196 map.insert("value".to_string(), true);
197 map
198 }).unwrap(), 1);
199 assert_eq!(size(&std::collections::HashMap::new()).unwrap(), 0);
200 assert_eq!(size(&{
201 let mut map = std::collections::HashMap::new();
202 map.insert("xd".to_string(), true);
203 map.insert("value".to_string(), true);
204 map
205 }).unwrap(), 2);
206 }
207 },
208 ));
209 }
210
211 #[test]
212 #[cfg(not(valgrind))]
213 fn test_size_runtime_repeated() {
214 let registry = ProtoTypeRegistry::new(
215 crate::Mode::Prost,
216 ExternPaths::new(crate::Mode::Prost),
217 PathSet::default(),
218 );
219 let compiler = Compiler::new(®istry);
220
221 let string_value = CompiledExpr::runtime(
222 CelType::Proto(ProtoType::Modified(ProtoModifiedValueType::Repeated(
223 ProtoValueType::String,
224 ))),
225 parse_quote!(input),
226 );
227
228 let output = Size
229 .compile(CompilerCtx::new(compiler.child(), Some(string_value), &[]))
230 .unwrap();
231
232 insta::assert_snapshot!(postcompile::compile_str!(
233 postcompile::config! {
234 test: true,
235 dependencies: vec![
236 postcompile::Dependency::path("tonneau", "../tonneau"),
237 ],
238 },
239 quote::quote! {
240 #![allow(unused_parens)]
241
242 fn size(input: &Vec<String>) -> Result<u64, ::tonneau::__private::cel::CelError<'_>> {
243 Ok(#output)
244 }
245
246 #[test]
247 fn test_contains() {
248 assert_eq!(size(&vec!["value".into()]).unwrap(), 1);
249 assert_eq!(size(&vec![]).unwrap(), 0);
250 assert_eq!(size(&vec!["xd".into(), "value".into()]).unwrap(), 2);
251 }
252 },
253 ));
254 }
255}