fastmash 0.7.1

Fast command-line statistics on text data, compatible with GNU datamash
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(clippy::undocumented_unsafe_blocks)]
// GNU Linux builds use startup's direct entry; musl and Darwin use Rust startup.
#![cfg_attr(all(not(test), target_os = "linux", target_env = "gnu"), no_main)]
#[cfg(not(any(
    all(
        target_arch = "x86_64",
        target_os = "linux",
        target_pointer_width = "64"
    ),
    all(
        target_arch = "aarch64",
        target_os = "macos",
        target_pointer_width = "64"
    ),
    all(
        target_arch = "x86_64",
        target_os = "windows",
        target_env = "msvc",
        target_pointer_width = "64"
    )
)))]
compile_error!("Fastmash builds for Linux x86-64, Apple Silicon macOS and Windows x64 MSVC");
#[cfg(all(target_os = "linux", not(any(target_env = "gnu", target_env = "musl"))))]
compile_error!("Fastmash requires glibc or musl");
mod annotated;
mod base64_fields;
mod binding;
mod boundary_exp;
mod buffered_stdout;
mod checksum;
mod collation_glibc;
mod collation_locales;
#[cfg(test)]
mod color_tests;
mod command_memory;
mod command_output;
mod command_sources;
#[cfg(test)]
mod command_test_support;
mod comparison;
#[cfg(test)]
mod comparison_tests;
#[cfg(any(windows, test))]
mod console_utf8;
mod conversion;
mod crosstab;
mod csv_input;
#[cfg(test)]
mod csv_input_tests;
mod decimal;
mod decimal_powers;
mod dispersion;
mod exp_table;
mod failure;
mod grammar;
mod grouping;
mod guarded_exp;
mod guarded_log;
mod health;
mod health_render;
#[cfg(test)]
mod health_tests;
mod help;
mod intake;
mod io_errors;
mod line_numeric;
mod locale;
mod log_cache;
mod log_table;
mod malloc_arenas;
mod mean_math;
mod moments;
mod named_fields;
mod normality;
mod numeric_contract;
mod numeric_locales;
mod numerics;
mod operation;
mod operation_set;
mod options;
mod ordered_statistics;
mod paired;
mod path_fields;
mod platform;
mod portable_numerics;
mod preparation;
#[cfg(test)]
mod preparation_tests;
mod presentation;
#[cfg(feature = "hotpath")]
mod profiling;
mod projected_sort;
mod random;
mod records;
mod replay;
mod robust_statistics;
#[cfg(test)]
mod routing_tests;
mod samples;
mod scalar_text;
mod selection;
#[cfg(test)]
mod selection_tests;
mod sort_process;
mod sort_route;
mod standard_io;
#[cfg(unix)]
mod standard_stream_io;
#[allow(unsafe_code)]
#[cfg(unix)]
mod startup;
mod table_checks;
mod table_modes;
mod terminal_style;
#[cfg(all(test, unix))]
#[path = "../tests/support/temp_dir.rs"]
mod test_dir;
#[cfg(test)]
mod test_io;
#[cfg(all(test, unix))]
#[path = "../tests/support/terminal.rs"]
mod test_terminal;
mod text_order;
mod text_samples;
mod transpose;
mod weighted;
#[cfg(test)]
mod weighted_tests;
#[cfg(windows)]
mod windows_stdio;

use crate::conversion::{field_policy, profile::Profile};
#[cfg(test)]
use failure::MESSAGE_FAILS;
use failure::{
    Failure, append, conversion_failure, failure, numeric_failure, os_failure, reported,
    unsupported, unsupported_hint,
};
use operation::Kind;
use operation_set::OperationSet;
use std::io::{self, BufRead, Write};

fn setup_sigpipe() -> Result<(), Failure> {
    #[cfg(unix)]
    {
        let mask = platform::sigpipe_mask()
            .map_err(|_| unsupported("unable to inspect runtime signal mask"))?;
        if mask & (1 << 12) != 0 {
            return Err(unsupported("blocked SIGPIPE is unsupported"));
        }
        sigpipe::reset();
    }
    Ok(())
}

/// The diagnostic for field `field` of line `line`, which has `fields` fields.
#[cold]
fn missing_field(field: u64, line: u64, fields: u64) -> Failure {
    failure(
        format!("invalid input: field {field} requested, line {line} has only {fields} fields\n")
            .into_bytes(),
    )
}

#[inline]
fn selected_field(
    record: &[u8],
    field: u64,
    line: u64,
    delimiter: records::Separator,
) -> Result<field_policy::FieldRange, Failure> {
    records::field(record, field, delimiter).map_err(|fields| missing_field(field, line, fields))
}

/// [`selected_field`] through the record's field index.
#[inline]
fn indexed_field(
    record: &[u8],
    index: &mut records::FieldIndex,
    field: u64,
    line: u64,
    delimiter: records::Separator,
) -> Result<field_policy::FieldRange, Failure> {
    index
        .field(record, field, delimiter)
        .map_err(|fields| missing_field(field, line, fields))
}

#[inline]
fn field_value(
    record: &[u8],
    index: &mut records::FieldIndex,
    field: u64,
    line: u64,
    delimiter: records::Separator,
    narm: bool,
    profile: Profile,
) -> Result<Option<numerics::Value>, Failure> {
    let span = indexed_field(record, index, field, line, delimiter)?;
    decimal::field(record, span, field, line, narm, profile)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Selector {
    Single(u64),
    Pair { left: u64, right: u64 },
}

fn integer(n: u64) -> numerics::Value {
    numerics::Numerics::promote_u64(n)
}

fn initialize_random(
    needs_random: bool,
    explicit_seed: Option<u32>,
    source: &mut impl random::SeedSource,
) -> Result<Option<random::RandomState>, Failure> {
    needs_random
        .then(|| random::RandomState::initialize(explicit_seed, source))
        .transpose()
        .map_err(|()| unsupported("unable to initialize random state"))
}

fn initialize_before_input<T>(
    needs_random: bool,
    explicit_seed: Option<u32>,
    source: &mut impl random::SeedSource,
    command_setup: impl FnOnce() -> Result<(), Failure>,
    startup: impl FnOnce() -> Result<T, Failure>,
) -> Result<(T, Option<random::RandomState>), Failure> {
    command_setup()?;
    let arithmetic = startup()?;
    let random = initialize_random(needs_random, explicit_seed, source)?;
    Ok((arithmetic, random))
}

/// What a Command reads from the process environment, read once at its
/// start: its locale and the settings that choose how it runs. The sort
/// trace (`FASTMASH_SORT_TRACE`), a diagnostic, is read where it reports.
struct Environment {
    locale: locale::Policy,
    posixly_correct: bool,
    /// `FASTMASH_GROUPING`, which only sorted Commands with Grouping keys
    /// read (and refuse when it is invalid).
    grouping: Option<std::ffi::OsString>,
    /// `FASTMASH_SORT_MEMORY_BYTES`, which only native sorts read.
    sort_memory: Option<std::ffi::OsString>,
    /// `FASTMASH_PIPE_GROUPING`, which only sorted Commands with Grouping
    /// keys read (and refuse when it is invalid).
    pipe_grouping: Option<std::ffi::OsString>,
    terminal: terminal_style::Detection,
}

impl Environment {
    fn from_env(terminal: terminal_style::Detection) -> Self {
        Self {
            locale: locale::Policy::from_env(),
            posixly_correct: std::env::var_os("POSIXLY_CORRECT").is_some(),
            grouping: std::env::var_os("FASTMASH_GROUPING"),
            sort_memory: std::env::var_os("FASTMASH_SORT_MEMORY_BYTES"),
            pipe_grouping: std::env::var_os("FASTMASH_PIPE_GROUPING"),
            terminal,
        }
    }
}

#[cfg(test)]
fn run(
    reader: &mut impl replay::Rewind,
    writer: &mut impl command_output::Transport,
    args: &[std::ffi::OsString],
    name: &[u8],
    report: &mut impl FnMut(&Failure) -> bool,
) -> Result<i32, Failure> {
    run_in(
        reader,
        writer,
        args,
        name,
        report,
        Environment::from_env(terminal_style::Detection::from_env()),
    )
}

/// [`run`] in `environment`.
#[cfg(test)]
fn run_in(
    reader: &mut impl replay::Rewind,
    writer: &mut impl command_output::Transport,
    args: &[std::ffi::OsString],
    name: &[u8],
    report: &mut impl FnMut(&Failure) -> bool,
    environment: Environment,
) -> Result<i32, Failure> {
    run_with_seed_source(
        reader,
        writer,
        args,
        name,
        report,
        &mut random::OsSeedSource,
        environment,
    )
}

#[cfg(test)]
fn run_with_seed_source(
    reader: &mut impl replay::Rewind,
    writer: &mut impl command_output::Transport,
    args: &[std::ffi::OsString],
    name: &[u8],
    report: &mut impl FnMut(&Failure) -> bool,
    seed_source: &mut impl random::SeedSource,
    environment: Environment,
) -> Result<i32, Failure> {
    run_with_sources(
        (reader, &mut command_sources::Files),
        writer,
        args,
        name,
        report,
        seed_source,
        environment,
    )
}

#[cfg(test)]
fn run_with_sources(
    input: (
        &mut impl replay::Rewind,
        &mut impl command_sources::Resolver,
    ),
    writer: &mut impl command_output::Transport,
    args: &[std::ffi::OsString],
    name: &[u8],
    report: &mut impl FnMut(&Failure) -> bool,
    seed_source: &mut impl random::SeedSource,
    environment: Environment,
) -> Result<i32, Failure> {
    let scan =
        options::scan_with_policy(args, name, environment.posixly_correct, environment.locale);
    run_scanned_with_sources(
        input,
        writer,
        (scan, environment),
        name,
        report,
        seed_source,
    )
}

/// Dispatches the same scanned Command for process and controlled transports.
/// The process resolves diagnostic styling before consuming a failed action.
#[cfg_attr(feature = "hotpath", hotpath::measure)]
fn run_scanned_with_sources(
    input: (
        &mut impl replay::Rewind,
        &mut impl command_sources::Resolver,
    ),
    writer: &mut impl command_output::Transport,
    scanned: (options::Scan, Environment),
    name: &[u8],
    report: &mut impl FnMut(&Failure) -> bool,
    seed_source: &mut impl random::SeedSource,
) -> Result<i32, Failure> {
    let (reader, sources) = input;
    let (scan, mut environment) = scanned;
    let policy = environment.locale;
    let style = environment
        .terminal
        .style(scan.color, terminal_style::Destination::Stdout);
    let action = scan.action;
    match &action {
        Ok(options::Action::Help) => {
            return help::write(writer, style)
                .map(|()| 0)
                .map_err(|e| os_failure(&e, false));
        }
        Ok(options::Action::Version) => {
            return records::write_output(
                writer,
                concat!("fastmash ", env!("CARGO_PKG_VERSION"), "\n").as_bytes(),
            )
            .map(|()| 0)
            .map_err(|e| os_failure(&e, false));
        }
        _ => {}
    }
    let profile = policy.numeric;
    let options::Action::Calculate(mut options) = action? else {
        unreachable!("informational action already handled")
    };
    options.presentation.profile = profile;
    // Data destinations stay plain even when color is explicitly forced.
    if environment.terminal.stdout_terminal {
        options.terminal = style;
    }
    options.sort_memory = environment.sort_memory.take();
    let command = grammar::command_for_format(
        &options.operands,
        options.group.as_ref(),
        options.vnlog,
        profile,
        policy.utf8,
    )?;
    if options.styled_results()
        && matches!(
            command.mode,
            grammar::Mode::Aggregate | grammar::Mode::Line | grammar::Mode::Select(_)
        )
    {
        options.header_out = true;
    }
    let (options, binding, needs, route) =
        match preparation::prepare(&mut options, command, &environment, name)? {
            preparation::Prepared::Comparison(prepared) => {
                setup_sigpipe()?;
                return comparison::run(reader, writer, sources, prepared, name, report);
            }
            preparation::Prepared::Health(prepared) => {
                setup_sigpipe()?;
                let options = prepared.into_options();
                return health::run(reader, writer, options, options.terminal, report);
            }
            preparation::Prepared::Table(prepared) => {
                let (options, mode, keys) = prepared.into_parts();
                setup_sigpipe()?;
                return table_modes::run(reader, writer, options, mode, keys, report);
            }
            preparation::Prepared::Selection(prepared) => {
                let (options, request, binding) = prepared.into_parts();
                setup_sigpipe()?;
                return selection::run(reader, writer, options, request, binding, report);
            }
            preparation::Prepared::Ordinary(prepared) => prepared.into_parts(),
        };
    let (mut arithmetic, mut random) = initialize_before_input(
        needs.random,
        options.seed,
        seed_source,
        setup_sigpipe,
        || numerics::Numerics::with(needs.numerics).map_err(numeric_failure),
    )?;
    if let Some(route) = route {
        return sort_route::run(
            route,
            reader,
            writer,
            options,
            binding,
            &mut arithmetic,
            random.as_mut(),
            report,
        );
    }
    let (capacity, line_buffered) = writer.buffering();
    let buffer = buffered_stdout::BufferedStdout::new(writer, capacity, line_buffered)
        .map_err(|e| os_failure(&e, false))?;
    let mut output = command_output::Results::new(buffer, options);
    let result = calculate(
        reader,
        &mut output,
        options,
        binding,
        &mut arithmetic,
        random.as_mut(),
        None,
    );
    Ok(command_output::complete(
        output.buffer,
        result,
        command_output::Transport::close,
        report,
    ))
}

fn calculate(
    reader: &mut (impl BufRead + ?Sized),
    output: &mut impl command_output::CommandOutput,
    options: &options::Options,
    mut binding: binding::Binding<'_>,
    arithmetic: &mut numerics::Numerics,
    random: Option<&mut random::RandomState>,
    // An Input header already read while preparing a sorted stream.
    prepared: Option<Vec<u8>>,
) -> Result<(), Failure> {
    if options.csv_in {
        return csv_input::calculate(reader, output, options, binding, arithmetic, random);
    }
    let mut random = random;
    // When the Input header was not found before sorting, GNU reads it again
    // from the sorted stream, and warns about --full only then (datamash.c
    // process_file), after the sort's own diagnostics.
    let (header, lines) = match &prepared {
        Some(_) => (intake::Header::None, 1),
        None => (intake::Header::of(options), 0),
    };
    let mut intake = intake::Intake::new(options, header)
        .after(lines)
        .warn_full(options, binding.program);
    if let Some(record) = prepared {
        output.first(&record, &binding.operations, &binding.keys)?;
    }
    let mut calculation = grouping::Calculation::new(&binding.keys, options);
    let mut spare = grouping::Raw::for_keys(binding.keys.len(), records::FieldIndex::default())?;
    // The records' field index, set up once the fields are resolved.
    let mut index = None;
    if intake.header(reader, spare.bytes_mut(), |record| {
        binding.header(record, options)
    })? {
        output.first(spare.bytes(), &binding.operations, &binding.keys)?;
    }
    if binding.keys.is_empty() && !options.full && !options.linewise {
        let mut fields = None;
        let mut any = false;
        intake.for_each(reader, spare.bytes_mut(), |record, line| {
            let bytes = record.data();
            if line == 1 {
                binding.header(bytes, options)?;
                output.first(bytes, &binding.operations, &binding.keys)?;
            }
            let fields = fields
                .get_or_insert_with(|| records::FieldIndex::selecting(binding.operations.fields()));
            fields.clear();
            binding.operations.collect(
                bytes,
                fields,
                line,
                options,
                arithmetic,
                random.as_deref_mut(),
            )?;
            any = true;
            Ok(())
        })?;
        if any {
            binding
                .operations
                .write_ungrouped_results(output, arithmetic, options)?;
        }
        output.end(options)?;
        return intake.finish();
    }
    while let Some(record) = intake.next(reader, spare.bytes_mut())? {
        let data = record.data().len();
        // Grouping keeps the data view only.
        spare.bytes_mut().truncate(data);
        let line = intake.line();
        if line == 1 {
            // Without an Input header, the first data Record binds the
            // Operations and gives a generated output header its width.
            binding.header(spare.bytes(), options)?;
            output.first(spare.bytes(), &binding.operations, &binding.keys)?;
        }
        let index = index.get_or_insert_with(|| {
            let index = records::FieldIndex::selecting(
                binding
                    .keys
                    .iter()
                    .copied()
                    .chain(binding.operations.fields()),
            );
            spare.index_fields(index.fresh());
            index
        });
        let mut context = grouping::Context::new(
            &mut binding.operations,
            &binding.keys,
            options,
            arithmetic,
            random.as_deref_mut(),
            output,
        );
        calculation.push_in_place(
            &mut spare,
            || grouping::Raw::for_keys(binding.keys.len(), index.fresh()),
            line,
            &mut context,
        )?;
    }
    let line = intake.line();
    let mut context = grouping::Context::new(
        &mut binding.operations,
        &binding.keys,
        options,
        arithmetic,
        None,
        output,
    );
    calculation.finish(line, &mut context)?;
    intake.finish()
}

fn sample_failure(kind: Kind, error: samples::Error) -> Failure {
    let reason = match error {
        #[cfg(test)]
        samples::Error::Capacity => "samples exceed 65536 values per operation per group",
        samples::Error::Allocation => "sample memory allocation failed",
        samples::Error::SortingAllocation => "sample sorting memory allocation failed",
    };
    unsupported(&format!("{} {reason}", kind.name()))
}

fn scalar_text_failure(error: scalar_text::Error) -> Failure {
    match error {
        scalar_text::Error::Allocation => unsupported("text value allocation failed"),
    }
}

fn quiet_nan() -> numerics::Value {
    numerics::canonical(crate::numeric_contract::Raw80::new(
        0x7fff,
        0xc000_0000_0000_0000,
    ))
}

/// Musl and Darwin use Rust's runtime and argument initialization.
#[cfg(all(not(test), any(target_env = "musl", target_os = "macos", windows)))]
fn main() {
    run_process();
}

/// The buffer standard input is read through: large reads keep system calls
/// off the per-record path, as GNU's stdio does with its own buffer.
const INPUT_BUFFER: usize = 128 << 10;

#[cfg_attr(test, allow(dead_code))]
fn run_process() {
    #[cfg(feature = "hotpath")]
    let profiling = match profiling::start() {
        Ok(guard) => guard,
        Err(message) => {
            let reported = writeln!(standard_io::Stderr, "fastmash: {message}").is_ok();
            let completed = standard_io::finish_stderr();
            std::process::exit(if reported && completed { 77 } else { 1 });
        }
    };
    let terminal = terminal_style::Detection::from_env();
    let args = match options::collect_args(std::env::args_os()) {
        Ok(args) => args,
        Err(error) => {
            let mut stderr = standard_io::Stderr;
            let style = terminal.style(
                terminal_style::ColorMode::Auto,
                terminal_style::Destination::Stderr,
            );
            let reported = failure::write_prefix(&mut stderr, b"fastmash", style)
                .and_then(|()| stderr.write_all(reported(&error)))
                .is_ok();
            let completed = standard_io::finish_stderr();
            #[cfg(feature = "hotpath")]
            drop(profiling);
            std::process::exit(if reported && completed {
                error.status
            } else {
                1
            });
        }
    };
    #[cfg(unix)]
    let name = args
        .first()
        .map_or(b"fastmash".as_slice(), |v| v.as_encoded_bytes());
    #[cfg(windows)]
    let name = args
        .first()
        .and_then(|name| std::path::Path::new(name).file_stem())
        .map_or(b"fastmash".as_slice(), |name| name.as_encoded_bytes());
    let mut stdin = io::BufReader::with_capacity(INPUT_BUFFER, standard_io::Stdin);
    let mut stdout = command_output::Stdout::new();
    let environment = Environment::from_env(terminal);
    // argc can be 0 (execve with an empty argv before Linux 5.18).
    let operands = args.get(1..).unwrap_or_default();
    let scan = options::scan_with_policy(
        operands,
        name,
        environment.posixly_correct,
        environment.locale,
    );
    let style = environment
        .terminal
        .style(scan.color, terminal_style::Destination::Stderr);
    let mut report = |error: &Failure| {
        let mut stderr = standard_io::Stderr;
        failure::write(&mut stderr, name, error, style).is_ok()
    };
    let result = run_scanned_with_sources(
        (&mut stdin, &mut command_sources::Files),
        &mut stdout,
        (scan, environment),
        name,
        &mut report,
        &mut random::OsSeedSource,
    );
    // The Command has completed its output, reporting any failure; a status of 1
    // may already stand for a diagnostic it could not write.
    let (mut status, mut reported_all) = match result {
        Ok(status) => (status, status != 1),
        Err(error) => (error.status, report(&error)),
    };
    #[cfg(windows)]
    if let Err(error) = platform::close(0)
        && !io_errors::bad_descriptor(error.raw_os_error())
    {
        let error = intake::read_failure(&error);
        status = failure::combine(status, error.status);
        reported_all &= report(&error);
    }
    // Standard output is still open where the Command stopped before any output.
    if let Err(error) = stdout.close()
        && !io_errors::bad_descriptor(error.raw_os_error())
    {
        let error = os_failure(&error, false);
        status = failure::combine(status, error.status);
        reported_all &= report(&error);
    }
    let stderr_completed = standard_io::finish_stderr();
    if !reported_all || !stderr_completed {
        status = 1;
    }
    if status != 0 {
        #[cfg(feature = "hotpath")]
        drop(profiling);
        std::process::exit(status);
    }
}

#[cfg(test)]
mod field_value_tests {
    use super::*;

    #[test]
    fn a_refusal_without_memory_for_its_message_still_names_its_cause() {
        let refusal = unsupported("sort memory allocation failed");
        assert_eq!(reported(&refusal), b"sort memory allocation failed\n");
        let bare = Failure {
            status: 77,
            message: Vec::new(),
            hint: None,
        };
        assert_eq!(reported(&bare), b"memory allocation failed\n");
    }

    #[test]
    fn a_hint_follows_the_cause_of_a_refusal_without_memory_for_its_message() {
        let hint = "install fastmash-sort-supervisor in the same directory as fastmash";
        MESSAGE_FAILS.with(|fails| fails.set(true));
        let error = unsupported_hint("unable to start sort supervisor", hint);
        assert_eq!(error.status, 77);
        assert_eq!(
            reported(&error),
            format!("memory allocation failed\nhint: {hint}\n").as_bytes()
        );
        let error = unsupported_hint("unable to start sort supervisor", hint);
        assert_eq!(
            reported(&error),
            format!("unable to start sort supervisor\nhint: {hint}\n").as_bytes()
        );
    }

    #[test]
    fn grouped_calculation_allocations_refuse_or_complete_exactly() {
        let args: Vec<std::ffi::OsString> = ["-g", "1", "sum", "2"]
            .into_iter()
            .map(Into::into)
            .collect();
        let (mut refusals, mut completed) = (0, false);
        for at in 0..200 {
            let mut input: &[u8] = b"a\t1\na\t2\nb\t4\n";
            let mut output = Vec::new();
            let mut reported = Vec::new();
            command_memory::FAIL_RESERVATION.with(|slot| slot.set(Some(at)));
            let result = run(&mut input, &mut output, &args, b"fastmash", &mut |error| {
                reported.push((error.status, error.message.clone()));
                true
            });
            command_memory::FAIL_RESERVATION.with(|slot| slot.set(None));
            match result {
                Ok(0) => {
                    assert_eq!(output, b"a\t3\nb\t4\n");
                    completed = true;
                    break;
                }
                Ok(status) => {
                    assert_eq!(status, 77);
                    assert_eq!(
                        reported,
                        [(77, b"command memory allocation failed\n".to_vec())]
                    );
                    refusals += 1;
                }
                Err(error) => {
                    assert_eq!(error.status, 77);
                    assert_eq!(error.message, b"command memory allocation failed\n");
                    refusals += 1;
                }
            }
        }
        assert!(completed && refusals > 0, "refusals={refusals}");
    }

    #[test]
    fn command_allocations_fail_before_publishing_partial_request_state() {
        let args: Vec<std::ffi::OsString> = ["-H", "-g", "a", "count", "a,a,a"]
            .into_iter()
            .map(Into::into)
            .collect();
        let mut failures = 0;
        let mut completed = false;
        for at in 0..100 {
            command_memory::FAIL_RESERVATION.with(|slot| slot.set(Some(at)));
            let result = (|| -> Result<(), Failure> {
                let options::Action::Calculate(options) =
                    options::parse(&args, b"fastmash", false)?
                else {
                    unreachable!()
                };
                let command = grammar::command(&options.operands, options.group.as_ref())?;
                let (_, names) = OperationSet::new(command.operations)?;
                named_fields::resolve_with(&names, b"a", options.input, options.locale.utf8)?;
                Ok(())
            })();
            command_memory::FAIL_RESERVATION.with(|slot| slot.set(None));
            match result {
                Err(error) => {
                    assert_eq!(error.status, 77);
                    assert_eq!(error.message, b"command memory allocation failed\n");
                    failures += 1;
                }
                Ok(()) => {
                    completed = true;
                    break;
                }
            }
        }
        assert!(
            completed && failures > 10,
            "failures={failures}, completed={completed}"
        );
    }

    #[test]
    fn selected_spans_distinguish_empty_fields_from_absent_columns() {
        let delimiter = records::Separator::Literal(b'\t');
        let span = selected_field(b"a\t", 2, 3, delimiter).ok().unwrap();
        assert_eq!((span.start, span.length), (2, 0));
        let error = selected_field(b"", 1, 3, delimiter).err().unwrap();
        assert_eq!(
            error.message,
            b"invalid input: field 1 requested, line 3 has only 0 fields\n"
        );
        assert!(!field_policy::is_na(b""));
        assert!(!field_policy::is_na(b"NA\0"));
        assert!(field_policy::is_na(b"n/A"));
    }

    #[test]
    fn missing_values_require_exact_whole_field_matches() {
        for word in [b"NA".as_slice(), b"na", b"N/A", b"n/a", b"NaN", b"nan"] {
            assert!(matches!(
                field_value(
                    word,
                    &mut records::FieldIndex::default(),
                    1,
                    1,
                    records::Separator::Literal(b'\t'),
                    true,
                    Profile::C
                ),
                Ok(None)
            ));
        }
        for word in [
            b" NA".as_slice(),
            b"NA ",
            b"NA\0",
            b"NAN\0tail",
            b"N/Ax",
            b"NANx",
        ] {
            assert_eq!(
                field_value(
                    word,
                    &mut records::FieldIndex::default(),
                    1,
                    1,
                    records::Separator::Literal(b'\t'),
                    true,
                    Profile::C
                )
                .err()
                .unwrap()
                .status,
                1
            );
        }
    }

    #[test]
    fn missing_values_preserve_field_errors_and_default_policy() {
        for (word, field, narm) in [
            (b"".as_slice(), 1, true),
            (b"NA".as_slice(), 2, true),
            (b"NA".as_slice(), 1, false),
        ] {
            assert_eq!(
                field_value(
                    word,
                    &mut records::FieldIndex::default(),
                    field,
                    1,
                    records::Separator::Literal(b'\t'),
                    narm,
                    Profile::C
                )
                .err()
                .unwrap()
                .status,
                1
            );
        }
    }
}

#[cfg(test)]
mod command_tests {
    use super::*;

    #[test]
    fn numeric_failures_preserve_exact_status_and_diagnostic_bytes() {
        use crate::portable_numerics::NumericFailure;
        for (cause, status, diagnostic) in [
            (
                NumericFailure::UnsupportedDomain,
                77,
                b"fastmash: numerical operation result is outside the supported domain\n"
                    .as_slice(),
            ),
            (
                NumericFailure::Capacity,
                77,
                b"fastmash: numerical arithmetic capacity exceeded\n",
            ),
            (
                NumericFailure::Allocation,
                77,
                b"fastmash: numerical arithmetic memory allocation failed\n",
            ),
            (
                NumericFailure::Invariant,
                70,
                b"fastmash: internal numerical invariant failure\n",
            ),
            (
                NumericFailure::TableIdentity,
                70,
                b"fastmash: numerical table identity check failed\n",
            ),
        ] {
            let error = numeric_failure(cause);
            assert_eq!(error.status, status, "{cause:?}");
            let prefix = b"fastmash: ";
            assert_eq!(error.message, &diagnostic[prefix.len()..], "{cause:?}");
            assert_eq!([prefix.as_slice(), &error.message].concat(), diagnostic);
        }
    }

    struct PanicSource;
    impl random::SeedSource for PanicSource {
        fn seed(&mut self) -> Result<u32, ()> {
            panic!("entropy source must not be used")
        }
    }

    #[derive(Default)]
    struct FailingSource {
        calls: usize,
    }
    impl random::SeedSource for FailingSource {
        fn seed(&mut self) -> Result<u32, ()> {
            self.calls += 1;
            Err(())
        }
    }

    #[test]
    fn conversion_failures_distinguish_capacity_allocation_and_internal_causes() {
        use crate::conversion::profile::Error;
        for (cause, message) in [
            (
                Error::InputCapacity,
                "numeric conversion input exceeds 8192-byte limit\n",
            ),
            (
                Error::OutputCapacity,
                "numeric output exceeds 16384-byte limit\n",
            ),
            (
                Error::CoefficientCapacity,
                "numeric conversion coefficient capacity exceeded\n",
            ),
            (
                Error::IntermediateCapacity,
                "numeric conversion intermediate capacity exceeded\n",
            ),
            (
                Error::PowerCapacity,
                "numeric conversion power capacity exceeded\n",
            ),
            (
                Error::ShiftCapacity,
                "numeric conversion shift capacity exceeded\n",
            ),
            (
                Error::UnsupportedProfile,
                "unsupported numerical conversion profile\n",
            ),
            (
                Error::UnsupportedFormat,
                "unsupported numerical output format\n",
            ),
            (
                Error::Allocation,
                "numeric conversion memory allocation failed\n",
            ),
            (Error::InvalidView, "internal numeric conversion failure\n"),
            (
                Error::InternalInvariant,
                "internal numeric conversion failure\n",
            ),
        ] {
            let error = conversion_failure(cause);
            assert_eq!(error.status, 77);
            assert_eq!(error.message, message.as_bytes());
        }
    }

    #[test]
    fn invocation_random_state_obeys_entropy_use_and_failure_contracts() {
        let count = OperationSet::new(grammar::parse(&args(&["count", "1"])).ok().unwrap())
            .ok()
            .unwrap()
            .0
            .needs(false)
            .random;
        assert!(
            initialize_random(count, Some(7), &mut PanicSource)
                .ok()
                .unwrap()
                .is_none()
        );

        let rand = OperationSet::new(grammar::parse(&args(&["rand", "1"])).ok().unwrap())
            .ok()
            .unwrap()
            .0
            .needs(false)
            .random;
        assert!(
            initialize_random(rand, Some(7), &mut PanicSource)
                .ok()
                .unwrap()
                .is_some()
        );
        let mut source = FailingSource::default();
        let error = initialize_random(rand, None, &mut source).err().unwrap();
        assert_eq!(source.calls, 1);
        assert_eq!(error.status, 77);
        assert_eq!(error.message, b"unable to initialize random state\n");
    }

    #[test]
    fn lifecycle_orders_runtime_and_entropy() {
        let rand = OperationSet::new(grammar::parse(&args(&["rand", "1"])).ok().unwrap())
            .ok()
            .unwrap()
            .0
            .needs(false)
            .random;
        let runtime = unsupported("runtime first");
        let error = initialize_before_input(
            rand,
            None,
            &mut PanicSource,
            || Ok(()),
            || Err::<(), _>(runtime),
        )
        .err()
        .unwrap();
        assert_eq!(error.message, b"runtime first\n");

        let mut source = FailingSource::default();
        let error = initialize_before_input(rand, None, &mut source, || Ok(()), || Ok(()))
            .err()
            .unwrap();
        assert_eq!(error.message, b"unable to initialize random state\n");
        assert_eq!(source.calls, 1);
    }

    fn args(items: &[&str]) -> Vec<std::ffi::OsString> {
        items.iter().map(std::ffi::OsString::from).collect()
    }
    #[test]
    fn selected_field_diagnostics_keep_length_and_raw_bytes() {
        for (record, field, expected) in [
            (
                b"1\tx\t9".as_slice(),
                2,
                b"invalid numeric value in line 7 field 2: 'x'\n".as_slice(),
            ),
            (
                b"1\t\xff\0tail",
                2,
                b"invalid numeric value in line 7 field 2: '\xff'\n",
            ),
            (
                b"x",
                2,
                b"invalid input: field 2 requested, line 7 has only 1 fields\n",
            ),
        ] {
            let error = field_value(
                record,
                &mut records::FieldIndex::default(),
                field,
                7,
                records::Separator::Literal(b'\t'),
                false,
                Profile::C,
            )
            .err()
            .unwrap();
            assert_eq!(error.status, 1);
            assert_eq!(error.message, expected);
        }
    }
    #[test]
    fn multi_column_short_zero_and_flush_writes() {
        struct Writer {
            data: Vec<u8>,
            zero: bool,
            fail_flush: bool,
        }
        impl Write for Writer {
            fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
                if self.zero {
                    return Ok(0);
                }
                let n = bytes.len().min(2);
                self.data.extend_from_slice(&bytes[..n]);
                Ok(n)
            }
            fn flush(&mut self) -> io::Result<()> {
                if self.fail_flush {
                    Err(crate::test_io::write(28))
                } else {
                    Ok(())
                }
            }
        }
        let row = b"12\t3\t4.5\n";
        let mut writer = Writer {
            data: vec![],
            zero: false,
            fail_flush: false,
        };
        records::write_output(&mut writer, row).unwrap();
        assert_eq!(writer.data, row);
        writer.zero = true;
        assert_eq!(
            records::write_output(&mut writer, row).unwrap_err().kind(),
            io::ErrorKind::WriteZero
        );
        writer.zero = false;
        writer.fail_flush = true;
        let error = records::write_output(&mut writer, row).unwrap_err();
        assert_eq!(
            os_failure(&error, false).message,
            b"write error: No space left on device\n"
        );
    }
}

mod headers;
mod result_names;
#[cfg(test)]
mod result_names_tests;

#[cfg(test)]
mod portable_routing_tests {
    use super::*;
    #[test]
    fn sorted_startup_retains_the_single_constructed_value() {
        let needs_random =
            OperationSet::new(grammar::parse(&["sum".into(), "1".into()]).ok().unwrap())
                .ok()
                .unwrap()
                .0
                .needs(false)
                .random;
        struct NoEntropy;
        impl random::SeedSource for NoEntropy {
            fn seed(&mut self) -> Result<u32, ()> {
                panic!("no random request")
            }
        }
        let (session, _) =
            initialize_before_input(needs_random, None, &mut NoEntropy, || Ok(()), || Ok(42u32))
                .ok()
                .unwrap();
        assert_eq!(session, 42);
    }
}

#[cfg(test)]
mod environment_tests {
    use super::*;

    /// A command's status and output in an environment of `variables`.
    fn run_with(variables: &[(&str, &str)], args: &[&str], input: &[u8]) -> (i32, Vec<u8>) {
        let get = |key: &str| {
            variables
                .iter()
                .find(|(name, _)| *name == key)
                .map(|(_, value)| std::ffi::OsString::from(value))
        };
        let environment = Environment {
            locale: locale::Policy::resolve(get),
            posixly_correct: false,
            grouping: None,
            sort_memory: None,
            pipe_grouping: None,
            terminal: Default::default(),
        };
        let args: Vec<std::ffi::OsString> = args.iter().map(Into::into).collect();
        let mut reader = io::Cursor::new(input);
        let mut output = Vec::new();
        let status = run_in(
            &mut reader,
            &mut output,
            &args,
            b"fastmash",
            &mut |_| true,
            environment,
        )
        .unwrap_or_else(|error| error.status);
        (status, output)
    }

    #[test]
    fn the_locale_comes_from_the_environment_given() {
        // German numbers: a decimal comma in and out.
        let german = [("LANG", "de_AT.UTF-8")];
        assert_eq!(
            run_with(&german, &["sum", "1"], b"1,5\n3\n"),
            (0, b"4,5\n".to_vec())
        );
        assert_eq!(run_with(&[], &["sum", "1"], b"1,5\n3\n").0, 1);
        // Language order: Spanish sorts ñ as a letter after n.
        let spanish = [("LANG", "es_ES.UTF-8")];
        let args = ["-s", "-g", "1", "count", "1"];
        assert_eq!(
            run_with(&spanish, &args, "o\nñ\nn\nnz\n".as_bytes()),
            (0, "n\t1\nnz\t1\nñ\t1\no\t1\n".as_bytes().to_vec())
        );
        // A locale whose numbers Fastmash cannot write is refused.
        assert_eq!(
            run_with(&[("LC_ALL", "fr_FR")], &["sum", "1"], b"1\n").0,
            77
        );
    }
}