1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use super::Handler;
use crate::{error, Path};
#[derive(Debug, Default)]
pub struct Unstringify;
impl Unstringify {
pub fn new() -> Self {
Self
}
}
impl Handler for Unstringify {
fn handle(
&mut self,
_path: &Path,
_matcher_idx: usize,
data: Option<&[u8]>,
) -> Result<Option<Vec<u8>>, error::Handler> {
let data = data.unwrap();
if data[0] != b'"' || data[data.len() - 1] != b'"' {
return Err(error::Handler::new(
"Unstringified data is supposed to be a string.",
));
}
let mut result: Vec<u8> = vec![];
let mut escaped = false;
for byte in data.iter().take(data.len() - 1).skip(1) {
if escaped {
result.push(*byte);
escaped = false;
} else {
match *byte {
b'\\' => escaped = true,
b'"' => return Err(error::Handler::new("Wrong unstringify format")),
byte => result.push(byte),
}
}
}
if escaped {
return Err(error::Handler::new("Wrong unstringify format"));
}
Ok(Some(result))
}
fn buffering_required(&self) -> bool {
true
}
}
#[cfg(test)]
mod tests {
use super::Unstringify;
use crate::{matcher::Simple, strategy::Convert};
use std::sync::{Arc, Mutex};
#[test]
fn unstringify_handler_ok() {
let mut convert = Convert::new();
let shorten_handler = Arc::new(Mutex::new(Unstringify::new()));
let matcher = Simple::new(r#"[]{"stringified"}[]"#).unwrap();
convert.add_matcher(Box::new(matcher), vec![shorten_handler.clone()]);
let mut output = convert
.process(br#"[{"stringified": ["true", "false", "null", "11", "\"\""]},"#)
.unwrap();
output.extend(
convert
.process(br#" {"stringified": ["\"inner\"", "[]", "{}", "{\"key\": \"value\"}"]}]"#)
.unwrap(),
);
let output: Vec<u8> = output.into_iter().flatten().collect();
assert_eq!(
String::from_utf8(output).unwrap(),
r#"[{"stringified": [true, false, null, 11, ""]}, {"stringified": ["inner", [], {}, {"key": "value"}]}]"#
);
}
}