armybox 0.3.0

A memory-safe #[no_std] BusyBox/Toybox clone in Rust - 299 Unix utilities in ~500KB
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Property-based tests using proptest
//!
//! These tests verify invariants and properties that should hold
//! for all inputs, helping catch edge cases.

use proptest::prelude::*;
use std::process::{Command, Stdio};
use std::io::Write;
use tempfile::NamedTempFile;

fn armybox() -> String {
    std::env::var("ARMYBOX_PATH")
        .unwrap_or_else(|_| "./target/release/armybox".to_string())
}

// =============================================================================
// Echo Tests
// =============================================================================

proptest! {
    /// echo should output exactly what we give it (with newline)
    #[test]
    fn echo_outputs_input(s in "[a-zA-Z0-9]{1,100}") {
        let output = Command::new(armybox())
            .args(["echo", &s])
            .output()
            .unwrap();

        let stdout = String::from_utf8_lossy(&output.stdout);
        prop_assert_eq!(stdout.trim_end(), s);
    }

    /// echo -n should not add newline
    #[test]
    fn echo_n_no_newline(s in "[a-zA-Z0-9]{1,50}") {
        let output = Command::new(armybox())
            .args(["echo", "-n", &s])
            .output()
            .unwrap();

        let stdout = String::from_utf8_lossy(&output.stdout);
        prop_assert!(!stdout.ends_with('\n'));
        prop_assert_eq!(stdout.as_ref(), s);
    }
}

// =============================================================================
// Cat Tests
// =============================================================================

proptest! {
    /// cat should output file contents exactly
    #[test]
    fn cat_preserves_content(content in prop::collection::vec(any::<u8>(), 0..10000)) {
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(&content).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["cat", path])
            .output()
            .unwrap();

        prop_assert_eq!(&output.stdout, &content);
    }

    /// cat multiple files should concatenate
    #[test]
    fn cat_concatenates(
        content1 in prop::collection::vec(any::<u8>(), 1..1000),
        content2 in prop::collection::vec(any::<u8>(), 1..1000)
    ) {
        let mut temp1 = NamedTempFile::new().unwrap();
        temp1.write_all(&content1).unwrap();
        let path1 = temp1.path().to_str().unwrap().to_string();

        let mut temp2 = NamedTempFile::new().unwrap();
        temp2.write_all(&content2).unwrap();
        let path2 = temp2.path().to_str().unwrap().to_string();

        let output = Command::new(armybox())
            .args(["cat", &path1, &path2])
            .output()
            .unwrap();

        let mut expected = content1.clone();
        expected.extend(&content2);
        prop_assert_eq!(&output.stdout, &expected);
    }
}

// =============================================================================
// Head/Tail Tests
// =============================================================================

proptest! {
    /// head -n N should return at most N lines
    #[test]
    fn head_limits_lines(
        lines in prop::collection::vec("[^\n]{1,50}", 1..100),
        n in 1usize..50
    ) {
        let content = lines.join("\n") + "\n";
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(content.as_bytes()).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["head", "-n", &n.to_string(), path])
            .output()
            .unwrap();

        let stdout_str = String::from_utf8_lossy(&output.stdout);
        let output_lines: Vec<&str> = stdout_str.lines().collect();

        prop_assert!(output_lines.len() <= n);
        prop_assert!(output_lines.len() <= lines.len());
    }

    /// tail -n N should return at most N lines
    #[test]
    fn tail_limits_lines(
        lines in prop::collection::vec("[^\n]{1,50}", 1..100),
        n in 1usize..50
    ) {
        let content = lines.join("\n") + "\n";
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(content.as_bytes()).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["tail", "-n", &n.to_string(), path])
            .output()
            .unwrap();

        let stdout_str = String::from_utf8_lossy(&output.stdout);
        let output_lines: Vec<&str> = stdout_str.lines().collect();

        prop_assert!(output_lines.len() <= n);
    }
}

// =============================================================================
// WC Tests
// =============================================================================

proptest! {
    /// wc -l should count newlines correctly
    #[test]
    fn wc_counts_lines(lines in prop::collection::vec("[^\n]{0,50}", 0..100)) {
        let content = lines.join("\n");
        let expected_lines = if content.is_empty() { 0 } else { lines.len() };

        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(content.as_bytes()).unwrap();
        if !content.is_empty() {
            temp.write_all(b"\n").unwrap();
        }
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["wc", "-l", path])
            .output()
            .unwrap();

        let stdout = String::from_utf8_lossy(&output.stdout);
        let count: usize = stdout.split_whitespace()
            .next()
            .unwrap_or("0")
            .parse()
            .unwrap_or(0);

        // wc counts newlines, so it might be lines.len() or lines.len() depending on trailing newline
        prop_assert!(count == expected_lines || count == expected_lines.saturating_sub(1));
    }

    /// wc -c should count bytes correctly
    #[test]
    fn wc_counts_bytes(content in prop::collection::vec(any::<u8>(), 0..10000)) {
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(&content).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["wc", "-c", path])
            .output()
            .unwrap();

        let stdout = String::from_utf8_lossy(&output.stdout);
        let count: usize = stdout.split_whitespace()
            .next()
            .unwrap_or("0")
            .parse()
            .unwrap_or(0);

        prop_assert_eq!(count, content.len());
    }
}

// =============================================================================
// Sort Tests
// =============================================================================

proptest! {
    /// sort output should be sorted
    #[test]
    fn sort_produces_sorted_output(lines in prop::collection::vec("[a-z]{1,20}", 1..100)) {
        let content = lines.join("\n") + "\n";
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(content.as_bytes()).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["sort", path])
            .output()
            .unwrap();

        let output_lines: Vec<_> = String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(String::from)
            .collect();

        let mut sorted = output_lines.clone();
        sorted.sort();
        prop_assert_eq!(output_lines, sorted);
    }

    /// sort -n should sort numerically
    #[test]
    fn sort_numeric(numbers in prop::collection::vec(0i32..10000, 1..100)) {
        let content: String = numbers.iter()
            .map(|n| n.to_string())
            .collect::<Vec<_>>()
            .join("\n") + "\n";

        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(content.as_bytes()).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["sort", "-n", path])
            .output()
            .unwrap();

        let output_nums: Vec<i32> = String::from_utf8_lossy(&output.stdout)
            .lines()
            .filter_map(|l| l.parse().ok())
            .collect();

        let mut sorted = numbers.clone();
        sorted.sort();
        prop_assert_eq!(output_nums, sorted);
    }

    /// sort -r should reverse sort
    #[test]
    fn sort_reverse(lines in prop::collection::vec("[a-z]{1,10}", 1..50)) {
        let content = lines.join("\n") + "\n";
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(content.as_bytes()).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["sort", "-r", path])
            .output()
            .unwrap();

        let output_lines: Vec<_> = String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(String::from)
            .collect();

        let mut sorted = output_lines.clone();
        sorted.sort();
        sorted.reverse();
        prop_assert_eq!(output_lines, sorted);
    }
}

// =============================================================================
// Uniq Tests
// =============================================================================

proptest! {
    /// uniq should remove consecutive duplicates
    #[test]
    fn uniq_removes_consecutive_duplicates(
        lines in prop::collection::vec("[a-z]{1,10}", 1..50)
    ) {
        // Create input with consecutive duplicates
        let mut duplicated: Vec<String> = Vec::new();
        for line in &lines {
            duplicated.push(line.clone());
            duplicated.push(line.clone()); // Add duplicate
        }

        let content = duplicated.join("\n") + "\n";
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(content.as_bytes()).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["uniq", path])
            .output()
            .unwrap();

        let stdout_str = String::from_utf8_lossy(&output.stdout);
        let output_lines: Vec<&str> = stdout_str.lines().collect();

        // Output should have no consecutive duplicates
        for i in 1..output_lines.len() {
            prop_assert_ne!(output_lines[i], output_lines[i-1]);
        }
    }
}

// =============================================================================
// Base64 Tests
// =============================================================================

proptest! {
    /// base64 encode/decode roundtrip should preserve data
    #[test]
    fn base64_roundtrip(data in prop::collection::vec(any::<u8>(), 0..1000)) {
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(&data).unwrap();
        let path = temp.path().to_str().unwrap();

        // Encode
        let encoded = Command::new(armybox())
            .args(["base64", path])
            .output()
            .unwrap();

        if !encoded.status.success() {
            return Ok(()); // Skip if encoding failed
        }

        // Decode
        let mut encoded_file = NamedTempFile::new().unwrap();
        encoded_file.write_all(&encoded.stdout).unwrap();
        let encoded_path = encoded_file.path().to_str().unwrap();

        let decoded = Command::new(armybox())
            .args(["base64", "-d", encoded_path])
            .output()
            .unwrap();

        prop_assert_eq!(&decoded.stdout, &data);
    }
}

// =============================================================================
// Rev/Tac Tests
// =============================================================================

proptest! {
    /// rev should reverse each line
    #[test]
    fn rev_reverses_lines(lines in prop::collection::vec("[a-zA-Z0-9]{1,50}", 1..20)) {
        let content = lines.join("\n") + "\n";
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(content.as_bytes()).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["rev", path])
            .output()
            .unwrap();

        let output_string = String::from_utf8_lossy(&output.stdout);
        let output_lines: Vec<&str> = output_string.lines().collect();

        for (orig, rev) in lines.iter().zip(output_lines.iter()) {
            let expected: String = orig.chars().rev().collect();
            prop_assert_eq!(*rev, expected.as_str());
        }
    }

    /// tac should reverse line order
    #[test]
    fn tac_reverses_line_order(lines in prop::collection::vec("[a-z]{1,20}", 1..50)) {
        let content = lines.join("\n") + "\n";
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(content.as_bytes()).unwrap();
        let path = temp.path().to_str().unwrap();

        let output = Command::new(armybox())
            .args(["tac", path])
            .output()
            .unwrap();

        let output_lines: Vec<_> = String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(String::from)
            .collect();

        let mut expected = lines.clone();
        expected.reverse();
        prop_assert_eq!(output_lines, expected);
    }
}

// =============================================================================
// Checksum Tests
// =============================================================================

proptest! {
    /// checksums should be deterministic
    #[test]
    fn md5sum_deterministic(data in prop::collection::vec(any::<u8>(), 0..10000)) {
        let mut temp = NamedTempFile::new().unwrap();
        temp.write_all(&data).unwrap();
        let path = temp.path().to_str().unwrap();

        let output1 = Command::new(armybox())
            .args(["md5sum", path])
            .output()
            .unwrap();

        let output2 = Command::new(armybox())
            .args(["md5sum", path])
            .output()
            .unwrap();

        prop_assert_eq!(output1.stdout, output2.stdout);
    }

    /// different data should produce different checksums (with high probability)
    #[test]
    fn md5sum_different_for_different_input(
        data1 in prop::collection::vec(any::<u8>(), 10..1000),
        data2 in prop::collection::vec(any::<u8>(), 10..1000)
    ) {
        prop_assume!(data1 != data2);

        let mut temp1 = NamedTempFile::new().unwrap();
        temp1.write_all(&data1).unwrap();
        let path1 = temp1.path().to_str().unwrap();

        let mut temp2 = NamedTempFile::new().unwrap();
        temp2.write_all(&data2).unwrap();
        let path2 = temp2.path().to_str().unwrap();

        let output1 = Command::new(armybox())
            .args(["md5sum", path1])
            .output()
            .unwrap();

        let output2 = Command::new(armybox())
            .args(["md5sum", path2])
            .output()
            .unwrap();

        // Extract just the hash (first field)
        let stdout1 = String::from_utf8_lossy(&output1.stdout);
        let hash1 = stdout1.split_whitespace().next().unwrap_or("");
        let stdout2 = String::from_utf8_lossy(&output2.stdout);
        let hash2 = stdout2.split_whitespace().next().unwrap_or("");

        prop_assert_ne!(hash1, hash2);
    }
}

// =============================================================================
// Compression Roundtrip Tests
// =============================================================================

proptest! {
    /// gzip/gunzip roundtrip should preserve data
    #[test]
    fn gzip_roundtrip(data in prop::collection::vec(any::<u8>(), 1..10000)) {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let input_path = temp_dir.path().join("input");
        std::fs::write(&input_path, &data).unwrap();

        // Compress
        let status = Command::new(armybox())
            .args(["gzip", "-k", input_path.to_str().unwrap()])
            .status()
            .unwrap();

        if !status.success() {
            return Ok(());
        }

        let gz_path = format!("{}.gz", input_path.to_str().unwrap());

        // Decompress
        let output = Command::new(armybox())
            .args(["zcat", &gz_path])
            .output()
            .unwrap();

        prop_assert_eq!(&output.stdout, &data);
    }
}