nu_command/bytes/
starts_with.rs

1use nu_cmd_base::input_handler::{CmdArgument, operate};
2use nu_engine::command_prelude::*;
3use nu_protocol::shell_error::io::IoError;
4use std::io::Read;
5
6struct Arguments {
7    pattern: Vec<u8>,
8    cell_paths: Option<Vec<CellPath>>,
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)]
18
19pub struct BytesStartsWith;
20
21impl Command for BytesStartsWith {
22    fn name(&self) -> &str {
23        "bytes starts-with"
24    }
25
26    fn signature(&self) -> Signature {
27        Signature::build("bytes starts-with")
28            .input_output_types(vec![
29                (Type::Binary, Type::Bool),
30                (Type::table(), Type::table()),
31                (Type::record(), Type::record()),
32            ])
33            .allow_variants_without_examples(true)
34            .required("pattern", SyntaxShape::Binary, "The pattern to match.")
35            .rest(
36                "rest",
37                SyntaxShape::CellPath,
38                "For a data structure input, check if bytes at the given cell paths start with the pattern.",
39            )
40            .category(Category::Bytes)
41    }
42
43    fn description(&self) -> &str {
44        "Check if bytes starts with a pattern."
45    }
46
47    fn search_terms(&self) -> Vec<&str> {
48        vec!["pattern", "match", "find", "search"]
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 head = call.head;
59        let pattern: Vec<u8> = call.req(engine_state, stack, 0)?;
60        let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?;
61        let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
62
63        if let PipelineData::ByteStream(stream, ..) = input {
64            let span = stream.span();
65            if pattern.is_empty() {
66                return Ok(Value::bool(true, head).into_pipeline_data());
67            }
68            let Some(reader) = stream.reader() else {
69                return Ok(Value::bool(false, head).into_pipeline_data());
70            };
71            let mut start = Vec::with_capacity(pattern.len());
72            reader
73                .take(pattern.len() as u64)
74                .read_to_end(&mut start)
75                .map_err(|err| IoError::new(err, span, None))?;
76
77            Ok(Value::bool(start == pattern, head).into_pipeline_data())
78        } else {
79            let arg = Arguments {
80                pattern,
81                cell_paths,
82            };
83            operate(starts_with, arg, input, head, engine_state.signals())
84        }
85    }
86
87    fn examples(&self) -> Vec<Example> {
88        vec![
89            Example {
90                description: "Checks if binary starts with `0x[1F FF AA]`",
91                example: "0x[1F FF AA AA] | bytes starts-with 0x[1F FF AA]",
92                result: Some(Value::test_bool(true)),
93            },
94            Example {
95                description: "Checks if binary starts with `0x[1F]`",
96                example: "0x[1F FF AA AA] | bytes starts-with 0x[1F]",
97                result: Some(Value::test_bool(true)),
98            },
99            Example {
100                description: "Checks if binary starts with `0x[1F]`",
101                example: "0x[1F FF AA AA] | bytes starts-with 0x[11]",
102                result: Some(Value::test_bool(false)),
103            },
104        ]
105    }
106}
107
108fn starts_with(val: &Value, args: &Arguments, span: Span) -> Value {
109    let val_span = val.span();
110    match val {
111        Value::Binary { val, .. } => Value::bool(val.starts_with(&args.pattern), val_span),
112        // Propagate errors by explicitly matching them before the final case.
113        Value::Error { .. } => val.clone(),
114        other => Value::error(
115            ShellError::OnlySupportsThisInputType {
116                exp_input_type: "binary".into(),
117                wrong_type: other.get_type().to_string(),
118                dst_span: span,
119                src_span: other.span(),
120            },
121            span,
122        ),
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn test_examples() {
132        use crate::test_examples;
133
134        test_examples(BytesStartsWith {})
135    }
136}