nu_command/bytes/
build_.rs

1use nu_engine::command_prelude::*;
2
3#[derive(Clone)]
4pub struct BytesBuild;
5
6impl Command for BytesBuild {
7    fn name(&self) -> &str {
8        "bytes build"
9    }
10
11    fn description(&self) -> &str {
12        "Create bytes from the arguments."
13    }
14
15    fn search_terms(&self) -> Vec<&str> {
16        vec!["concatenate", "join"]
17    }
18
19    fn signature(&self) -> nu_protocol::Signature {
20        Signature::build("bytes build")
21            .input_output_types(vec![(Type::Nothing, Type::Binary)])
22            .rest("rest", SyntaxShape::Any, "List of bytes.")
23            .category(Category::Bytes)
24    }
25
26    fn examples(&self) -> Vec<Example<'_>> {
27        vec![
28            Example {
29                example: "bytes build 0x[01 02] 0x[03] 0x[04]",
30                description: "Builds binary data from 0x[01 02], 0x[03], 0x[04]",
31                result: Some(Value::binary(
32                    vec![0x01, 0x02, 0x03, 0x04],
33                    Span::test_data(),
34                )),
35            },
36            Example {
37                example: "bytes build 255 254 253 252",
38                description: "Builds binary data from byte numbers",
39                result: Some(Value::test_binary(vec![0xff, 0xfe, 0xfd, 0xfc])),
40            },
41        ]
42    }
43
44    fn run(
45        &self,
46        engine_state: &EngineState,
47        stack: &mut Stack,
48        call: &Call,
49        _input: PipelineData,
50    ) -> Result<PipelineData, ShellError> {
51        let mut output = vec![];
52        for val in call.rest::<Value>(engine_state, stack, 0)? {
53            let val_span = val.span();
54            match val {
55                Value::Binary { mut val, .. } => output.append(&mut val),
56                Value::Int { val, .. } => {
57                    let byte: u8 = val.try_into().map_err(|_| ShellError::IncorrectValue {
58                        msg: format!("{val} is out of range for byte"),
59                        val_span,
60                        call_span: call.head,
61                    })?;
62                    output.push(byte);
63                }
64                // Explicitly propagate errors instead of dropping them.
65                Value::Error { error, .. } => return Err(*error),
66                other => {
67                    return Err(ShellError::TypeMismatch {
68                        err_message: "only binary data arguments are supported".to_string(),
69                        span: other.span(),
70                    });
71                }
72            }
73        }
74
75        Ok(Value::binary(output, call.head).into_pipeline_data())
76    }
77}
78
79#[cfg(test)]
80mod test {
81    use super::*;
82
83    #[test]
84    fn test_examples() {
85        use crate::test_examples;
86
87        test_examples(BytesBuild {})
88    }
89}