streamson_lib/handler/replace.rs
1//! Handler which replaces output by fixed data
2//! it can be used e.g. to clear the sensitive data
3//! `"secred_password"` -> `"***"
4//!
5//! # Example
6//! ```
7//! use streamson_lib::{handler, matcher, strategy::{self, Strategy}};
8//! use std::sync::{Arc, Mutex};
9//!
10//! let handler = Arc::new(Mutex::new(handler::Replace::new(br#"***"#.to_vec())));
11//! let matcher = matcher::Simple::new(r#"{"users"}[]{"password"}"#).unwrap();
12//!
13//! let mut convert = strategy::Convert::new();
14//!
15//! // Set the matcher for convert strategy
16//! convert.add_matcher(Box::new(matcher), handler);
17//!
18//! for input in vec![
19//! br#"{"users": [{"password": "1234", "name": "first"}, {"#.to_vec(),
20//! br#""password": "0000", "name": "second}]}"#.to_vec(),
21//! ] {
22//! for converted_data in convert.process(&input).unwrap() {
23//! println!("{:?}", converted_data);
24//! }
25//! }
26//! ```
27
28use super::Handler;
29use crate::{error, path::Path, streamer::Token};
30use std::{any::Any, str::FromStr};
31
32/// Replace handler which converts matched data to fixed output
33#[derive(Debug)]
34pub struct Replace {
35 /// Data which will be returned instead of matched data
36 new_data: Vec<u8>,
37}
38
39impl Replace {
40 /// Creates a new handler which replaces matched data by fixed output
41 pub fn new(new_data: Vec<u8>) -> Self {
42 Self { new_data }
43 }
44}
45
46impl FromStr for Replace {
47 type Err = error::Handler;
48 fn from_str(input: &str) -> Result<Self, Self::Err> {
49 Ok(Self::new(input.to_string().into_bytes()))
50 }
51}
52
53impl Handler for Replace {
54 fn end(
55 &mut self,
56 _path: &Path,
57 _matcher_idx: usize,
58 _token: Token,
59 ) -> Result<Option<Vec<u8>>, error::Handler> {
60 Ok(Some(self.new_data.clone()))
61 }
62
63 fn is_converter(&self) -> bool {
64 true
65 }
66
67 fn as_any(&self) -> &dyn Any {
68 self
69 }
70}