1use nu_cmd_base::input_handler::{CmdArgument, operate};
2use nu_engine::command_prelude::*;
3use nu_heavy_utils::endian::Endian;
4
5struct Arguments {
6 cell_paths: Option<Vec<CellPath>>,
7 compact: bool,
8 endian: Endian,
9}
10
11impl CmdArgument for Arguments {
12 fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
13 self.cell_paths.take()
14 }
15}
16
17#[derive(Clone)]
18pub struct IntoBinary;
19
20impl Command for IntoBinary {
21 fn name(&self) -> &str {
22 "into binary"
23 }
24
25 fn signature(&self) -> Signature {
26 Signature::build("into binary")
27 .input_output_types(vec![
28 (Type::Binary, Type::Binary),
29 (Type::Int, Type::Binary),
30 (Type::Number, Type::Binary),
31 (Type::String, Type::Binary),
32 (Type::Bool, Type::Binary),
33 (Type::Filesize, Type::Binary),
34 (Type::Duration, Type::Binary),
35 (Type::Date, Type::Binary),
36 (Type::table(), Type::table()),
37 (Type::record(), Type::record()),
38 ])
39 .allow_variants_without_examples(true) .switch("compact", "Output without padding zeros.", Some('c'))
41 .param(Endian::flag().desc(
42 "Byte encode endian. Does not affect string, date or binary. \
43 In containers, only individual elements are affected. \
44 Available options: native(default), little, big.",
45 ))
46 .rest(
47 "rest",
48 SyntaxShape::CellPath,
49 "For a data structure input, convert data at the given cell paths.",
50 )
51 .category(Category::Conversions)
52 }
53
54 fn description(&self) -> &str {
55 "Convert value to a binary primitive."
56 }
57
58 fn search_terms(&self) -> Vec<&str> {
59 vec!["convert", "bytes"]
60 }
61
62 fn run(
63 &self,
64 engine_state: &EngineState,
65 stack: &mut Stack,
66 call: &Call,
67 input: PipelineData,
68 ) -> Result<PipelineData, ShellError> {
69 into_binary(engine_state, stack, call, input)
70 }
71
72 fn examples(&self) -> Vec<Example<'_>> {
73 vec![
74 Example {
75 description: "convert string to a nushell binary primitive.",
76 example: "'This is a string that is exactly 52 characters long.' | into binary",
77 result: Some(Value::binary(
78 "This is a string that is exactly 52 characters long."
79 .to_string()
80 .as_bytes()
81 .to_vec(),
82 Span::test_data(),
83 )),
84 },
85 Example {
86 description: "convert a number to a nushell binary primitive.",
87 example: "1 | into binary",
88 result: Some(Value::binary(
89 i64::from(1).to_ne_bytes().to_vec(),
90 Span::test_data(),
91 )),
92 },
93 Example {
94 description: "convert a number to a nushell binary primitive (big endian).",
95 example: "258 | into binary --endian big",
96 result: Some(Value::binary(
97 i64::from(258).to_be_bytes().to_vec(),
98 Span::test_data(),
99 )),
100 },
101 Example {
102 description: "convert a number to a nushell binary primitive (little endian).",
103 example: "258 | into binary --endian little",
104 result: Some(Value::binary(
105 i64::from(258).to_le_bytes().to_vec(),
106 Span::test_data(),
107 )),
108 },
109 Example {
110 description: "convert a boolean to a nushell binary primitive.",
111 example: "true | into binary",
112 result: Some(Value::binary(
113 i64::from(1).to_ne_bytes().to_vec(),
114 Span::test_data(),
115 )),
116 },
117 Example {
118 description: "convert a filesize to a nushell binary primitive.",
119 example: "ls | where name == LICENSE | get size | into binary",
120 result: None,
121 },
122 Example {
123 description: "convert a filepath to a nushell binary primitive.",
124 example: "ls | where name == LICENSE | get name | path expand | into binary",
125 result: None,
126 },
127 Example {
128 description: "convert a float to a nushell binary primitive.",
129 example: "1.234 | into binary",
130 result: Some(Value::binary(
131 1.234f64.to_ne_bytes().to_vec(),
132 Span::test_data(),
133 )),
134 },
135 Example {
136 description: "convert an int to a nushell binary primitive with compact enabled.",
137 example: "10 | into binary --compact",
138 result: Some(Value::binary(vec![10], Span::test_data())),
139 },
140 Example {
141 description: "convert a duration to a nushell binary primitive.",
142 example: "1sec | into binary",
143 result: Some(Value::binary(
144 1_000_000_000i64.to_ne_bytes().to_vec(),
145 Span::test_data(),
146 )),
147 },
148 ]
149 }
150}
151
152fn into_binary(
153 engine_state: &EngineState,
154 stack: &mut Stack,
155 call: &Call,
156 input: PipelineData,
157) -> Result<PipelineData, ShellError> {
158 let head = call.head;
159 let cell_paths = call.rest(engine_state, stack, 0)?;
160 let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
161
162 if let PipelineData::ByteStream(stream, metadata) = input {
163 Ok(PipelineData::byte_stream(
165 stream.with_type(ByteStreamType::Binary),
166 metadata,
167 ))
168 } else {
169 let endian = call
170 .get_flag::<Endian>(engine_state, stack, "endian")?
171 .unwrap_or_default();
172
173 let args = Arguments {
174 cell_paths,
175 compact: call.has_flag(engine_state, stack, "compact")?,
176 endian,
177 };
178 operate(action, args, input, head, engine_state.signals())
179 }
180}
181
182fn action(input: &Value, args: &Arguments, span: Span) -> Value {
183 let value = match input {
184 Value::Binary { .. } => input.clone(),
185 Value::Int { val, .. } => Value::binary(
186 match args.endian {
187 Endian::Little => val.to_le_bytes(),
188 Endian::Big => val.to_be_bytes(),
189 }
190 .to_vec(),
191 span,
192 ),
193 Value::Float { val, .. } => Value::binary(
194 match args.endian {
195 Endian::Little => val.to_le_bytes(),
196 Endian::Big => val.to_be_bytes(),
197 }
198 .to_vec(),
199 span,
200 ),
201 Value::Filesize { val, .. } => Value::binary(
202 match args.endian {
203 Endian::Little => val.get().to_le_bytes(),
204 Endian::Big => val.get().to_be_bytes(),
205 }
206 .to_vec(),
207 span,
208 ),
209 Value::String { val, .. } => Value::binary(val.as_bytes().to_vec(), span),
210 Value::Bool { val, .. } => Value::binary(
211 {
212 let as_int = i64::from(*val);
213 match args.endian {
214 Endian::Little => as_int.to_le_bytes(),
215 Endian::Big => as_int.to_be_bytes(),
216 }
217 .to_vec()
218 },
219 span,
220 ),
221 Value::Duration { val, .. } => Value::binary(
222 match args.endian {
223 Endian::Little => val.to_le_bytes(),
224 Endian::Big => val.to_be_bytes(),
225 }
226 .to_vec(),
227 span,
228 ),
229 Value::Date { val, .. } => {
230 Value::binary(val.format("%c").to_string().as_bytes().to_vec(), span)
231 }
232 Value::Error { .. } => input.clone(),
234 other => Value::error(
235 ShellError::OnlySupportsThisInputType {
236 exp_input_type: "int, float, filesize, string, date, duration, binary, or bool"
237 .into(),
238 wrong_type: other.get_type().to_string(),
239 dst_span: span,
240 src_span: other.span(),
241 },
242 span,
243 ),
244 };
245
246 if args.compact {
247 let val_span = value.span();
248 if let Value::Binary { val, .. } = value {
249 let val = match args.endian {
250 Endian::Little => {
251 match val.iter().rposition(|&x| x != 0) {
252 Some(idx) => &val[..idx + 1],
253
254 None => &[0],
256 }
257 }
258 Endian::Big => match val.iter().position(|&x| x != 0) {
259 Some(idx) => &val[idx..],
260 None => &[0],
261 },
262 };
263
264 Value::binary(val.to_vec(), val_span)
265 } else {
266 value
267 }
268 } else {
269 value
270 }
271}
272
273#[cfg(test)]
274mod test {
275 use rstest::rstest;
276
277 use super::*;
278
279 #[test]
280 fn test_examples() -> nu_test_support::Result {
281 nu_test_support::test().examples(IntoBinary)
282 }
283
284 #[rstest]
285 #[case(vec![10], vec![10], vec![10])]
286 #[case(vec![10, 0, 0], vec![10], vec![10, 0, 0])]
287 #[case(vec![0, 0, 10], vec![0, 0, 10], vec![10])]
288 #[case(vec![0, 10, 0, 0], vec![0, 10], vec![10, 0, 0])]
289 fn test_compact(#[case] input: Vec<u8>, #[case] little: Vec<u8>, #[case] big: Vec<u8>) {
290 let s = Value::test_binary(input);
291 let actual = action(
292 &s,
293 &Arguments {
294 cell_paths: None,
295 compact: true,
296 endian: Endian::NATIVE,
297 },
298 Span::test_data(),
299 );
300 if cfg!(target_endian = "little") {
301 assert_eq!(actual, Value::test_binary(little));
302 } else {
303 assert_eq!(actual, Value::test_binary(big));
304 }
305 }
306}