nu_command/bytes/
replace.rs

1use nu_cmd_base::input_handler::{operate, CmdArgument};
2use nu_engine::command_prelude::*;
3
4struct Arguments {
5    find: Vec<u8>,
6    replace: Vec<u8>,
7    cell_paths: Option<Vec<CellPath>>,
8    all: bool,
9}
10
11impl CmdArgument for Arguments {
12    fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
13        self.cell_paths.take()
14    }
15}
16
17#[derive(Clone)]
18pub struct BytesReplace;
19
20impl Command for BytesReplace {
21    fn name(&self) -> &str {
22        "bytes replace"
23    }
24
25    fn signature(&self) -> Signature {
26        Signature::build("bytes replace")
27            .input_output_types(vec![
28                (Type::Binary, Type::Binary),
29                (Type::table(), Type::table()),
30                (Type::record(), Type::record()),
31            ])
32            .allow_variants_without_examples(true)
33            .required("find", SyntaxShape::Binary, "The pattern to find.")
34            .required("replace", SyntaxShape::Binary, "The replacement pattern.")
35            .rest(
36                "rest",
37                SyntaxShape::CellPath,
38                "For a data structure input, replace bytes in data at the given cell paths.",
39            )
40            .switch("all", "replace all occurrences of find binary", Some('a'))
41            .category(Category::Bytes)
42    }
43
44    fn description(&self) -> &str {
45        "Find and replace binary."
46    }
47
48    fn search_terms(&self) -> Vec<&str> {
49        vec!["search", "shift", "switch"]
50    }
51
52    fn run(
53        &self,
54        engine_state: &EngineState,
55        stack: &mut Stack,
56        call: &Call,
57        input: PipelineData,
58    ) -> Result<PipelineData, ShellError> {
59        let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 2)?;
60        let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
61        let find = call.req::<Spanned<Vec<u8>>>(engine_state, stack, 0)?;
62        if find.item.is_empty() {
63            return Err(ShellError::TypeMismatch {
64                err_message: "the pattern to find cannot be empty".to_string(),
65                span: find.span,
66            });
67        }
68
69        let arg = Arguments {
70            find: find.item,
71            replace: call.req::<Vec<u8>>(engine_state, stack, 1)?,
72            cell_paths,
73            all: call.has_flag(engine_state, stack, "all")?,
74        };
75
76        operate(replace, arg, input, call.head, engine_state.signals())
77    }
78
79    fn examples(&self) -> Vec<Example> {
80        vec![
81            Example {
82                description: "Find and replace contents",
83                example: "0x[10 AA FF AA FF] | bytes replace 0x[10 AA] 0x[FF]",
84                result: Some(Value::test_binary (
85                    vec![0xFF, 0xFF, 0xAA, 0xFF],
86                )),
87            },
88            Example {
89                description: "Find and replace all occurrences of find binary",
90                example: "0x[10 AA 10 BB 10] | bytes replace --all 0x[10] 0x[A0]",
91                result: Some(Value::test_binary (
92                    vec![0xA0, 0xAA, 0xA0, 0xBB, 0xA0],
93                )),
94            },
95            Example {
96                description: "Find and replace all occurrences of find binary in table",
97                example: "[[ColA ColB ColC]; [0x[11 12 13] 0x[14 15 16] 0x[17 18 19]]] | bytes replace --all 0x[11] 0x[13] ColA ColC",
98                result: Some(Value::test_list (
99                    vec![Value::test_record(record! {
100                        "ColA" => Value::test_binary(vec![0x13, 0x12, 0x13]),
101                        "ColB" => Value::test_binary(vec![0x14, 0x15, 0x16]),
102                        "ColC" => Value::test_binary(vec![0x17, 0x18, 0x19]),
103                    })],
104                )),
105            },
106        ]
107    }
108}
109
110fn replace(val: &Value, args: &Arguments, span: Span) -> Value {
111    let val_span = val.span();
112    match val {
113        Value::Binary { val, .. } => replace_impl(val, args, val_span),
114        // Propagate errors by explicitly matching them before the final case.
115        Value::Error { .. } => val.clone(),
116        other => Value::error(
117            ShellError::OnlySupportsThisInputType {
118                exp_input_type: "binary".into(),
119                wrong_type: other.get_type().to_string(),
120                dst_span: span,
121                src_span: other.span(),
122            },
123            span,
124        ),
125    }
126}
127
128fn replace_impl(input: &[u8], arg: &Arguments, span: Span) -> Value {
129    let mut replaced = vec![];
130    let replace_all = arg.all;
131
132    // doing find-and-replace stuff.
133    let (mut left, mut right) = (0, arg.find.len());
134    let input_len = input.len();
135    let pattern_len = arg.find.len();
136    while right <= input_len {
137        if input[left..right] == arg.find {
138            let mut to_replace = arg.replace.clone();
139            replaced.append(&mut to_replace);
140            left += pattern_len;
141            right += pattern_len;
142            if !replace_all {
143                break;
144            }
145        } else {
146            replaced.push(input[left]);
147            left += 1;
148            right += 1;
149        }
150    }
151
152    let mut remain = input[left..].to_vec();
153    replaced.append(&mut remain);
154    Value::binary(replaced, span)
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn test_examples() {
163        use crate::test_examples;
164
165        test_examples(BytesReplace {})
166    }
167}