nu_command/random/
binary.rs

1use super::byte_stream::{RandomDistribution, random_byte_stream};
2use nu_engine::command_prelude::*;
3
4#[derive(Clone)]
5pub struct RandomBinary;
6
7impl Command for RandomBinary {
8    fn name(&self) -> &str {
9        "random binary"
10    }
11
12    fn signature(&self) -> Signature {
13        Signature::build("random binary")
14            .input_output_types(vec![(Type::Nothing, Type::Binary)])
15            .allow_variants_without_examples(true)
16            .required(
17                "length",
18                SyntaxShape::OneOf(vec![SyntaxShape::Int, SyntaxShape::Filesize]),
19                "Length of the output binary.",
20            )
21            .category(Category::Random)
22    }
23
24    fn description(&self) -> &str {
25        "Generate random bytes."
26    }
27
28    fn search_terms(&self) -> Vec<&str> {
29        vec!["generate", "bytes"]
30    }
31
32    fn run(
33        &self,
34        engine_state: &EngineState,
35        stack: &mut Stack,
36        call: &Call,
37        _input: PipelineData,
38    ) -> Result<PipelineData, ShellError> {
39        let length_val = call.req(engine_state, stack, 0)?;
40        let length = match length_val {
41            Value::Int { val, .. } => usize::try_from(val).map_err(|_| ShellError::InvalidValue {
42                valid: "a non-negative int or filesize".into(),
43                actual: val.to_string(),
44                span: length_val.span(),
45            }),
46            Value::Filesize { val, .. } => {
47                usize::try_from(val).map_err(|_| ShellError::InvalidValue {
48                    valid: "a non-negative int or filesize".into(),
49                    actual: stack
50                        .get_config(engine_state)
51                        .filesize
52                        .format(val)
53                        .to_string(),
54                    span: length_val.span(),
55                })
56            }
57            val => Err(ShellError::RuntimeTypeMismatch {
58                expected: Type::custom("int or filesize"),
59                actual: val.get_type(),
60                span: val.span(),
61            }),
62        }?;
63
64        Ok(random_byte_stream(
65            RandomDistribution::Binary,
66            length,
67            call.head,
68            engine_state.signals().clone(),
69        ))
70    }
71
72    fn examples(&self) -> Vec<Example<'_>> {
73        vec![
74            Example {
75                description: "Generate 16 random bytes",
76                example: "random binary 16",
77                result: None,
78            },
79            Example {
80                description: "Generate 1 random kilobyte",
81                example: "random binary 1kb",
82                result: None,
83            },
84        ]
85    }
86}
87
88#[cfg(test)]
89mod test {
90    use super::*;
91
92    #[test]
93    fn test_examples() {
94        use crate::test_examples;
95
96        test_examples(RandomBinary {})
97    }
98}