vrl/stdlib/
append.rs

1use crate::compiler::prelude::*;
2
3fn append(value: Value, items: Value) -> Resolved {
4    let mut value = value.try_array()?;
5    let mut items = items.try_array()?;
6    value.append(&mut items);
7    Ok(value.into())
8}
9
10#[derive(Clone, Copy, Debug)]
11pub struct Append;
12
13impl Function for Append {
14    fn identifier(&self) -> &'static str {
15        "append"
16    }
17
18    fn usage(&self) -> &'static str {
19        "Appends each item in the `items` array to the end of the `value` array."
20    }
21
22    fn category(&self) -> &'static str {
23        Category::Array.as_ref()
24    }
25
26    fn return_kind(&self) -> u16 {
27        kind::ARRAY
28    }
29
30    fn parameters(&self) -> &'static [Parameter] {
31        const PARAMETERS: &[Parameter] = &[
32            Parameter::required("value", kind::ARRAY, "The initial array."),
33            Parameter::required("items", kind::ARRAY, "The items to append."),
34        ];
35        PARAMETERS
36    }
37
38    fn examples(&self) -> &'static [Example] {
39        &[example! {
40            title: "Append to an array",
41            source: "append([1, 2], [3, 4])",
42            result: Ok("[1, 2, 3, 4]"),
43        }]
44    }
45
46    fn compile(
47        &self,
48        _state: &state::TypeState,
49        _ctx: &mut FunctionCompileContext,
50        arguments: ArgumentList,
51    ) -> Compiled {
52        let value = arguments.required("value");
53        let items = arguments.required("items");
54
55        Ok(AppendFn { value, items }.as_expr())
56    }
57}
58
59#[derive(Debug, Clone)]
60struct AppendFn {
61    value: Box<dyn Expression>,
62    items: Box<dyn Expression>,
63}
64
65impl FunctionExpression for AppendFn {
66    fn resolve(&self, ctx: &mut Context) -> Resolved {
67        let value = self.value.resolve(ctx)?;
68        let items = self.items.resolve(ctx)?;
69
70        append(value, items)
71    }
72
73    fn type_def(&self, state: &state::TypeState) -> TypeDef {
74        let mut self_value = self.value.type_def(state).restrict_array();
75        let items = self.items.type_def(state).restrict_array();
76
77        let self_array = self_value.as_array_mut().expect("must be an array");
78        let items_array = items.as_array().expect("must be an array");
79
80        if let Some(exact_len) = self_array.exact_length() {
81            // The exact array length is known.
82            for (i, i_kind) in items_array.known() {
83                self_array
84                    .known_mut()
85                    .insert((i.to_usize() + exact_len).into(), i_kind.clone());
86            }
87
88            // "value" can't have an unknown, so they new unknown is just that of "items".
89            self_array.set_unknown(items_array.unknown_kind());
90        } else {
91            // We don't know where the items will be inserted, so the union of all items will be added to the unknown.
92            self_array.set_unknown(self_array.unknown_kind().union(items_array.reduced_kind()));
93        }
94
95        self_value.infallible()
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use crate::{btreemap, value};
103
104    test_function![
105        append => Append;
106
107        both_arrays_empty {
108            args: func_args![value: value!([]), items: value!([])],
109            want: Ok(value!([])),
110            tdef: TypeDef::array(Collection::empty()),
111        }
112
113        one_array_empty {
114            args: func_args![value: value!([]), items: value!([1, 2, 3])],
115            want: Ok(value!([1, 2, 3])),
116            tdef: TypeDef::array(btreemap! {
117                Index::from(0) => Kind::integer(),
118                Index::from(1) => Kind::integer(),
119                Index::from(2) => Kind::integer(),
120            }),
121        }
122
123        neither_array_empty {
124            args: func_args![value: value!([1, 2, 3]), items: value!([4, 5, 6])],
125            want: Ok(value!([1, 2, 3, 4, 5, 6])),
126            tdef: TypeDef::array(btreemap! {
127                Index::from(0) => Kind::integer(),
128                Index::from(1) => Kind::integer(),
129                Index::from(2) => Kind::integer(),
130                Index::from(3) => Kind::integer(),
131                Index::from(4) => Kind::integer(),
132                Index::from(5) => Kind::integer(),
133            }),
134        }
135
136        mixed_array_types {
137            args: func_args![value: value!([1, 2, 3]), items: value!([true, 5.0, "bar"])],
138            want: Ok(value!([1, 2, 3, true, 5.0, "bar"])),
139            tdef: TypeDef::array(btreemap! {
140                Index::from(0) => Kind::integer(),
141                Index::from(1) => Kind::integer(),
142                Index::from(2) => Kind::integer(),
143                Index::from(3) => Kind::boolean(),
144                Index::from(4) => Kind::float(),
145                Index::from(5) => Kind::bytes(),
146            }),
147        }
148    ];
149}