1use nu_cmd_base::input_handler::{CmdArgument, operate};
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(vec![0xFF, 0xFF, 0xAA, 0xFF])),
85 },
86 Example {
87 description: "Find and replace all occurrences of find binary",
88 example: "0x[10 AA 10 BB 10] | bytes replace --all 0x[10] 0x[A0]",
89 result: Some(Value::test_binary(vec![0xA0, 0xAA, 0xA0, 0xBB, 0xA0])),
90 },
91 Example {
92 description: "Find and replace all occurrences of find binary in table",
93 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",
94 result: Some(Value::test_list(vec![Value::test_record(record! {
95 "ColA" => Value::test_binary(vec![0x13, 0x12, 0x13]),
96 "ColB" => Value::test_binary(vec![0x14, 0x15, 0x16]),
97 "ColC" => Value::test_binary(vec![0x17, 0x18, 0x19]),
98 })])),
99 },
100 ]
101 }
102}
103
104fn replace(val: &Value, args: &Arguments, span: Span) -> Value {
105 let val_span = val.span();
106 match val {
107 Value::Binary { val, .. } => replace_impl(val, args, val_span),
108 Value::Error { .. } => val.clone(),
110 other => Value::error(
111 ShellError::OnlySupportsThisInputType {
112 exp_input_type: "binary".into(),
113 wrong_type: other.get_type().to_string(),
114 dst_span: span,
115 src_span: other.span(),
116 },
117 span,
118 ),
119 }
120}
121
122fn replace_impl(input: &[u8], arg: &Arguments, span: Span) -> Value {
123 let mut replaced = vec![];
124 let replace_all = arg.all;
125
126 let (mut left, mut right) = (0, arg.find.len());
128 let input_len = input.len();
129 let pattern_len = arg.find.len();
130 while right <= input_len {
131 if input[left..right] == arg.find {
132 let mut to_replace = arg.replace.clone();
133 replaced.append(&mut to_replace);
134 left += pattern_len;
135 right += pattern_len;
136 if !replace_all {
137 break;
138 }
139 } else {
140 replaced.push(input[left]);
141 left += 1;
142 right += 1;
143 }
144 }
145
146 let mut remain = input[left..].to_vec();
147 replaced.append(&mut remain);
148 Value::binary(replaced, span)
149}
150
151#[cfg(test)]
152mod tests {
153 use super::*;
154
155 #[test]
156 fn test_examples() {
157 use crate::test_examples;
158
159 test_examples(BytesReplace {})
160 }
161}