|
| 1 | +use crate::cursor; |
| 2 | +use crate::extractor::pre_processors::pre_processor::PreProcessor; |
| 3 | + |
| 4 | +#[derive(Debug, Default)] |
| 5 | +pub struct Json; |
| 6 | + |
| 7 | +impl PreProcessor for Json { |
| 8 | + fn process(&self, content: &[u8]) -> Vec<u8> { |
| 9 | + let len = content.len(); |
| 10 | + let mut result = content.to_vec(); |
| 11 | + let mut cursor = cursor::Cursor::new(content); |
| 12 | + |
| 13 | + while cursor.pos < len { |
| 14 | + match cursor.curr { |
| 15 | + // Consume strings as-is |
| 16 | + b'"' => { |
| 17 | + cursor.advance(); |
| 18 | + |
| 19 | + while cursor.pos < len { |
| 20 | + match cursor.curr { |
| 21 | + // Escaped character, skip ahead to the next character |
| 22 | + b'\\' => cursor.advance_twice(), |
| 23 | + |
| 24 | + // End of the string |
| 25 | + b'"' => break, |
| 26 | + |
| 27 | + // Everything else is valid |
| 28 | + _ => cursor.advance(), |
| 29 | + }; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // Replace brackets and curlies with spaces |
| 34 | + b'[' | b'{' | b']' | b'}' => { |
| 35 | + result[cursor.pos] = b' '; |
| 36 | + } |
| 37 | + |
| 38 | + // Consume everything else |
| 39 | + _ => {} |
| 40 | + }; |
| 41 | + |
| 42 | + cursor.advance(); |
| 43 | + } |
| 44 | + |
| 45 | + result |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +#[cfg(test)] |
| 50 | +mod tests { |
| 51 | + use super::Json; |
| 52 | + use crate::extractor::pre_processors::pre_processor::PreProcessor; |
| 53 | + |
| 54 | + #[test] |
| 55 | + fn test_json_pre_processor() { |
| 56 | + let (input, expected) = ( |
| 57 | + r#"[1,[2,[3,4,["flex flex-1 content-['hello_world']"]]], {"flex": true}]"#, |
| 58 | + r#" 1, 2, 3,4, "flex flex-1 content-['hello_world']" , "flex": true "#, |
| 59 | + ); |
| 60 | + |
| 61 | + Json::test(input, expected); |
| 62 | + } |
| 63 | +} |
0 commit comments