tzselect-rs 0.1.0

Rust port of upstream tzselect.ksh — the interactive tzdb timezone selector
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
// Awk-program ports + the interactive primitives, `include!`d into lib.rs.
// Line citations refer to tzselect.ksh (pinned tzdb-2026b, sha256 18a20b55…).

use std::collections::{BTreeSet, HashMap, HashSet};

// ===== doselect — the `select` builtin, single-column (tzselect.ksh:92-101) =====
//
// Under `COLUMNS=1`, bash's `select` lists one item per line with the index
// right-aligned to the width of the item count, prompts with PS3 ("#? "), and:
//   - a valid index in 1..=N → returns that item;
//   - an empty line → re-lists the menu;
//   - any other input → "Please enter a number in range." (no re-list);
//   - EOF → the program exits (`read … || exit`), modelled as `None`.
fn doselect(_o: &Options, h: &mut dyn Host, items: &[String]) -> Option<String> {
    let width = items.len().to_string().len();
    let mut relist = true;
    loop {
        if relist {
            for (i, it) in items.iter().enumerate() {
                h.err(&format!("{:>width$}) {}\n", i + 1, it, width = width));
            }
            relist = false;
        }
        h.err("#? ");
        let line = match h.read_line() {
            Some(l) => l,
            None => {
                // bash's `select` builtin writes a newline to STDOUT on EOF,
                // before the `|| exit` fires (the menu/prompt go to stderr).
                h.out("\n");
                return None;
            }
        };
        if line.is_empty() {
            relist = true;
            continue;
        }
        if line.bytes().all(|b| b.is_ascii_digit()) {
            if let Ok(n) = line.parse::<usize>() {
                if (1..=items.len()).contains(&n) {
                    return Some(items[n - 1].clone());
                }
            }
        }
        h.err("Please enter a number in range.\n");
    }
}

// ===== continent menu (tzselect.ksh:392-449) =====
fn ask_continent(o: &Options, h: &mut dyn Host, zonetab: &str) -> Option<String> {
    h.err("Please select a continent, ocean, \"coord\", \"TZ\", \"time\", or \"now\".\n");
    let mut items: Vec<String> = continents(zonetab);
    items.push("coord - I want to use geographical coordinates.".to_string());
    items.push("TZ - I want to specify the timezone using a proleptic TZ string.".to_string());
    items.push("time - I know local time already.".to_string());
    items.push("now - Like \"time\", but configure only for timestamps from now on.".to_string());
    let sel = doselect(o, h, &items)?;
    // continent = first whitespace word, except Americas → America (tzselect.ksh:434-442).
    let cont = if sel == "Americas" {
        "America".to_string()
    } else {
        sel.split(' ').next().unwrap_or("").to_string()
    };
    Some(cont)
}

/// Continent/ocean list (tzselect.ksh:396-421), sorted-unique (bytewise).
fn continents(zonetab: &str) -> Vec<String> {
    let mut set: BTreeSet<String> = BTreeSet::new();
    for line in zonetab.lines() {
        if line.starts_with("#@") {
            let f: Vec<&str> = line.split('\t').collect();
            for c in f.get(1).copied().unwrap_or("").split(',') {
                handle_entry(c, &mut set);
            }
        } else if !line.starts_with('#') && !line.is_empty() {
            let f: Vec<&str> = line.split('\t').collect();
            handle_entry(f.get(2).copied().unwrap_or(""), &mut set);
        }
    }
    set.into_iter().collect()
}

/// handle_entry (tzselect.ksh:397-404): first path component, America→Americas,
/// the four oceans get " Ocean".
fn handle_entry(entry: &str, set: &mut BTreeSet<String>) {
    let mut e = match entry.find('/') {
        Some(i) => entry[..i].to_string(),
        None => String::new(), // index()-1 == -1 → substr → ""
    };
    if e == "America" {
        e = "Americas".to_string();
    }
    if matches!(e.as_str(), "Arctic" | "Atlantic" | "Indian" | "Pacific") {
        e.push_str(" Ocean");
    }
    set.insert(e);
}

// ===== country list (tzselect.ksh:201-251) + sort -f =====
fn country_menu(o: &Options, h: &mut dyn Host, continent_re: &str, country_table: &str, zone_table: &str) -> Vec<String> {
    let _ = (o, &h);
    let mut names = output_country_list(continent_re, country_table, zone_table);
    sort_fold(&mut names);
    cmd_subst(names)
}

fn output_country_list(continent_re: &str, country_table: &str, zone_table: &str) -> Vec<String> {
    let mut cc_list: Vec<String> = Vec::new();
    let mut cc_seen: HashSet<String> = HashSet::new();
    let mut cc_elsewhere: HashSet<String> = HashSet::new();

    for line in zone_table.lines() {
        let commentary = line.starts_with("#@");
        let f: Vec<&str> = line.split('\t').collect();
        let (col1ccs, conts) = if commentary {
            let c1 = f.first().copied().unwrap_or("");
            let c1 = if c1.len() >= 2 { &c1[2..] } else { "" };
            (c1.to_string(), f.get(1).copied().unwrap_or("").to_string())
        } else {
            (
                f.first().copied().unwrap_or("").to_string(),
                f.get(2).copied().unwrap_or("").to_string(),
            )
        };
        let cc: Vec<&str> = col1ccs.split(',').collect();
        let cont: Vec<&str> = conts.split(',').collect();
        for code in &cc {
            let mut elsewhere = commentary;
            for c in &cont {
                if continent_matches(c, continent_re) {
                    if cc_seen.insert(code.to_string()) {
                        cc_list.push(code.to_string());
                    }
                    elsewhere = false;
                }
            }
            if elsewhere {
                for c2 in &cc {
                    cc_elsewhere.insert(c2.to_string());
                }
            }
        }
    }

    let mut cc_name: HashMap<String, String> = HashMap::new();
    for line in country_table.lines() {
        if !line.starts_with('#') {
            let f: Vec<&str> = line.split('\t').collect();
            if let (Some(code), Some(name)) = (f.first(), f.get(1)) {
                cc_name.insert(code.to_string(), name.to_string());
            }
        }
    }

    let mut out = Vec::new();
    for cc in &cc_list {
        if cc_elsewhere.contains(cc) {
            continue;
        }
        out.push(cc_name.get(cc).cloned().unwrap_or_else(|| cc.clone()));
    }
    out
}

/// `cont ~ continent_re` where continent_re is always `^<prefix>/` or `^`.
fn continent_matches(cont: &str, continent_re: &str) -> bool {
    let pat = continent_re.strip_prefix('^').unwrap_or(continent_re);
    cont.starts_with(pat)
}

/// `$1 ~ cc` — cc is a 2-letter country code (no regex metacharacters), so a
/// substring test reproduces the awk `~` for these inputs.
fn cc_matches(field1: &str, cc: &str) -> bool {
    if cc.is_empty() {
        return true; // an empty regex matches anything
    }
    field1.contains(cc)
}

// ===== country / region selection =====
/// Returns `(country_result, country)`; `country_result` is `Some` only when a
/// menu was shown. Outer `None` = EOF.
fn pick_country(o: &Options, h: &mut dyn Host, countries: &[String]) -> Option<(Option<String>, String)> {
    match countries.len() {
        0 => Some((None, String::new())),
        1 => Some((None, countries[0].clone())),
        _ => {
            h.err("Please select a country whose clocks agree with yours.\n");
            let sel = doselect(o, h, countries)?;
            Some((Some(sel.clone()), sel))
        }
    }
}

/// Regions ($4) for a country (tzselect.ksh:661-688).
fn regions_for_country(country: &str, country_table: &str, zone_table: &str) -> Vec<String> {
    let cc = country_to_cc(country, country_table);
    let mut out = Vec::new();
    for line in zone_table.lines() {
        if line.starts_with('#') {
            continue;
        }
        let f: Vec<&str> = line.split('\t').collect();
        if cc_matches(f.first().copied().unwrap_or(""), &cc) {
            out.push(f.get(3).copied().unwrap_or("").to_string());
        }
    }
    cmd_subst(out)
}

/// `tz` from country (+region) (tzselect.ksh:699-727).
fn derive_tz(country: &str, region: &str, country_table: &str, zone_table: &str) -> String {
    let cc = country_to_cc(country, country_table);
    let mut out = Vec::new();
    for line in zone_table.lines() {
        if line.starts_with('#') {
            continue;
        }
        let f: Vec<&str> = line.split('\t').collect();
        let matches_region = f.get(3).copied().unwrap_or("") == region || region.is_empty();
        if cc_matches(f.first().copied().unwrap_or(""), &cc) && matches_region {
            out.push(f.get(2).copied().unwrap_or("").to_string());
        }
    }
    cmd_subst(out).join("\n")
}

/// Map a country *name* back to its code via the country table (else the name
/// itself), as the region/tz awk does (`country == $2 → cc = $1`).
fn country_to_cc(country: &str, country_table: &str) -> String {
    for line in country_table.lines() {
        if !line.starts_with('#') {
            let f: Vec<&str> = line.split('\t').collect();
            if f.get(1).copied() == Some(country) {
                return f.first().copied().unwrap_or(country).to_string();
            }
        }
    }
    country.to_string()
}

/// `sort -f` (case-fold; ties broken by GNU sort's last-resort whole-line compare).
fn sort_fold(v: &mut [String]) {
    v.sort_by(|a, b| {
        let fa: Vec<u8> = a.bytes().map(|x| x.to_ascii_lowercase()).collect();
        let fb: Vec<u8> = b.bytes().map(|x| x.to_ascii_lowercase()).collect();
        fa.cmp(&fb).then_with(|| a.as_bytes().cmp(b.as_bytes()))
    });
}

/// Emulate `$(...)`: trailing newlines stripped (⇒ drop trailing empty fields),
/// interior empties kept; the result is the IFS=newline word list.
fn cmd_subst(mut lines: Vec<String>) -> Vec<String> {
    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
        lines.pop();
    }
    lines
}

// ===== coordinate path (tzselect.ksh:258-369, output_times unset) =====
/// Returns `(distance, "$1\t$2\t$3\t<items>")` per zone row.
fn output_distances(coord: &str, country_table: &str, zone_table: &str) -> Vec<(f64, String)> {
    // country[$1]=$2, with country["US"]="US".
    let mut country: HashMap<String, String> = HashMap::new();
    for line in country_table.lines() {
        if line.starts_with('#') {
            continue;
        }
        let f: Vec<&str> = line.split('\t').collect();
        if let (Some(code), Some(name)) = (f.first(), f.get(1)) {
            country.insert(code.to_string(), name.to_string());
        }
    }
    country.insert("US".to_string(), "US".to_string());

    // First pass: cc_used counts; collect data rows.
    let mut rows: Vec<Vec<String>> = Vec::new();
    let mut cc_used: HashMap<String, u32> = HashMap::new();
    for line in zone_table.lines() {
        if line.starts_with('#') {
            continue;
        }
        let f: Vec<String> = line.split('\t').map(|s| s.to_string()).collect();
        for c in f.first().map(|s| s.as_str()).unwrap_or("").split(',') {
            *cc_used.entry(c.to_string()).or_insert(0) += 1;
        }
        rows.push(f);
    }

    let (coord_lat, coord_long) = (convert_latitude(coord), convert_longitude(coord));
    let mut result = Vec::new();
    for f in &rows {
        let f1 = f.first().map(|s| s.as_str()).unwrap_or("");
        let f2 = f.get(1).map(|s| s.as_str()).unwrap_or("");
        let f3 = f.get(2).map(|s| s.as_str()).unwrap_or("");
        let f4 = f.get(3).map(|s| s.as_str()).unwrap_or("");
        let mut outline = format!("{f1}\t{f2}\t{f3}");
        let mut sep = "\t";
        let mut item_seen: HashSet<String> = HashSet::new();
        item_seen.insert(String::new());
        for c in f1.split(',') {
            let item = if *cc_used.get(c).unwrap_or(&0) <= 1 {
                country.get(c).cloned().unwrap_or_default()
            } else {
                f4.to_string()
            };
            if !item_seen.insert(item.clone()) {
                continue;
            }
            outline.push_str(sep);
            outline.push_str(&item);
            sep = "; ";
        }
        let here_lat = convert_latitude(f2);
        let here_long = convert_longitude(f2);
        let d = dist(coord_lat, coord_long, here_lat, here_long);
        result.push((d, outline));
    }
    result
}

fn convert_latitude(coord: &str) -> f64 {
    let (lat, _) = split_coord(coord);
    convert_coord(lat)
}
fn convert_longitude(coord: &str) -> f64 {
    let (_, long) = split_coord(coord);
    convert_coord(long)
}

/// `match(coord, /..*[-+]/)` — split at the last sign that has ≥1 char before it.
fn split_coord(coord: &str) -> (&str, &str) {
    let b = coord.as_bytes();
    let mut last = None;
    for (i, &c) in b.iter().enumerate().skip(1) {
        if c == b'-' || c == b'+' {
            last = Some(i);
        }
    }
    match last {
        // substr(coord,1,RLENGTH-1) = before the sign; substr(coord,RLENGTH) = from it.
        Some(i) => (&coord[..i], &coord[i..]),
        // No match: RLENGTH=-1 → latitude substr(,1,-2)="" (→ 0), longitude
        // substr(,-1) = the whole string (awk clamps the start to 1).
        None => ("", coord),
    }
}

const DEG_TO_RAD: f64 = 0.017453292519943296;

fn convert_coord(coord: &str) -> f64 {
    let n = awk_numf(coord);
    let digits = leading_digit_count(coord);
    let deg = if digits == 6 || digits == 7 {
        // DDMMSS
        let degminsec = n;
        let intdeg = trunc_div(degminsec, 10000.0);
        let minsec = degminsec - intdeg * 10000.0;
        let intmin = trunc_div(minsec, 100.0);
        let sec = minsec - intmin * 100.0;
        (intdeg * 3600.0 + intmin * 60.0 + sec) / 3600.0
    } else if digits == 4 || digits == 5 {
        // DDMM
        let degmin = n;
        let intdeg = trunc_div(degmin, 100.0);
        let minute = degmin - intdeg * 100.0;
        (intdeg * 60.0 + minute) / 60.0
    } else {
        n
    };
    deg * DEG_TO_RAD
}

/// `x<0 ? -int(-x/d) : int(x/d)` — truncate toward zero after dividing.
fn trunc_div(x: f64, d: f64) -> f64 {
    if x < 0.0 {
        -((-x / d).trunc())
    } else {
        (x / d).trunc()
    }
}

/// Count leading digits after an optional sign (the regex anchors of convert_coord).
fn leading_digit_count(coord: &str) -> usize {
    let b = coord.as_bytes();
    let mut i = 0;
    if i < b.len() && (b[i] == b'-' || b[i] == b'+') {
        i += 1;
    }
    let mut n = 0;
    while i < b.len() && b[i].is_ascii_digit() {
        i += 1;
        n += 1;
    }
    n
}

fn dist(lat1: f64, long1: f64, lat2: f64, long2: f64) -> f64 {
    gcdist(lat1, long1, lat2, long2) + pardist(lat1, long1, lat2, long2)
}
fn gcdist(lat1: f64, long1: f64, lat2: f64, long2: f64) -> f64 {
    let dlong = long2 - long1;
    let x = lat2.cos() * dlong.sin();
    let y = lat1.cos() * lat2.sin() - lat1.sin() * lat2.cos() * dlong.cos();
    let num = (x * x + y * y).sqrt();
    let denom = lat1.sin() * lat2.sin() + lat1.cos() * lat2.cos() * dlong.cos();
    num.atan2(denom)
}
fn pardist(lat1: f64, long1: f64, lat2: f64, long2: f64) -> f64 {
    (long1 - long2).abs() * lat1.cos().min(lat2.cos())
}

// ===== time / now path (tzselect.ksh:541-608) — time-dependent =====
fn build_time_table(h: &mut dyn Host, zone_table: &str) -> Vec<String> {
    // Reuse the output_distances outline builder, but prefix with index + date.
    let outlines = time_outlines(zone_table);
    let mut table = Vec::new();
    for (h_idx, (tz, outline)) in outlines.iter().enumerate() {
        let datestr = h
            .run_date_fmt(tz, "%Y %m %d %H:%M %a %b")
            .unwrap_or_default();
        table.push(format!("{h_idx} {datestr}\t{outline}"));
    }
    table
}

/// The (tz, outline) pairs for time mode — outline identical to coord mode.
fn time_outlines(zone_table: &str) -> Vec<(String, String)> {
    // output_times mode does NOT build the country map (tzselect.ksh:265).
    let mut rows: Vec<Vec<String>> = Vec::new();
    let mut cc_used: HashMap<String, u32> = HashMap::new();
    for line in zone_table.lines() {
        if line.starts_with('#') {
            continue;
        }
        let f: Vec<String> = line.split('\t').map(|s| s.to_string()).collect();
        for c in f.first().map(|s| s.as_str()).unwrap_or("").split(',') {
            *cc_used.entry(c.to_string()).or_insert(0) += 1;
        }
        rows.push(f);
    }
    let mut out = Vec::new();
    for f in &rows {
        let f1 = f.first().map(|s| s.as_str()).unwrap_or("");
        let f2 = f.get(1).map(|s| s.as_str()).unwrap_or("");
        let f3 = f.get(2).map(|s| s.as_str()).unwrap_or("");
        let f4 = f.get(3).map(|s| s.as_str()).unwrap_or("");
        let mut outline = format!("{f1}\t{f2}\t{f3}");
        let mut sep = "\t";
        let mut item_seen: HashSet<String> = HashSet::new();
        item_seen.insert(String::new());
        for c in f1.split(',') {
            // output_times: cc unique → country[c] (undefined → "") ; else $4.
            let item = if *cc_used.get(c).unwrap_or(&0) <= 1 {
                String::new()
            } else {
                f4.to_string()
            };
            if !item_seen.insert(item.clone()) {
                continue;
            }
            outline.push_str(sep);
            outline.push_str(&item);
            sep = "; ";
        }
        out.push((f3.to_string(), outline));
    }
    out
}

/// `$6 $7 $4 $5` (whitespace-split) — the time menu key.
fn time_key(line: &str) -> String {
    let f: Vec<&str> = line.split_whitespace().collect();
    let g = |i: usize| f.get(i).copied().unwrap_or("");
    format!("{} {} {} {}", g(5), g(6), g(3), g(4))
}

/// `sort -k2n -k2,5 -k1n` over the time table.
fn sort_time_table(table: &[String]) -> Vec<String> {
    let key = |l: &String| -> (f64, String, f64) {
        let f: Vec<&str> = l.split_whitespace().collect();
        let n = |i: usize| f.get(i).and_then(|s| s.parse::<f64>().ok()).unwrap_or(0.0);
        // -k2n: field 2 numeric; -k2,5: fields 2..=5 textual; -k1n: field 1 numeric.
        let k25 = f.get(1..5).map(|s| s.join(" ")).unwrap_or_default();
        (n(1), k25, n(0))
    };
    let mut v: Vec<String> = table.to_vec();
    v.sort_by(|a, b| {
        let (a1, a2, a3) = key(a);
        let (b1, b2, b3) = key(b);
        a1.partial_cmp(&b1)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a2.cmp(&b2))
            .then(a3.partial_cmp(&b3).unwrap_or(std::cmp::Ordering::Equal))
    });
    v
}

/// Do the seconds of two `date` outputs match? (tzselect.ksh:748-750)
fn secs_match(tzdate: &str, utdate: &str) -> bool {
    // ${X##*[0-5][0-9]:} then %%[!0-9]* — i.e. the digits right after the last
    // "MM:" group: the seconds. Compare those.
    secs_of(tzdate) == secs_of(utdate)
}
fn secs_of(d: &str) -> String {
    // strip the longest prefix ending in [0-5][0-9]: (a "MM:"), keep the rest,
    // then take its leading digits.
    let b = d.as_bytes();
    let mut cut = 0;
    let mut i = 0;
    while i + 2 < b.len() {
        if (b'0'..=b'5').contains(&b[i]) && b[i + 1].is_ascii_digit() && b[i + 2] == b':' {
            cut = i + 3;
        }
        i += 1;
    }
    let rest = &d[cut..];
    rest.bytes()
        .take_while(|c| c.is_ascii_digit())
        .map(|c| c as char)
        .collect()
}

// ===== POSIX proleptic TZ-string validator (tzselect.ksh:455-471) =====
/// Hand-parsed equivalent of the `check_POSIX_TZ_string` regex (no regex crate).
pub fn posix_tz_valid(tz: &str) -> bool {
    if tz.starts_with(':') {
        return true; // `:.*`
    }
    let b = tz.as_bytes();
    let mut p = 0;
    if !match_tzname(b, &mut p) {
        return false;
    }
    if !match_offset(b, &mut p) {
        return false;
    }
    // Optional: tzname (offset)? (datetime datetime)?
    let save = p;
    if match_tzname(b, &mut p) {
        let _ = match_offset(b, &mut p);
        let s2 = p;
        if !(match_datetime(b, &mut p) && match_datetime(b, &mut p)) {
            p = s2;
        }
    } else {
        p = save;
    }
    p == b.len()
}

fn is_alpha(c: u8) -> bool {
    c.is_ascii_alphabetic()
}
fn is_alnum_pm(c: u8) -> bool {
    c.is_ascii_alphanumeric() || c == b'+' || c == b'-'
}

/// tzname = `<[[:alnum:]+-]{3,}>` | `[[:alpha:]]{3,}`.
fn match_tzname(b: &[u8], p: &mut usize) -> bool {
    let start = *p;
    if b.get(*p) == Some(&b'<') {
        let mut q = *p + 1;
        let mut n = 0;
        while q < b.len() && is_alnum_pm(b[q]) {
            q += 1;
            n += 1;
        }
        if n >= 3 && b.get(q) == Some(&b'>') {
            *p = q + 1;
            return true;
        }
        *p = start;
        return false;
    }
    let mut q = *p;
    let mut n = 0;
    while q < b.len() && is_alpha(b[q]) {
        q += 1;
        n += 1;
    }
    if n >= 3 {
        *p = q;
        true
    } else {
        *p = start;
        false
    }
}

/// hhmm = `(:[0-5][0-9](:[0-5][0-9])?)?`.
fn match_hhmm(b: &[u8], p: &mut usize) {
    let consume = |b: &[u8], p: &mut usize| -> bool {
        if b.get(*p) == Some(&b':')
            && b.get(*p + 1).map(|c| (b'0'..=b'5').contains(c)).unwrap_or(false)
            && b.get(*p + 2).map(|c| c.is_ascii_digit()).unwrap_or(false)
        {
            *p += 3;
            true
        } else {
            false
        }
    };
    if consume(b, p) {
        let _ = consume(b, p);
    }
}

/// offset = sign `(2[0-4]|[0-1]?[0-9])` hhmm.
fn match_offset(b: &[u8], p: &mut usize) -> bool {
    let start = *p;
    if matches!(b.get(*p), Some(b'-') | Some(b'+')) {
        *p += 1;
    }
    if !match_hour_0_24(b, p) {
        *p = start;
        return false;
    }
    match_hhmm(b, p);
    true
}

/// `2[0-4]|[0-1]?[0-9]` (hours 0..=24, with optional leading 0/1).
fn match_hour_0_24(b: &[u8], p: &mut usize) -> bool {
    if b.get(*p) == Some(&b'2') && b.get(*p + 1).map(|c| (b'0'..=b'4').contains(c)).unwrap_or(false) {
        *p += 2;
        return true;
    }
    let mut q = *p;
    if matches!(b.get(q), Some(b'0') | Some(b'1')) && b.get(q + 1).map(|c| c.is_ascii_digit()).unwrap_or(false) {
        q += 1; // the optional [0-1]
    }
    if b.get(q).map(|c| c.is_ascii_digit()).unwrap_or(false) {
        *p = q + 1;
        true
    } else {
        false
    }
}

/// time = sign `(16[0-7]|(1[0-5]|[0-9]?)[0-9])` hhmm.
fn match_time(b: &[u8], p: &mut usize) -> bool {
    let start = *p;
    if matches!(b.get(*p), Some(b'-') | Some(b'+')) {
        *p += 1;
    }
    if !match_hour_0_167(b, p) {
        *p = start;
        return false;
    }
    match_hhmm(b, p);
    true
}

/// `16[0-7]|(1[0-5]|[0-9]?)[0-9]` (0..=167).
fn match_hour_0_167(b: &[u8], p: &mut usize) -> bool {
    if b.get(*p) == Some(&b'1')
        && b.get(*p + 1) == Some(&b'6')
        && b.get(*p + 2).map(|c| (b'0'..=b'7').contains(c)).unwrap_or(false)
    {
        *p += 3;
        return true;
    }
    let mut q = *p;
    // (1[0-5]|[0-9]?) then [0-9]
    if b.get(q) == Some(&b'1') && b.get(q + 1).map(|c| (b'0'..=b'5').contains(c)).unwrap_or(false) {
        q += 1;
    } else if b.get(q).map(|c| c.is_ascii_digit()).unwrap_or(false)
        && b.get(q + 1).map(|c| c.is_ascii_digit()).unwrap_or(false)
    {
        q += 1; // the optional [0-9]
    }
    if b.get(q).map(|c| c.is_ascii_digit()).unwrap_or(false) {
        *p = q + 1;
        true
    } else {
        false
    }
}

/// datetime = `,(mdate|jdate)(/time)?`.
fn match_datetime(b: &[u8], p: &mut usize) -> bool {
    let start = *p;
    if b.get(*p) != Some(&b',') {
        return false;
    }
    *p += 1;
    if !(match_mdate(b, p) || match_jdate(b, p)) {
        *p = start;
        return false;
    }
    if b.get(*p) == Some(&b'/') {
        let s = *p;
        *p += 1;
        if !match_time(b, p) {
            *p = s; // the (/time)? did not match → leave the '/' for the anchor check to reject
        }
    }
    true
}

/// mdate = `M([1-9]|1[0-2])\.[1-5]\.[0-6]`.
fn match_mdate(b: &[u8], p: &mut usize) -> bool {
    let start = *p;
    if b.get(*p) != Some(&b'M') {
        return false;
    }
    let mut q = *p + 1;
    // month 1..=12
    if b.get(q) == Some(&b'1') && b.get(q + 1).map(|c| (b'0'..=b'2').contains(c)).unwrap_or(false) {
        q += 2;
    } else if b.get(q).map(|c| (b'1'..=b'9').contains(c)).unwrap_or(false) {
        q += 1;
    } else {
        return false;
    }
    if b.get(q) != Some(&b'.') {
        return false;
    }
    q += 1;
    if !b.get(q).map(|c| (b'1'..=b'5').contains(c)).unwrap_or(false) {
        return false;
    }
    q += 1;
    if b.get(q) != Some(&b'.') {
        return false;
    }
    q += 1;
    if !b.get(q).map(|c| (b'0'..=b'6').contains(c)).unwrap_or(false) {
        *p = start;
        return false;
    }
    q += 1;
    *p = q;
    true
}

/// jdate = `(J[1-9]|[0-9]|J?[1-9][0-9]|J?[1-2][0-9][0-9])|J?3[0-5][0-9]|J?36[0-5]`.
/// Implemented as: optional `J`, then a day number whose range depends on `J`
/// (J → 1..=365, no-J → 0..=365), matched longest-first.
fn match_jdate(b: &[u8], p: &mut usize) -> bool {
    let start = *p;
    let has_j = b.get(*p) == Some(&b'J');
    let mut q = *p + usize::from(has_j);
    // Greedily take up to 3 digits, then validate the range.
    let d0 = b.get(q).copied();
    if !d0.map(|c| c.is_ascii_digit()).unwrap_or(false) {
        return false;
    }
    let mut digs = Vec::new();
    while digs.len() < 3 && b.get(q).map(|c| c.is_ascii_digit()).unwrap_or(false) {
        digs.push(b[q]);
        q += 1;
    }
    let val: i32 = std::str::from_utf8(&digs).unwrap().parse().unwrap();
    let ok = if has_j {
        (1..=365).contains(&val)
    } else {
        (0..=365).contains(&val)
    };
    // The regex forbids a leading-zero multi-digit (no rule produces "0d"/"00d"),
    // and J0 is invalid. Reject leading zero on multi-digit, and 0 for J.
    let leading_zero_multi = digs.len() > 1 && digs[0] == b'0';
    if ok && !leading_zero_multi {
        *p = q;
        true
    } else {
        *p = start;
        false
    }
}

// ===== numeric helpers =====
/// awk numeric coercion → f64 (leading optional sign + digits + optional `.frac`).
fn awk_numf(s: &str) -> f64 {
    let s = s.trim_start();
    let b = s.as_bytes();
    let mut i = 0;
    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
        i += 1;
    }
    while i < b.len() && b[i].is_ascii_digit() {
        i += 1;
    }
    if i < b.len() && b[i] == b'.' {
        i += 1;
        while i < b.len() && b[i].is_ascii_digit() {
            i += 1;
        }
    }
    s[..i].parse().unwrap_or(0.0)
}

/// C `printf "%g"` (default precision 6): 6 significant digits, trailing zeros
/// and a trailing `.` stripped, `%e`/`%f` chosen by exponent.
fn fmt_g(x: f64) -> String {
    if x == 0.0 {
        return "0".to_string();
    }
    if !x.is_finite() {
        return if x.is_nan() {
            "nan".to_string()
        } else if x < 0.0 {
            "-inf".to_string()
        } else {
            "inf".to_string()
        };
    }
    let p: i32 = 6;
    let exp = x.abs().log10().floor() as i32;
    if exp < -4 || exp >= p {
        // %e with precision p-1, then strip trailing zeros in the mantissa.
        let s = format!("{:.*e}", (p - 1) as usize, x);
        strip_e(&s)
    } else {
        let prec = (p - 1 - exp).max(0) as usize;
        let s = format!("{x:.prec$}");
        strip_f(&s)
    }
}
fn strip_f(s: &str) -> String {
    if s.contains('.') {
        let t = s.trim_end_matches('0');
        t.trim_end_matches('.').to_string()
    } else {
        s.to_string()
    }
}
fn strip_e(s: &str) -> String {
    // s like "1.234500e2"; Rust uses no leading-zero/`+` in exponent.
    if let Some(epos) = s.find('e') {
        let (mant, exp) = s.split_at(epos);
        let mant = strip_f(mant);
        format!("{mant}{exp}")
    } else {
        s.to_string()
    }
}