nu_command/bytes/
remove.rs

1use nu_cmd_base::input_handler::{CmdArgument, operate};
2use nu_engine::command_prelude::*;
3
4struct Arguments {
5    pattern: Vec<u8>,
6    end: bool,
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 BytesRemove;
19
20impl Command for BytesRemove {
21    fn name(&self) -> &str {
22        "bytes remove"
23    }
24
25    fn signature(&self) -> Signature {
26        Signature::build("bytes remove")
27            .input_output_types(vec![
28                (Type::Binary, Type::Binary),
29                (Type::table(), Type::table()),
30                (Type::record(), Type::record()),
31            ])
32            .required("pattern", SyntaxShape::Binary, "The pattern to find.")
33            .rest(
34                "rest",
35                SyntaxShape::CellPath,
36                "For a data structure input, remove bytes from data at the given cell paths.",
37            )
38            .switch("end", "remove from end of binary", Some('e'))
39            .switch("all", "remove occurrences of finding binary", Some('a'))
40            .category(Category::Bytes)
41    }
42
43    fn description(&self) -> &str {
44        "Remove bytes."
45    }
46
47    fn search_terms(&self) -> Vec<&str> {
48        vec!["search", "shift", "switch"]
49    }
50
51    fn run(
52        &self,
53        engine_state: &EngineState,
54        stack: &mut Stack,
55        call: &Call,
56        input: PipelineData,
57    ) -> Result<PipelineData, ShellError> {
58        let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?;
59        let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
60        let pattern_to_remove = call.req::<Spanned<Vec<u8>>>(engine_state, stack, 0)?;
61        if pattern_to_remove.item.is_empty() {
62            return Err(ShellError::TypeMismatch {
63                err_message: "the pattern to remove cannot be empty".to_string(),
64                span: pattern_to_remove.span,
65            });
66        }
67
68        let pattern_to_remove: Vec<u8> = pattern_to_remove.item;
69        let arg = Arguments {
70            pattern: pattern_to_remove,
71            end: call.has_flag(engine_state, stack, "end")?,
72            cell_paths,
73            all: call.has_flag(engine_state, stack, "all")?,
74        };
75
76        operate(remove, arg, input, call.head, engine_state.signals())
77    }
78
79    fn examples(&self) -> Vec<Example> {
80        vec![
81            Example {
82                description: "Remove contents",
83                example: "0x[10 AA FF AA FF] | bytes remove 0x[10 AA]",
84                result: Some(Value::test_binary(vec![0xFF, 0xAA, 0xFF])),
85            },
86            Example {
87                description: "Remove all occurrences of find binary in record field",
88                example: "{ data: 0x[10 AA 10 BB 10] } | bytes remove --all 0x[10] data",
89                result: Some(Value::test_record(record! {
90                    "data" => Value::test_binary(vec![0xAA, 0xBB])
91                })),
92            },
93            Example {
94                description: "Remove occurrences of find binary from end",
95                example: "0x[10 AA 10 BB CC AA 10] | bytes remove --end 0x[10]",
96                result: Some(Value::test_binary(vec![0x10, 0xAA, 0x10, 0xBB, 0xCC, 0xAA])),
97            },
98            Example {
99                description: "Remove find binary from end not found",
100                example: "0x[10 AA 10 BB CC AA 10] | bytes remove --end 0x[11]",
101                result: Some(Value::test_binary(vec![
102                    0x10, 0xAA, 0x10, 0xBB, 0xCC, 0xAA, 0x10,
103                ])),
104            },
105            Example {
106                description: "Remove all occurrences of find binary in table",
107                example: "[[ColA ColB ColC]; [0x[11 12 13] 0x[14 15 16] 0x[17 18 19]]] | bytes remove 0x[11] ColA ColC",
108                result: Some(Value::test_list(vec![Value::test_record(record! {
109                    "ColA" => Value::test_binary ( vec![0x12, 0x13],),
110                    "ColB" => Value::test_binary ( vec![0x14, 0x15, 0x16],),
111                    "ColC" => Value::test_binary ( vec![0x17, 0x18, 0x19],),
112                })])),
113            },
114        ]
115    }
116}
117
118fn remove(val: &Value, args: &Arguments, span: Span) -> Value {
119    let val_span = val.span();
120    match val {
121        Value::Binary { val, .. } => remove_impl(val, args, val_span),
122        // Propagate errors by explicitly matching them before the final case.
123        Value::Error { .. } => val.clone(),
124        other => Value::error(
125            ShellError::OnlySupportsThisInputType {
126                exp_input_type: "binary".into(),
127                wrong_type: other.get_type().to_string(),
128                dst_span: span,
129                src_span: other.span(),
130            },
131            span,
132        ),
133    }
134}
135
136fn remove_impl(input: &[u8], arg: &Arguments, span: Span) -> Value {
137    let mut result = vec![];
138    let remove_all = arg.all;
139    let input_len = input.len();
140    let pattern_len = arg.pattern.len();
141
142    // Note:
143    // remove_all from start and end will generate the same result.
144    // so we'll put `remove_all` relative logic into else clause.
145    if arg.end && !remove_all {
146        let (mut left, mut right) = (
147            input.len() as isize - arg.pattern.len() as isize,
148            input.len() as isize,
149        );
150        while left >= 0 && input[left as usize..right as usize] != arg.pattern {
151            result.push(input[right as usize - 1]);
152            left -= 1;
153            right -= 1;
154        }
155        // append the remaining thing to result, this can be happening when
156        // we have something to remove and remove_all is False.
157        // check if the left is positive, if it is not, we don't need to append anything.
158        if left > 0 {
159            let mut remain = input[..left as usize].iter().copied().rev().collect();
160            result.append(&mut remain);
161        }
162        result = result.into_iter().rev().collect();
163        Value::binary(result, span)
164    } else {
165        let (mut left, mut right) = (0, arg.pattern.len());
166        while right <= input_len {
167            if input[left..right] == arg.pattern {
168                left += pattern_len;
169                right += pattern_len;
170                if !remove_all {
171                    break;
172                }
173            } else {
174                result.push(input[left]);
175                left += 1;
176                right += 1;
177            }
178        }
179        // append the remaining thing to result, this can happened when
180        // we have something to remove and remove_all is False.
181        let mut remain = input[left..].to_vec();
182        result.append(&mut remain);
183        Value::binary(result, span)
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn test_examples() {
193        use crate::test_examples;
194
195        test_examples(BytesRemove {})
196    }
197}