hhh 1.0.1

The hhh Binary File Processor
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
// hhh
// Copyright (c) 2023 by Stacy Prowell.  All rights reserved.
// https://gitlab.com/sprowell/hhh

//! Definition of directives.

use crate::directives::{number_to_bytes, parse_directive};
use crate::options::HhhArgs;
use num::ToPrimitive;
use trivet::parse_from_string;
use trivet::parser::ParseResult;

/// Compute the number of groups that will fit on a line based on all current settings.
/// This modifies the [`HhhArgs.groups_per_line`] setting in `args`.
///
/// This presumes that [`HhhArgs.bytes_per_group`] has been set correctly in `args`, and
/// that the terminal line size is obtained correctly.  This is a static calculation, so
/// if the terminal size changes, this is not updated.  This is also a "best effort" or
/// "best guess" approach.
///
/// At least one group must be output per line.
///
pub fn set_groups(args: &mut HhhArgs) {
    // This is the fixed cost of the line.
    let mut cost = 0;

    // Add the offset, colon, and space.
    if !args.no_offset {
        cost += 8.max(args.offset_width as u16) + 2 + if args.radix_prefixes { 2 } else { 0 };
    }

    // Compute the size of one group.  We don't want to overflow, so be careful.
    let group = args.bytes_per_group as u32 * 2
        + args.group_separator.len() as u32
        + if args.radix_prefixes { 2 } else { 0 };
    if group > u16::MAX as u32 {
        // Group size is too large.  Reject and default to one group per line.
        args.groups_per_line = 1;
        return;
    }
    let group = group as u16;

    // Get the terminal line width.
    let mut line = match termsize::get() {
        None => 80,
        Some(termsize::Size { cols: value, .. }) => value,
    };

    // Subtract the fixed costs from the line width.  Be careful with underflow.
    line = line.checked_sub(cost).unwrap_or(40);

    // Compute the number of groups.
    if args.no_ascii {
        args.groups_per_line = line / group;
    } else if line < 6 {
        args.groups_per_line = 1;
    } else {
        args.groups_per_line = (line - 5) / (group + args.bytes_per_group);
    }
    args.groups_per_line = 1.max(args.groups_per_line)
}

/// The type for the closure that implements a directive.
///
/// The arguments are the mutable configuration and a (possibly empty) vector
/// of arguments.  The directive returns `None` if there are no errors,
/// and otherwise returns an error message.
///
type DirOp = fn(&mut HhhArgs, &Vec<Arg>) -> Option<String>;

/// The type for an initialization closure.  This can only accept a mutable
/// configuration, and does not permit any return value.
type DirInitOp = fn(&mut HhhArgs) -> ();

/// Define a particular directive.
#[derive(Copy, Clone, Debug)]
pub struct DirData {
    /// Directive name.
    pub name: &'static str,
    /// Is this directive used for hex input?
    pub input: bool,
    /// Is this directive used for hex output?
    pub output: bool,
    /// A closure to execute on initialization.  Use `None` if no initialization should be done.
    pub init_closure: Option<DirInitOp>,
    /// Prototype for argument list.  This is displayed to the user.
    pub prototype: &'static str,
    /// Description of the directive.  This is displayed to the user.
    pub description: &'static str,
    /// A closure to execute the directive.
    pub closure: DirOp,
}

impl DirData {
    /// Execute the closure for this directive.
    ///
    /// The usual operation of a closure is to modify the configuration.
    ///
    pub fn execute(&self, config: &mut HhhArgs, args: &Vec<Arg>) -> Option<String> {
        (self.closure)(config, args)
    }
}

/// Specify the directive names and which ones take arguments.
/// Each entry has the following elements.
///
///   * the directive name
///   * whether the directive is valid for input
///   * whether the directive is valid for output
///   * whether the directive requires an argument
///   * a user-readable description of the directive
///   * a closure to "initialize" the directive (usually set default values)
///   * a closure to "execute" the directive
///
pub const DIRECTIVES: &[DirData] = &[
    DirData {
        name: "ascii",
        input: false,
        output: true,
        prototype: "",
        init_closure: Some(|config| {
            config.no_ascii = false;
        }),
        description: "Generate an ASCII preview.",
        closure: |config, _args| {
            config.no_ascii = false;
            None
        },
    },
    DirData {
        name: "big_endian",
        input: true,
        output: true,
        prototype: "",
        init_closure: None,
        description: "When generating, encode groups in big endian order.  When parsing, assume non-prefixed \
            groups are given in big endian order and numbers should be encoded in big endian order.",
        closure: |config, _args| {
            config.little_endian = false;
            None
        },
    },
    DirData {
        name: "bytes_per_group",
        input: false,
        output: true,
        prototype: "([1-255])",
        init_closure: None,
        description: "Specify the number of bytes to include in each group on a line.",
        closure: |config, args| {
            // The grouping must be given as a number.
            if args.len() != 1 {
                return Some("bytes_per_group requires a single number argument".to_string());
            }
            match &args[0] {
                Arg::String(_) | Arg::Bytes(_) => {
                    Some("bytes_per_group requires a single number argument".to_string())
                },
                Arg::Number(num) => {
                    match num.to_u8() {
                        None => {
                            Some("maximum bytes_per_group size is 255".to_string())
                        },
                        Some(value) => {
                            if value < 1 {
                                Some("bytes_per_group cannot be zero".to_string())
                            } else {
                                config.bytes_per_group = value as u16;
                                None
                            }
                        }
                    }
                }
            }
        },
    },
    DirData {
        name: "stoic",
        input: true,
        output: false,
        prototype: "",
        init_closure: None,
        description: "Enable stoic mode.  In stoic mode any error causes the current line to be discarded and the \
            error suppressed.",
        closure: |config, _args| {
            config.stoic = true;
            None
        },
    },
    DirData {
        name: "groups_per_line",
        input: false,
        output: true,
        prototype: "([1,255])",
        init_closure: None,
        description: "Specify the number of groups to print per line.  Use zero to try to use the terminal width.",
        closure: |config, args| {
            // The number of groups in a line must be given as a number.
            if args.len() != 1 {
                return Some("groups_per_line requires a single number argument".to_string());
            }
            match &args[0] {
                Arg::String(_) | Arg::Bytes(_) => {
                    Some("groups_per_line requires a single number argument".to_string())
                },
                Arg::Number(num) => {
                    match num.to_u8() {
                        None => {
                            Some("maximum groups_per_line is 255".to_string())
                        },
                        Some(value) => {
                            if value < 1 {
                                // Guess the groups per line based on the current settings.
                                set_groups(config);
                                None
                            } else {
                                config.groups_per_line = value as u16;
                                None
                            }
                        }
                    }
                },
            }
        },
    },
    DirData {
        name: "little_endian",
        input: true,
        output: true,
        prototype: "",
        init_closure: None,
        description: "When generating, encode groups in little endian order.  When parsing, assume non-prefixed \
            groups are given in little endian order and numbers should be written in little endian order.",
        closure: |config, _args| {
            config.little_endian = true;
            None
        },
    },
    DirData {
        name: "lowercase",
        input: false,
        output: true,
        prototype: "",
        init_closure: None,
        description: "Use lower case for hexadecimal.",
        closure: |config, _args| {
            config.uppercase = false;
            None
        },
    },
    DirData {
        name: "metadata",
        input: false,
        output: true,
        prototype: "",
        init_closure: None,
        description: "Enable metadata generation.  To have an effect this must be done before any output is generated.",
        closure: |config, _args| {
            config.meta = true;
            None
        },
    },
    DirData {
        name: "no_ascii",
        input: false,
        output: true,
        prototype: "",
        init_closure: None,
        description: "Suppress the ASCII preview on output.",
        closure: |config, _args| {
            config.no_ascii = true;
            None
        },
    },
    DirData {
        name: "no_stoic",
        input: true,
        output: false,
        prototype: "",
        init_closure: None,
        description: "Disable stoic mode.  Errors are printed and halt the parse.",
        closure: |config, _args| {
            config.stoic = false;
            None
        },
    },
    DirData {
        name: "no_metadata",
        input: false,
        output: true,
        prototype: "",
        init_closure: None,
        description: "Disable metadata generation.  To have an effect this must be done before any output is \
            generated.",
        closure: |config, _args| {
            config.meta = false;
            None
        },
    },
    DirData {
        name: "no_offsets",
        input: false,
        output: true,
        prototype: "",
        init_closure: None,
        description: "Do not print the file offset at the start of a line.",
        closure: |config, _args| {
            config.no_offset = true;
            None
        },
    },
    DirData {
        name: "no_prefix",
        input: false,
        output: true,
        prototype: "",
        init_closure: None,
        description: "Do not print radix prefixes on numbers, and do not look for radix prefixes when parsing.",
        closure: |config, _args| {
            config.radix_prefixes = false;
            None
        },
    },
    DirData {
        name: "offset_limit",
        input: true,
        output: false,
        prototype: "([0..0xffff_ffff_ffff_ffff])",
        init_closure: None,
        description: "Set a hard limit on the offset to prevent creating a huge file.  By default the offset is \
            limited to a 30-bit address (1 gigabyte).  This limit is checked only when an offset is specified \
            during parsing.",
        closure: |config, args| {
            if args.len() != 1 {
                return Some("offset_limit requires a single number argument".to_string());
            }
            match &args[0] {
                Arg::String(_) | Arg::Bytes(_) => {
                    Some("offset_limit requires a single number argument".to_string())
                }
                Arg::Number(num) => {
                    match num.to_u64() {
                        None => {
                            Some("maximum offset_width is 0xffff_ffff_ffff_ffff".to_string())
                        },
                        Some(value) => {
                            config.offset_limit = value;
                            None
                        }
                    }
                }
            }
        }
    },
    DirData {
        name: "offset_width",
        input: false,
        output: true,
        prototype: "([0..255])",
        init_closure: None,
        description: "If offsets are being printed, this sets the width of the offset in hexadecimal digits.  \
            Zero turns it off, and any other number turns it on.",
        closure: |config, args| {
            // The value padding must be given as a number.
            if args.len() != 1 {
                return Some("offset_width requires a single number argument".to_string());
            }
            match &args[0] {
                Arg::String(_) | Arg::Bytes(_) => {
                    Some("offset_width requires a single number argument".to_string())
                }
                Arg::Number(num) => {
                    match num.to_u8() {
                        None => {
                            Some("maximum offset_width is 255".to_string())
                        },
                        Some(0) => {
                            config.offset_width = 8;
                            config.no_offset = true;
                            None
                        },
                        Some(value) => {
                            config.offset_width = value;
                            config.no_offset = false;
                            None
                        }
                    }
                }
            }
        },
    },
    DirData {
        name: "offsets",
        input: false,
        output: true,
        prototype: "",
        init_closure: None,
        description: "Print the current file offset at the start of each line.",
        closure: |config, _args| {
            config.no_offset = false;
            None
        },
    },
    DirData {
        name: "prefix",
        input: false,
        output: true,
        prototype: "",
        init_closure: None,
        description: "Print radix prefixes on numbers, and look for radix prefixes when parsing.",
        closure: |config, _args| {
            config.radix_prefixes = true;
            None
        },
    },
    DirData {
        name: "bias",
        input: true,
        output: true,
        prototype: "(number)",
        init_closure: None,
        description: "Set an absolute bias.  The bias is subtracted from offsets found in the file, so a bias of \
            0x1000 converts offset 0x4000 into 0x3000.",
        closure: |config, args| {
            // The absolute rebase must be given as a number.
            if args.len() != 1 {
                return Some("rebase requires a single number argument".to_string());
            }
            match &args[0] {
                Arg::String(_) | Arg::Bytes(_) => {
                    Some("rebase requires a single number argument".to_string())
                }
                Arg::Number(num) => {
                    config.bias = *num;
                    None
                }
            }
        },
    },
    DirData {
        name: "relative",
        input: true,
        output: false,
        prototype: "(number)",
        init_closure: None,
        description: "Set a relative bias using an address.  This sets the bias so that the current offset is \
            treated as the given address.  To undo this, use bias(0).",
        closure: |config, args| {
            // The relative rebase must be given as a number.
            if args.len() != 1 {
                return Some("relative requires a single number argument".to_string());
            }
            match &args[0] {
                Arg::String(_) | Arg::Bytes(_) => {
                    Some("relative requires a single number argument".to_string())
                }
                Arg::Number(num) => {
                    // Computing the correct relative offset requires that we know the current
                    // file offset, but it isn't part of the config.  In order for this to work,
                    // the caller first has to set the last offset value in the config.
                    if *num < 0 {
                        Some("relative bias requires an address and cannot be negative".to_string())
                    } else {
                        // Compute the bias that makes the last offset into the given value.
                        let bias = num - config.last_offset as i64;
                        config.bias = bias;
                        None
                    }
                }
            }
        },
    },
    DirData {
        name: "set",
        input: true,
        output: false,
        prototype: "(string,number)",
        init_closure: None,
        description: "Set a constant.  Constants are assumed to be a byte sequence of the platform's pointer size.  \
            Specify the constant's name with a string; do not use the $ form or it will be treated as an expression.",
        closure: |config, args| {
            // The constant name and value must be given.
            if args.len() != 2 {
                return Some("set requires two arguments".to_string());
            }
            let name = match &args[0] {
                Arg::String(name) => name,
                _ => return Some("first argument to set must be a string".to_string()),
            }.to_owned();
            let value = match &args[1] {
                Arg::Number(value) => value,
                _ => return Some("second argument to set must be a number".to_string()),
            };
            config.set_variable(&name, &number_to_bytes(*value, Some(usize::BITS as usize / 8), config.little_endian));
            None
        }
    },
    DirData {
        name: "set_metadata",
        input: false,
        output: true,
        prototype: "(name, value)",
        init_closure: None,
        description: "Set or suppress a metadata item.",
        closure: |config, args| {
            // The constant name and value must be given.
            if args.len() != 2 {
                return Some("set-metadata requires two arguments".to_string());
            }
            let name = match &args[0] {
                Arg::String(value) => value,
                _ => return Some("first argument to set-metadata must be a string".to_string()),
            }.to_owned();
            let value: String = match &args[1] {
                Arg::String(value) => value.clone(),
                _ => return Some("second argument to set-metadatas must be a string".to_string()),
            };
            config.set_meta.push((name, value));
            None
        },
    },
    DirData {
        name: "uppercase",
        input: false,
        output: true,
        prototype: "",
        init_closure: None,
        description: "Use upper case for hexadecimal.",
        closure: |config, _args| {
            config.uppercase = true;
            None
        },
    },
    DirData {
        name: "group_separator",
        input: true,
        output: true,
        prototype: "(string)",
        init_closure: None,
        description: "Set the group separator for hex dump generation.",
        closure: |config, args| {
            if args.len() != 1 {
                return Some("group_separator requires a single string argument".to_string());
            }
            match &args[0] {
                Arg::Number(_) | Arg::Bytes(_) => {
                    Some("group_separator requires a single string argument".to_string())
                }
                Arg::String(separator) => {
                    config.group_separator = separator.to_owned();
                    None
                }
            }
        },
    },
];

/// Represent a single argument to a directive.
#[derive(Debug, PartialEq)]
pub enum Arg {
    /// The argument is a string.
    String(String),
    /// The argument is a number.
    Number(i64),
    /// The argument is a byte string given by suffixing a number with a width.
    Bytes(Vec<u8>),
}

impl Clone for Arg {
    fn clone(&self) -> Arg {
        match self {
            Arg::String(value) => Arg::String(value.clone()),
            Arg::Number(value) => Arg::Number(*value),
            Arg::Bytes(value) => Arg::Bytes(value.clone()),
        }
    }
}

/// Represent a directive invocation.  This combines a directive name (or abbreviation) with
/// the list of actual arguments provided.  See [`Self.execute()`] to actually perform this
/// directive's action.
///
#[derive(Debug, Default, PartialEq)]
pub struct Directive {
    /// The directive name.
    pub name: String,
    /// The directive arguments.
    pub arguments: Vec<Arg>,
}

impl Directive {
    /// Try to execute the directive.  This performs lookup of the directive, where the name
    /// is allowed to be an (unambiguous) abbreviation of the directive name.
    ///
    /// The return value is `None` on success and an error message on error.
    ///
    pub fn execute(&self, config: &mut HhhArgs) -> Option<String> {
        let mut matches = vec![];
        for direct in DIRECTIVES {
            // Exact matches always win.
            if direct.name == self.name {
                matches = vec![direct];
                break;
            }

            // Check the prefix.
            if direct.name.starts_with(&self.name) {
                matches.push(direct);
            }
        }
        if matches.is_empty() {
            return Some(format!("No directive matches '{}'.", self.name));
        }
        if matches.len() > 1 {
            return Some(format!(
                "The directive '{}' is ambiguous; it might be '{}' or '{}'.",
                self.name, matches[0].name, matches[1].name
            ));
        }
        if !matches[0].prototype.is_empty() && self.arguments.is_empty() {
            return Some(format!(
                "The directive '{}' requires argument(s), but none were given.",
                self.name
            ));
        }
        if matches[0].prototype.is_empty() && !self.arguments.is_empty() {
            return Some(format!(
                "The directive '{}' does not take arguments, but arguments were given.",
                self.name
            ));
        }
        matches[0].execute(config, &self.arguments)
    }
}

/// Parse a directive from a string and then try to execute that directive.
/// On success `None` is returned, otherwise an error message is given.
pub fn parse_and_do_directive(text: &str, config: &mut HhhArgs) -> ParseResult<Option<String>> {
    let mut parser = parse_from_string(text);
    let directive = parse_directive(&mut parser, config)?;
    Ok(directive.execute(config))
}

/// Write information about available directives.
///
/// Information is written with the directive prototype, then three spaces at least, and the
/// wrapped description.  If there is not at least 20 columns for the description, then it is
/// moved to the subsequent line and indented four spaces.  If this cannot be done, then the
/// terminal size is ignored and the description width is set to 10.
pub fn directives_help() {
    // Get terminal columns.
    let mut size = termsize::get()
        .unwrap_or(termsize::Size { rows: 24, cols: 80 })
        .cols as usize;

    // The description is indented 20 characters, if possible, and then takes the remainder
    // of the column width.  That is, indent = 20 and width = size - 20.  However, if there
    // are not at least 20 columns for the description, then the sizes are changed, so that
    // indent = size - 20 and width = 20.  If this would result in a negative indent, then
    // an indent of one is used no matter what, and width = size - 1 and width is 20 no
    // matter what.
    let min_width = 30;
    if size < min_width {
        size = min_width;
    }
    let mut desc_indent = min_width;
    let mut desc_width = size - desc_indent;
    if desc_width < min_width {
        desc_indent = 1.max(size - min_width);
        desc_width = min_width;
    }

    // Figure out the maximum prototype width and wrap the description to the correct width.
    let mut output = vec![];
    for directive in DIRECTIVES {
        let proto = directive.name.to_owned() + directive.prototype;
        let mut desc = directive.description.to_string();
        desc.push(' ');
        desc.push(' ');
        if directive.input {
            desc.push('P')
        }
        if directive.output {
            desc.push('G')
        }
        desc.push(')');
        output.push((proto, desc));
    }

    println!("Directives: (P = usable during parsing, G = usable during generation)");
    for (proto, desc_str) in output {
        // There are two options.  If the prototype exceeds the min character allotment, then
        // print a newline and indent the entire description.  If it does not, then print the
        // prototype in a min column field, then print the first line of the description and
        // indent all subsequent lines.
        let desc = textwrap::wrap(&desc_str, desc_width);
        let field = format!("{} ..", proto);
        if field.len() > desc_indent {
            println!("{}", field);
            for line in &desc {
                print!("{:>1$}", "", desc_indent);
                println!("{:<1$}", line, desc_width);
            }
        } else {
            print!("{:.<1$} ", field, desc_indent - 1);
            println!("{}", desc[0]);
            for line in &desc[1..] {
                print!("{:>1$}", "", desc_indent);
                println!("{:<1$}", line, desc_width);
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::{directives_help, parse_and_do_directive, set_groups, Arg, Directive};
    use crate::options::HhhArgs;

    #[test]
    fn set_groups_test() {
        let mut args = HhhArgs::default();
        args.bytes_per_group = 3;
        args.groups_per_line = 0;
        set_groups(&mut args);
        assert!(args.groups_per_line != 0);
    }

    #[test]
    fn arg_test() {
        let mut arg = Arg::Bytes(vec![1, 2, 3, 4]);
        assert_eq!(arg, arg.clone());
        arg = Arg::Number(-376);
        assert_eq!(arg, arg.clone());
        arg = Arg::String("Freddy".to_string());
        assert_eq!(arg, arg.clone());
    }

    #[test]
    fn directive_help_test() {
        directives_help();
    }

    #[test]
    fn directive_test_1() {
        // Abbreviation tests.
        let mut args = HhhArgs::default();
        args.radix_prefixes = false;
        let mut directive = Directive {
            name: "prefi".to_string(),
            arguments: vec![],
        };
        assert!(directive.execute(&mut args).is_none());
        assert!(args.radix_prefixes);
        directive = Directive {
            name: "no_pre".to_string(),
            arguments: vec![],
        };
        assert!(directive.execute(&mut args).is_none());
        assert_eq!(args.radix_prefixes, false);

        // Not found test.
        directive = Directive {
            name: "xyzzy".to_string(),
            arguments: vec![],
        };
        assert!(directive.execute(&mut args).is_some());

        // Ambiguous test.
        directive = Directive {
            name: "no_".to_string(),
            arguments: vec![],
        };
        assert!(directive.execute(&mut args).is_some());

        // Missing arguments.
        directive = Directive {
            name: "groups_per_line".to_string(),
            arguments: vec![],
        };
        assert!(directive.execute(&mut args).is_some());

        // Unexpected arguments.
        directive = Directive {
            name: "prefix".to_string(),
            arguments: vec![Arg::String("freddy".to_string())],
        };
        assert!(directive.execute(&mut args).is_some());
    }

    #[test]
    fn parse_directive_test() {
        let mut args = HhhArgs::default();
        args.groups_per_line = 1;
        args.bytes_per_group = 1;
        args.group_separator = " ".to_string();
        args.radix_prefixes = false;
        parse_and_do_directive("groups_per_l(4)", &mut args).unwrap();
        assert_eq!(args.groups_per_line, 4);
        parse_and_do_directive("bytes_per(17)", &mut args).unwrap();
        assert_eq!(args.bytes_per_group, 17);
        parse_and_do_directive("group_separator(\";\")", &mut args).unwrap();
        assert_eq!(args.group_separator, ";");
        parse_and_do_directive("prefix", &mut args).unwrap();
        assert_eq!(args.radix_prefixes, true);
    }

    #[test]
    fn large_group_test() {
        let mut args = HhhArgs::default();
        args.bytes_per_group = 65535;
        set_groups(&mut args);
        assert_eq!(args.groups_per_line, 1);
        args.bytes_per_group = 80;
        args.no_ascii = true;
        set_groups(&mut args);
        assert_eq!(args.groups_per_line, 1);
    }
}