vrl/stdlib/
decode_base16.rs1use crate::compiler::prelude::*;
2use nom::AsBytes;
3use std::str;
4
5fn decode_base16(value: &Value) -> Resolved {
6 match base16::decode(&value.try_bytes_utf8_lossy()?.to_string()) {
7 Ok(s) => Ok((s.as_bytes()).into()),
8 Err(_) => Err("unable to decode value to base16".into()),
9 }
10}
11
12#[derive(Clone, Copy, Debug)]
13pub struct DecodeBase16;
14
15impl Function for DecodeBase16 {
16 fn identifier(&self) -> &'static str {
17 "decode_base16"
18 }
19
20 fn usage(&self) -> &'static str {
21 "Decodes the `value` (a [Base16](https://en.wikipedia.org/wiki/Hexadecimal) string) into its original string."
22 }
23
24 fn category(&self) -> &'static str {
25 Category::Codec.as_ref()
26 }
27
28 fn internal_failure_reasons(&self) -> &'static [&'static str] {
29 &["`value` isn't a valid encoded Base16 string."]
30 }
31
32 fn return_kind(&self) -> u16 {
33 kind::BYTES
34 }
35
36 fn parameters(&self) -> &'static [Parameter] {
37 const PARAMETERS: &[Parameter] = &[Parameter::required(
38 "value",
39 kind::BYTES,
40 "The [Base16](https://en.wikipedia.org/wiki/Hexadecimal) data to decode.",
41 )];
42 PARAMETERS
43 }
44
45 fn compile(
46 &self,
47 _state: &state::TypeState,
48 _ctx: &mut FunctionCompileContext,
49 arguments: ArgumentList,
50 ) -> Compiled {
51 let value = arguments.required("value");
52
53 Ok(DecodeBase16Fn { value }.as_expr())
54 }
55
56 fn examples(&self) -> &'static [Example] {
57 &[
58 example! {
59 title: "Decode Base16 data",
60 source: r#"decode_base16!("736F6D6520737472696E672076616C7565")"#,
61 result: Ok("some string value"),
62 },
63 example! {
64 title: "Decode longer Base16 data",
65 source: r#"decode_base16!("796f752068617665207375636365737366756c6c79206465636f646564206d65")"#,
66 result: Ok("you have successfully decoded me"),
67 },
68 ]
69 }
70}
71
72#[derive(Clone, Debug)]
73struct DecodeBase16Fn {
74 value: Box<dyn Expression>,
75}
76
77impl FunctionExpression for DecodeBase16Fn {
78 fn resolve(&self, ctx: &mut Context) -> Resolved {
79 let value = self.value.resolve(ctx)?;
80
81 decode_base16(&value)
82 }
83
84 fn type_def(&self, _: &state::TypeState) -> TypeDef {
85 TypeDef::bytes().fallible()
87 }
88}
89
90#[cfg(test)]
91mod test {
92 use super::*;
93 use crate::value;
94
95 test_function![
96 decode_base16 => DecodeBase16;
97
98 standard {
99 args: func_args![value: value!("736F6D652B3D737472696E672F76616C7565")],
100 want: Ok(value!("some+=string/value")),
101 tdef: TypeDef::bytes().fallible(),
102 }
103 ];
104}