nushell/crates/nu-command/src/strings/encode_decode/decode_hex.rs
uaeio d0aa69bfcb
Decode and Encode hex (#8392)
# Description

I need a command that will transform hex string into bytes and into
other direction.

I've implemented `decode hex` command and `encode hex` command. (Based
on `encode base64` and `decode base64` commands
# User-Facing Changes

```
> '010203' | decode hex
0x[01 02 03]
```

and 

```
> 0x[01 02 0a] | encode hex
'01020A'
```

---------

Co-authored-by: whiteand <andrewbeletskiy@gmail.com>
2023-03-24 12:25:26 +01:00

73 lines
1.9 KiB
Rust

use super::hex::{operate, ActionType};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value,
};
#[derive(Clone)]
pub struct DecodeHex;
impl Command for DecodeHex {
fn name(&self) -> &str {
"decode hex"
}
fn signature(&self) -> Signature {
Signature::build("decode hex")
.input_output_types(vec![(Type::String, Type::Binary)])
.vectorizes_over_list(true)
.rest(
"rest",
SyntaxShape::CellPath,
"For a data structure input, decode data at the given cell paths",
)
.category(Category::Formats)
}
fn usage(&self) -> &str {
"Hex decode a value."
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Hex decode a value and output as binary",
example: "'0102030A0a0B' | decode hex",
result: Some(Value::binary(
[0x01, 0x02, 0x03, 0x0A, 0x0A, 0x0B],
Span::test_data(),
)),
},
Example {
description: "Whitespaces are allowed to be between hex digits",
example: "'01 02 03 0A 0a 0B' | decode hex",
result: Some(Value::binary(
[0x01, 0x02, 0x03, 0x0A, 0x0A, 0x0B],
Span::test_data(),
)),
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
operate(ActionType::Decode, engine_state, stack, call, input)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
crate::test_examples(DecodeHex)
}
}