vrl/stdlib/
decode_zlib.rs

1use crate::compiler::prelude::*;
2use flate2::read::ZlibDecoder;
3use std::io::Read;
4
5fn decode_zlib(value: Value) -> Resolved {
6    let value = value.try_bytes()?;
7    let mut buf = Vec::new();
8    let result = ZlibDecoder::new(std::io::Cursor::new(value)).read_to_end(&mut buf);
9
10    match result {
11        Ok(_) => Ok(Value::Bytes(buf.into())),
12        Err(_) => Err("unable to decode value with Zlib decoder".into()),
13    }
14}
15
16#[derive(Clone, Copy, Debug)]
17pub struct DecodeZlib;
18
19impl Function for DecodeZlib {
20    fn identifier(&self) -> &'static str {
21        "decode_zlib"
22    }
23
24    fn examples(&self) -> &'static [Example] {
25        &[Example {
26            title: "demo string",
27            source: r#"decode_zlib!(decode_base64!("eJxLzUvOT0mNz00FABI5A6A="))"#,
28            result: Ok("encode_me"),
29        }]
30    }
31
32    fn compile(
33        &self,
34        _state: &state::TypeState,
35        _ctx: &mut FunctionCompileContext,
36        arguments: ArgumentList,
37    ) -> Compiled {
38        let value = arguments.required("value");
39
40        Ok(DecodeZlibFn { value }.as_expr())
41    }
42
43    fn parameters(&self) -> &'static [Parameter] {
44        &[Parameter {
45            keyword: "value",
46            kind: kind::BYTES,
47            required: true,
48        }]
49    }
50}
51
52#[derive(Clone, Debug)]
53struct DecodeZlibFn {
54    value: Box<dyn Expression>,
55}
56
57impl FunctionExpression for DecodeZlibFn {
58    fn resolve(&self, ctx: &mut Context) -> Resolved {
59        let value = self.value.resolve(ctx)?;
60
61        decode_zlib(value)
62    }
63
64    fn type_def(&self, _: &state::TypeState) -> TypeDef {
65        // Always fallible due to the possibility of decoding errors that VRL can't detect
66        TypeDef::bytes().fallible()
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    use crate::value;
74    use flate2::read::ZlibEncoder;
75    use nom::AsBytes;
76
77    fn get_encoded_bytes(text: &str) -> Vec<u8> {
78        let mut buf = Vec::new();
79        let mut gz = ZlibEncoder::new(text.as_bytes(), flate2::Compression::fast());
80        gz.read_to_end(&mut buf)
81            .expect("Cannot encode bytes with Gzip encoder");
82        buf
83    }
84
85    test_function![
86        decode_zlib => DecodeZlib;
87
88        right_gzip {
89            args: func_args![value: value!(get_encoded_bytes("sample").as_bytes())],
90            want: Ok(value!(b"sample")),
91            tdef: TypeDef::bytes().fallible(),
92        }
93
94        wrong_gzip {
95            args: func_args![value: value!("some_bytes")],
96            want: Err("unable to decode value with Zlib decoder"),
97            tdef: TypeDef::bytes().fallible(),
98        }
99    ];
100}