Make bytes build accept integer values as individual bytes (#12685)

# Description
This creates an option for building binary data from byte integers.
Previously I think you could only do this by formatting the integers to
hex and using `decode hex`.

One potentially confusing thing is that this is different from the `into
binary` behavior. But since this doesn't support any of the other `into
binary` behaviors, it might be okay.

# User-Facing Changes
- `bytes build` accepts single byte arguments as integers

# Tests + Formatting
Example added.

# After Submitting
- [ ] release notes
This commit is contained in:
Devyn Cairns 2024-05-01 15:29:33 -07:00 committed by GitHub
parent f184a77fe1
commit 2970d48d41
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -24,14 +24,21 @@ impl Command for BytesBuild {
} }
fn examples(&self) -> Vec<Example> { fn examples(&self) -> Vec<Example> {
vec![Example { vec![
example: "bytes build 0x[01 02] 0x[03] 0x[04]", Example {
description: "Builds binary data from 0x[01 02], 0x[03], 0x[04]", example: "bytes build 0x[01 02] 0x[03] 0x[04]",
result: Some(Value::binary( description: "Builds binary data from 0x[01 02], 0x[03], 0x[04]",
vec![0x01, 0x02, 0x03, 0x04], result: Some(Value::binary(
Span::test_data(), vec![0x01, 0x02, 0x03, 0x04],
)), Span::test_data(),
}] )),
},
Example {
example: "bytes build 255 254 253 252",
description: "Builds binary data from byte numbers",
result: Some(Value::test_binary(vec![0xff, 0xfe, 0xfd, 0xfc])),
},
]
} }
fn run( fn run(
@ -46,8 +53,17 @@ impl Command for BytesBuild {
let eval_expression = get_eval_expression(engine_state); let eval_expression = get_eval_expression(engine_state);
eval_expression(engine_state, stack, expr) eval_expression(engine_state, stack, expr)
})? { })? {
let val_span = val.span();
match val { match val {
Value::Binary { mut val, .. } => output.append(&mut val), Value::Binary { mut val, .. } => output.append(&mut val),
Value::Int { val, .. } => {
let byte: u8 = val.try_into().map_err(|_| ShellError::IncorrectValue {
msg: format!("{val} is out of range for byte"),
val_span,
call_span: call.head,
})?;
output.push(byte);
}
// Explicitly propagate errors instead of dropping them. // Explicitly propagate errors instead of dropping them.
Value::Error { error, .. } => return Err(*error), Value::Error { error, .. } => return Err(*error),
other => { other => {