vrl/stdlib/
parse_ruby_hash.rs1use crate::compiler::prelude::*;
2
3fn parse_ruby_hash(value: &Value) -> Resolved {
4 let input = value.try_bytes_utf8_lossy()?;
5 crate::parsing::ruby_hash::parse_ruby_hash(&input)
6}
7
8#[derive(Clone, Copy, Debug)]
9pub struct ParseRubyHash;
10
11impl Function for ParseRubyHash {
12 fn identifier(&self) -> &'static str {
13 "parse_ruby_hash"
14 }
15
16 fn usage(&self) -> &'static str {
17 "Parses the `value` as ruby hash."
18 }
19
20 fn category(&self) -> &'static str {
21 Category::Parse.as_ref()
22 }
23
24 fn internal_failure_reasons(&self) -> &'static [&'static str] {
25 &["`value` is not a valid ruby hash formatted payload."]
26 }
27
28 fn return_kind(&self) -> u16 {
29 kind::OBJECT
30 }
31
32 fn notices(&self) -> &'static [&'static str] {
33 &[indoc! {"
34 Only ruby types are returned. If you need to convert a `string` into a `timestamp`,
35 consider the [`parse_timestamp`](#parse_timestamp) function.
36 "}]
37 }
38
39 fn examples(&self) -> &'static [Example] {
40 &[example! {
41 title: "Parse ruby hash",
42 source: r#"parse_ruby_hash!(s'{ "test" => "value", "testNum" => 0.2, "testObj" => { "testBool" => true, "testNull" => nil } }')"#,
43 result: Ok(r#"
44 {
45 "test": "value",
46 "testNum": 0.2,
47 "testObj": {
48 "testBool": true,
49 "testNull": null
50 }
51 }
52 "#),
53 }]
54 }
55
56 fn compile(
57 &self,
58 _state: &state::TypeState,
59 _ctx: &mut FunctionCompileContext,
60 arguments: ArgumentList,
61 ) -> Compiled {
62 let value = arguments.required("value");
63 Ok(ParseRubyHashFn { value }.as_expr())
64 }
65
66 fn parameters(&self) -> &'static [Parameter] {
67 const PARAMETERS: &[Parameter] = &[Parameter::required(
68 "value",
69 kind::BYTES,
70 "The string representation of the ruby hash to parse.",
71 )];
72 PARAMETERS
73 }
74}
75
76#[derive(Debug, Clone)]
77struct ParseRubyHashFn {
78 value: Box<dyn Expression>,
79}
80
81impl FunctionExpression for ParseRubyHashFn {
82 fn resolve(&self, ctx: &mut Context) -> Resolved {
83 let value = self.value.resolve(ctx)?;
84 parse_ruby_hash(&value)
85 }
86
87 fn type_def(&self, _: &state::TypeState) -> TypeDef {
88 TypeDef::object(Collection::from_unknown(inner_kinds())).fallible()
89 }
90}
91
92fn inner_kinds() -> Kind {
93 Kind::null()
94 | Kind::bytes()
95 | Kind::float()
96 | Kind::boolean()
97 | Kind::array(Collection::any())
98 | Kind::object(Collection::any())
99}
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104 use crate::value;
105
106 test_function![
107 parse_ruby_hash => ParseRubyHash;
108
109 complete {
110 args: func_args![value: value!(r#"{ "test" => "value", "testNum" => 0.2, "testObj" => { "testBool" => true } }"#)],
111 want: Ok(value!({
112 test: "value",
113 testNum: 0.2,
114 testObj: {
115 testBool: true
116 }
117 })),
118 tdef: TypeDef::object(Collection::from_unknown(inner_kinds())).fallible(),
119 }
120 ];
121}