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: engine_state.get_config().filesize.format(val).to_string(),
50                    span: length_val.span(),
51                })
52            }
53            val => Err(ShellError::RuntimeTypeMismatch {
54                expected: Type::custom("int or filesize"),
55                actual: val.get_type(),
56                span: val.span(),
57            }),
58        }?;
59
60        Ok(random_byte_stream(
61            RandomDistribution::Binary,
62            length,
63            call.head,
64            engine_state.signals().clone(),
65        ))
66    }
67
68    fn examples(&self) -> Vec<Example> {
69        vec![
70            Example {
71                description: "Generate 16 random bytes",
72                example: "random binary 16",
73                result: None,
74            },
75            Example {
76                description: "Generate 1 random kilobyte",
77                example: "random binary 1kb",
78                result: None,
79            },
80        ]
81    }
82}
83
84#[cfg(test)]
85mod test {
86    use super::*;
87
88    #[test]
89    fn test_examples() {
90        use crate::test_examples;
91
92        test_examples(RandomBinary {})
93    }
94}