from2to 0.5.0

Fast conversion at the terminal: hex2bin, dec2char, hex2b64, and friends
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
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
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
//! Decoding, converting and encoding.
//!
//! Three paths matter, in order of how often they run:
//!
//! 1. Both sides are powers of two (`hex2bin`, `hex2b64`, `bin2oct`): pure bit
//!    regrouping. No bignum, O(n), and leading zeros survive for free.
//! 2. The value fits in `u128`: the common case for a stream of small numbers,
//!    which is what `dec2char` sees.
//! 3. Anything else: `BigUint`.

use crate::endian::{Endian, swap_words};
use crate::expr;
use crate::format::Format;
use data_encoding::{BASE32, BASE32HEX, BASE32HEX_NOPAD, BASE32_NOPAD, BASE64, BASE64URL,
                    BASE64URL_NOPAD, BASE64_NOPAD, Encoding};
use num_bigint::{BigInt, BigUint, Sign};
use std::fmt;

const DIGITS: &[u8; 36] = b"0123456789abcdefghijklmnopqrstuvwxyz";

fn digit_char(d: u8) -> char {
    DIGITS[d as usize] as char
}

// ---------------------------------------------------------------- errors

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConvError {
    BadDigit { token: String, ch: char, base: u32 },
    EmptyToken,
    NotACodepoint { token: String },
    NotAByte { token: String },
    BadEncoding { format: String, detail: String },
    /// A byte order was asked for where no byte width can be worked out.
    NoByteWidth { format: String },
    /// A byte order was asked for on code points, which are not bytes.
    EndianNeedsBytes,
    /// A token's digits do not add up to a whole number of bytes.
    NotWholeBytes { token: String, base: u32 },
    /// A run of bytes is not a whole number of `--word` sized words.
    RaggedWord { len: usize, word: usize },
    /// A value needs more room than the word size allows.
    TooWide { token: String, want: usize },
    /// An expression that could not be parsed or evaluated.
    BadExpr { text: String, detail: crate::expr::ExprError },
    /// A negative result reaching somewhere that has no way to say so.
    NegativeResult { text: String, wher: String },
}

impl fmt::Display for ConvError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConvError::BadDigit { token, ch, base } => {
                write!(f, "'{token}' is not valid base {base} (bad digit '{ch}')")
            }
            ConvError::EmptyToken => write!(f, "empty input token"),
            ConvError::NotACodepoint { token } => {
                write!(f, "'{token}' is not a Unicode code point")
            }
            ConvError::NotAByte { token } => write!(f, "'{token}' does not fit in a byte"),
            ConvError::BadEncoding { format, detail } => {
                write!(f, "invalid {format} input: {detail}")
            }
            ConvError::NoByteWidth { format } => {
                write!(f, "{format} carries no byte width of its own; say how wide the word is: --word 4")
            }
            ConvError::EndianNeedsBytes => {
                write!(f, "byte order applies to bytes, but char is being read as code points here; add --bytes")
            }
            ConvError::NotWholeBytes { token, base } => {
                write!(f, "'{token}' is not a whole number of bytes in base {base}; pad it or add --word")
            }
            ConvError::RaggedWord { len, word } => {
                write!(f, "{len} bytes is not a whole number of {word}-byte words")
            }
            ConvError::TooWide { token, want } => {
                write!(f, "'{token}' does not fit in {want} bytes")
            }
            ConvError::BadExpr { text, detail } => write!(f, "'{text}': {detail}"),
            ConvError::NegativeResult { text, wher } => write!(
                f,
                "'{text}' is negative, and {wher} cannot express that; \
                 add --word N to wrap it to N bytes"
            ),
        }
    }
}

impl std::error::Error for ConvError {}

// ---------------------------------------------------------------- magnitude

/// An arbitrary-precision unsigned integer that stays on the stack while it can.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Mag {
    Small(u128),
    Big(BigUint),
}

impl Mag {
    fn mul_add(&mut self, base: u32, digit: u8) {
        match self {
            Mag::Small(v) => {
                match v
                    .checked_mul(base as u128)
                    .and_then(|x| x.checked_add(digit as u128))
                {
                    Some(next) => *v = next,
                    None => {
                        let mut b = BigUint::from(*v);
                        b *= base;
                        b += digit;
                        *self = Mag::Big(b);
                    }
                }
            }
            Mag::Big(b) => {
                *b *= base;
                *b += digit;
            }
        }
    }

    fn to_str_radix(&self, base: u32) -> String {
        match self {
            Mag::Small(v) => small_to_radix(*v, base),
            Mag::Big(b) => b.to_str_radix(base),
        }
    }

    /// Big-endian bytes, minimal length (a single `0` for zero).
    fn to_bytes_be(&self) -> Vec<u8> {
        match self {
            Mag::Small(0) => vec![0],
            Mag::Small(v) => {
                let bytes = v.to_be_bytes();
                let first = bytes.iter().position(|&b| b != 0).unwrap();
                bytes[first..].to_vec()
            }
            Mag::Big(b) => b.to_bytes_be(),
        }
    }

    fn to_u32(&self) -> Option<u32> {
        match self {
            Mag::Small(v) => u32::try_from(*v).ok(),
            // Anything that overflowed u128 is far past u32.
            Mag::Big(_) => None,
        }
    }
}

fn small_to_radix(mut v: u128, base: u32) -> String {
    if v == 0 {
        return "0".to_string();
    }
    let base = base as u128;
    let mut buf = Vec::new();
    while v > 0 {
        buf.push(digit_char((v % base) as u8));
        v /= base;
    }
    buf.iter().rev().collect()
}

// ---------------------------------------------------------------- numbers

/// A number as it was written: the digit values, plus the base they were in.
///
/// Keeping the digits rather than collapsing straight to a value is what makes
/// the power-of-two path possible and what preserves leading zeros.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Num {
    digits: Vec<u8>,
    base: u32,
    /// Set only by an expression result; digits somebody wrote are unsigned.
    neg: bool,
    /// The original text, kept only for error messages.
    text: String,
}

impl Num {
    /// The magnitude, which says nothing about the sign — callers must consult
    /// `neg` themselves. Forgetting to is how a negative silently renders as a
    /// positive, which is the one failure this whole feature must not have.
    fn to_mag(&self) -> Mag {
        let mut m = Mag::Small(0);
        for &d in &self.digits {
            m.mul_add(self.base, d);
        }
        m
    }

    fn bits_per_digit(&self) -> Option<u32> {
        self.base.is_power_of_two().then(|| self.base.trailing_zeros())
    }
}

/// Regroup a digit sequence from one power-of-two base into another, producing
/// exactly `out_len` digits.
///
/// Shorter output than the input's bit length is only ever requested when the
/// dropped leading bits are known to be zero.
fn regroup_to(digits: &[u8], from_bits: u32, to_bits: u32, out_len: usize) -> Vec<u8> {
    let total_in = digits.len() * from_bits as usize;
    let out_bits = out_len * to_bits as usize;
    let pad = out_bits.saturating_sub(total_in);
    let skip = total_in.saturating_sub(out_bits);

    let bits = std::iter::repeat_n(0u8, pad)
        .chain(
            digits
                .iter()
                .flat_map(|&d| (0..from_bits).rev().map(move |i| (d >> i) & 1)),
        )
        .skip(skip);

    let mut out = Vec::with_capacity(out_len);
    let mut cur = 0u8;
    let mut have = 0u32;
    for bit in bits {
        cur = (cur << 1) | bit;
        have += 1;
        if have == to_bits {
            out.push(cur);
            cur = 0;
            have = 0;
        }
    }
    out
}

/// How many bytes a number should occupy, given how it was written.
///
/// For a power-of-two base the written digit count carries real width
/// information (`00706963` is four bytes, not three), so honour it — but never
/// go below what the value actually needs.
fn byte_width(n: &Num, minimal: usize) -> usize {
    match n.bits_per_digit() {
        Some(bits) => minimal.max(n.digits.len() * bits as usize / 8),
        None => minimal,
    }
}

// ---------------------------------------------------------------- options

#[derive(Debug, Clone, Default)]
pub struct Options {
    pub width: Option<usize>,
    pub no_width: bool,
    pub group: Option<usize>,
    pub upper: bool,
    pub prefix: bool,
    pub delim: Option<String>,
    /// `Some(true)` forces byte semantics, `Some(false)` forces code points.
    pub bytes_mode: Option<bool>,
    pub strict: bool,
    /// Skip tokens that fail to convert instead of aborting.
    pub keep_going: bool,
    /// Byte order of the input and of the output. `Big` on both sides is the
    /// identity, and is checked for explicitly so that every conversion that
    /// existed before byte order did still takes the same code path.
    pub from_endian: Endian,
    pub to_endian: Endian,
    /// Bytes per word for the byte-order swap. `None` means "the whole value".
    pub word: Option<usize>,
}

// ---------------------------------------------------------------- decoding

/// Strip the leniency affordances: a base-appropriate prefix and `_` spacers.
///
/// Shared with `detect`, which has to accept exactly what this accepts or it
/// would rule out inputs the converter would have handled.
pub(crate) fn clean_token<'a>(tok: &'a str, base: u32, strict: bool) -> std::borrow::Cow<'a, str> {
    if strict {
        return std::borrow::Cow::Borrowed(tok);
    }
    let prefix = match base {
        2 => "0b",
        8 => "0o",
        10 => "0d",
        16 => "0x",
        _ => "",
    };
    let mut s = tok;
    if !prefix.is_empty()
        && s.len() > prefix.len()
        && s.get(..2).is_some_and(|p| p.eq_ignore_ascii_case(prefix))
    {
        s = &s[2..];
    }
    if s.contains('_') {
        std::borrow::Cow::Owned(s.replace('_', ""))
    } else {
        std::borrow::Cow::Borrowed(s)
    }
}

fn decode_num(tok: &str, base: u32, strict: bool) -> Result<Num, ConvError> {
    let cleaned = clean_token(tok, base, strict);
    if cleaned.is_empty() {
        return Err(ConvError::EmptyToken);
    }
    let mut digits = Vec::with_capacity(cleaned.len());
    for ch in cleaned.chars() {
        match ch.to_digit(base) {
            Some(d) => digits.push(d as u8),
            None => {
                return Err(ConvError::BadDigit {
                    token: tok.to_string(),
                    ch,
                    base,
                });
            }
        }
    }
    Ok(Num {
        digits,
        base,
        neg: false,
        text: tok.to_string(),
    })
}

fn encoding_for(f: Format, padded: bool) -> Encoding {
    match (f, padded) {
        (Format::B64, true) => BASE64,
        (Format::B64, false) => BASE64_NOPAD,
        (Format::B64Url, true) => BASE64URL,
        (Format::B64Url, false) => BASE64URL_NOPAD,
        (Format::B32, true) => BASE32,
        (Format::B32, false) => BASE32_NOPAD,
        (Format::B32Hex, true) => BASE32HEX,
        (Format::B32Hex, false) => BASE32HEX_NOPAD,
        _ => unreachable!("not an encoding format"),
    }
}

/// Decode base64/base32 text, tolerating missing padding and (for base32)
/// lowercase input, which real-world CTF strings routinely have.
fn decode_encoding(text: &str, f: Format, strict: bool) -> Result<Vec<u8>, ConvError> {
    let mut s: String = text.chars().filter(|c| !c.is_whitespace()).collect();
    if !strict && matches!(f, Format::B32 | Format::B32Hex) {
        s = s.to_ascii_uppercase();
    }
    if let Ok(bytes) = encoding_for(f, true).decode(s.as_bytes()) {
        return Ok(bytes);
    }
    if !strict {
        let trimmed = s.trim_end_matches('=');
        if let Ok(bytes) = encoding_for(f, false).decode(trimmed.as_bytes()) {
            return Ok(bytes);
        }
    }
    // Re-run the strict decode purely to get a useful error message.
    let err = encoding_for(f, true).decode(s.as_bytes()).unwrap_err();
    Err(ConvError::BadEncoding {
        format: f.name().to_string(),
        detail: err.to_string(),
    })
}

// ---------------------------------------------------------------- escaped hex

/// Render bytes as `\x48\x65` — every byte escaped, always.
///
/// Never "printable as-is, the rest escaped" the way Python's `repr` does it:
/// that spelling is ambiguous about whether a literal backslash was data, and
/// it makes the output depend on the content. Uniform escaping round-trips.
fn encode_esc(bytes: &[u8], upper: bool) -> String {
    let mut out = String::with_capacity(bytes.len() * 4);
    for &b in bytes {
        out.push_str("\\x");
        out.push(digit_char(b >> 4));
        out.push(digit_char(b & 0x0f));
    }
    if upper { out.to_uppercase().replace("\\X", "\\x") } else { out }
}

/// The single-character escapes worth understanding on the way in.
///
/// Only ever *read*, never written: a payload lifted out of a real script has
/// `\r\n` in it, and refusing that would be pedantry.
const SHORT_ESCAPES: [(char, u8); 7] = [
    ('n', b'\n'), ('r', b'\r'), ('t', b'\t'), ('0', 0),
    ('\\', b'\\'), ('\'', b'\''), ('"', b'"'),
];

/// Whether an escaped-hex reading holds together, for the detector.
///
/// Shared rather than reimplemented so the two can never disagree about
/// what counts as valid — the detector must not offer a reading that the
/// converter would then refuse.
pub(crate) fn decode_esc_ok(text: &str) -> bool {
    decode_esc(text, false).is_ok()
}

/// Parse `\x48`, the short escapes, and — unless `strict` — literal text.
///
/// Mixed input is the common case, not an edge case: `GET /\r\n` is exactly
/// what you copy out of an exploit script, and every byte of it is meant.
fn decode_esc(text: &str, strict: bool) -> Result<Vec<u8>, ConvError> {
    let bad = |detail: String| ConvError::BadEncoding { format: "esc".to_string(), detail };
    let mut out = Vec::with_capacity(text.len() / 4);
    let mut chars = text.chars().peekable();

    while let Some(c) = chars.next() {
        if c != '\\' {
            if strict && !c.is_whitespace() {
                return Err(bad(format!("expected an escape, found '{c}'")));
            }
            if !strict {
                let mut buf = [0u8; 4];
                out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
            }
            continue;
        }
        match chars.next() {
            Some('x') | Some('X') => {
                let mut v = 0u8;
                for i in 0..2 {
                    match chars.next().and_then(|h| h.to_digit(16)) {
                        Some(d) => v = (v << 4) | d as u8,
                        None => {
                            return Err(bad(format!(
                                "\\x needs two hex digits, found {i}"
                            )));
                        }
                    }
                }
                out.push(v);
            }
            Some(e) => match SHORT_ESCAPES.iter().find(|(k, _)| *k == e) {
                Some(&(_, b)) if !strict => out.push(b),
                _ => return Err(bad(format!("unknown escape '\\{e}'"))),
            },
            None => return Err(bad("trailing backslash".to_string())),
        }
    }
    Ok(out)
}

// ---------------------------------------------------------------- converter

/// A configured conversion. Built once, then fed input.
pub struct Converter {
    pub from: Format,
    pub to: Format,
    pub opts: Options,
}

impl Converter {
    pub fn new(from: Format, to: Format, opts: Options) -> Self {
        Converter { from, to, opts }
    }

    /// True when output cannot be emitted incrementally.
    ///
    /// base64/base32 output has to see the whole byte stream before it can
    /// place its padding, so those conversions buffer to EOF. Everything else
    /// streams, which is what makes `nc host port | dec2char` print live.
    pub fn buffers_output(&self) -> bool {
        self.to.is_encoding() || self.swap_needs_whole_input()
    }

    /// True when a byte-order swap has to see the whole input at once.
    ///
    /// A swap over a *run* of bytes has no token boundaries to work with, so
    /// reading it a line at a time would reverse each line independently —
    /// a wrong answer, not merely a slow one. A swap inside a positional token
    /// is safe, because a token is complete before it is converted.
    ///
    /// What decides it is the **source**, not whichever side wears the `le`:
    /// the source is what determines whether `reorder` sees one byte run or a
    /// list of tokens. `char2lehex` swaps a run even though its `le` is on the
    /// hex side, so it has to buffer.
    fn swap_needs_whole_input(&self) -> bool {
        (self.opts.from_endian.is_little() || self.opts.to_endian.is_little())
            && self.from.is_byteish()
    }

    /// Reject a configuration that cannot mean anything, before reading input.
    ///
    /// A byte order needs a byte width. A run of bytes is its own width, and a
    /// byte-aligned base writes a known number of digits per byte — but base
    /// 10 and base 8 carry no width at all, and inferring one from the value
    /// would make the word size depend on the value. That is how a swap
    /// silently produces the wrong address, so it is an error instead.
    pub fn check(&self) -> Result<(), ConvError> {
        if !self.opts.from_endian.is_little() && !self.opts.to_endian.is_little() {
            return Ok(());
        }
        if self.opts.word.is_some_and(|w| w > 0) {
            return Ok(());
        }
        if self.from.is_byteish() || self.from.byte_aligned() {
            return Ok(());
        }
        Err(ConvError::NoByteWidth { format: self.from.to_string() })
    }

    /// Whether input arrives as tokens (positional) or as an opaque run of
    /// text/bytes (`char`, base64, base32).
    pub fn tokenizes_input(&self) -> bool {
        self.from.is_positional()
    }

    /// Should a `char` endpoint be treated as bytes rather than code points?
    ///
    /// Powers of two carry byte structure (`hex2char 706963` is "pic"), while
    /// base 10 does not, so a decimal token is a code point (`dec2char 128512`
    /// is an emoji). `--bytes` / `--codepoint` override this.
    fn char_is_bytes(&self) -> bool {
        let other = if self.from == Format::Char { self.to } else { self.from };
        self.opts.bytes_mode.unwrap_or_else(|| {
            other.is_byteish() || other.bits_per_digit().is_some()
        })
    }

    /// The separator between results, when the caller hasn't chosen one.
    pub fn default_delim(&self) -> &'static str {
        if !self.to.is_positional() {
            // char/b64/b32 output is a single run: joining is the whole point.
            ""
        } else if self.from.is_byteish() {
            // Byte-sourced numbers: xxd-style for hex/bin/oct, spaced for base 10.
            if self.to.bits_per_digit().is_some() { "" } else { " " }
        } else {
            "\n"
        }
    }

    /// The separator actually in use, honouring `--delim` / `--join`.
    pub fn delim(&self) -> &str {
        self.opts.delim.as_deref().unwrap_or_else(|| self.default_delim())
    }

    /// True when input can be processed a line at a time and written straight
    /// out. base64 and base32 need the whole stream at either end.
    pub fn can_stream(&self) -> bool {
        !self.from.is_encoding() && !self.to.is_encoding() && !self.swap_needs_whole_input()
    }

    // ---- number formatting

    fn finish_digits(&self, mut s: String, natural_width: bool) -> String {
        let explicit = self.opts.width.is_some();
        if (self.opts.no_width || explicit) && natural_width {
            let trimmed = s.trim_start_matches('0');
            s = if trimmed.is_empty() { "0".to_string() } else { trimmed.to_string() };
        }
        if let Some(w) = self.opts.width.filter(|w| s.len() < *w) {
            s = "0".repeat(w - s.len()) + &s;
        }
        if let Some(g) = self.opts.group.filter(|g| *g > 0) {
            s = group_digits(&s, g);
        }
        if self.opts.upper {
            s = s.to_ascii_uppercase();
        }
        if self.opts.prefix {
            let p = match self.to.radix() {
                Some(2) => "0b",
                Some(8) => "0o",
                Some(16) => "0x",
                _ => "",
            };
            s = format!("{p}{s}");
        }
        s
    }

    /// Render one number in the target base.
    fn num_to_string(&self, n: &Num, to_base: u32) -> String {
        let s = self.mag_to_string(n, to_base);
        // Outside `finish_digits`, so the sign lands outside the `0x` prefix
        // and is not counted against `--width`.
        if n.neg { format!("-{s}") } else { s }
    }

    fn mag_to_string(&self, n: &Num, to_base: u32) -> String {
        let to_bits = to_base.is_power_of_two().then(|| to_base.trailing_zeros());
        match (n.bits_per_digit(), to_bits) {
            // Path 1: bit regrouping, no bignum.
            (Some(fb), Some(tb)) => {
                let total_bits = n.digits.len() * fb as usize;
                let out_len = total_bits.div_ceil(tb as usize).max(1);
                let out = regroup_to(&n.digits, fb, tb, out_len);
                let s: String = out.into_iter().map(digit_char).collect();
                self.finish_digits(s, true)
            }
            // Paths 2 and 3: via the magnitude, which picks u128 or BigUint.
            _ => self.finish_digits(n.to_mag().to_str_radix(to_base), false),
        }
    }

    /// Render one byte in the target base, padded to the base's natural byte width.
    fn byte_to_string(&self, b: u8, to_base: u32) -> String {
        match to_base.is_power_of_two().then(|| to_base.trailing_zeros()) {
            Some(tb) => {
                let out_len = 8usize.div_ceil(tb as usize);
                let s: String = regroup_to(&[b], 8, tb, out_len)
                    .into_iter()
                    .map(digit_char)
                    .collect();
                self.finish_digits(s, true)
            }
            None => self.finish_digits(small_to_radix(b as u128, to_base), false),
        }
    }

}

// ------------------------------------------------------------ bytes of a number

/// The bytes of a number, at the width its digits imply.
///
/// Free rather than a method: the body never looked at `self`, and the
/// byte-order pass needs it from outside the impl.
/// A `Num` from a computed value, rather than from digits somebody wrote.
///
/// An expression result carries **no written width** — nobody wrote its digits
/// down — so the digits are minimal, the same rule base 10 already follows.
/// A register width is the exception: `--word 2` says the value *is* two bytes
/// wide, so a byte-aligned base is padded out to say so. That padding lives in
/// the digit vector rather than being applied at the end, because everything
/// downstream — `num_to_bytes`, `byte_span`, the swap — reads the width off
/// `digits.len()`.
fn num_from_mag(v: &BigInt, base: u32, word: Option<usize>, text: String) -> Num {
    let s = v.magnitude().to_str_radix(base);
    let mut digits: Vec<u8> = s.chars().map(|c| c.to_digit(base).unwrap() as u8).collect();
    if let Some(w) = word {
        if let Some(bits) = base.is_power_of_two().then(|| base.trailing_zeros()) {
            // Base 8 is a power of two but not byte-aligned, so it has no
            // digit count that means "two bytes"; it wraps without padding.
            if 8 % bits == 0 {
                let want = 8 * w / bits as usize;
                if digits.len() < want {
                    let mut padded = vec![0u8; want - digits.len()];
                    padded.append(&mut digits);
                    digits = padded;
                }
            }
        }
    }
    Num { digits, base, neg: v.sign() == Sign::Minus, text }
}

fn num_to_bytes(n: &Num) -> Vec<u8> {
    match n.bits_per_digit() {
        Some(fb) => {
            let minimal = {
                let significant = n.digits.iter().position(|&d| d != 0).unwrap_or(n.digits.len());
                let bits = (n.digits.len() - significant) * fb as usize;
                bits.div_ceil(8).max(1)
            };
            let want = byte_width(n, minimal);
            regroup_to(&n.digits, fb, 8, want)
        }
        None => {
            let bytes = n.to_mag().to_bytes_be();
            let want = byte_width(n, bytes.len());
            let mut out = vec![0u8; want - bytes.len()];
            out.extend_from_slice(&bytes);
            out
        }
    }
}

/// The bytes of `n` at exactly `want` bytes: zero-extended on the left, and an
/// error rather than a silent truncation when the value needs more room.
fn num_to_bytes_at(n: &Num, want: usize) -> Result<Vec<u8>, ConvError> {
    let b = num_to_bytes(n);
    if b.len() > want {
        let cut = b.len() - want;
        if b[..cut].iter().any(|&x| x != 0) {
            return Err(ConvError::TooWide { token: n.text.clone(), want });
        }
        return Ok(b[cut..].to_vec());
    }
    let mut out = vec![0u8; want - b.len()];
    out.extend_from_slice(&b);
    Ok(out)
}

/// Rebuild a number from bytes: pure regrouping for a power-of-two base, and
/// through the magnitude otherwise.
///
/// The digit count comes from the byte count, which is what carries a swapped
/// value's width back into the pipeline so the rest of it never learns that a
/// swap happened.
fn num_from_bytes(bytes: &[u8], base: u32, text: String) -> Num {
    match base.is_power_of_two().then(|| base.trailing_zeros()) {
        Some(tb) => {
            let out_len = (bytes.len() * 8).div_ceil(tb as usize).max(1);
            Num { digits: regroup_to(bytes, 8, tb, out_len), base, neg: false, text }
        }
        None => {
            let mut m = Mag::Small(0);
            for &b in bytes {
                m.mul_add(256, b);
            }
            let digits = m
                .to_str_radix(base)
                .chars()
                .map(|c| c.to_digit(base).unwrap() as u8)
                .collect();
            Num { digits, base, neg: false, text }
        }
    }
}

impl Converter {
    // ---- the two directions

    /// How many bytes of this token the swap should cover.
    fn byte_span(&self, n: &Num) -> Result<usize, ConvError> {
        if let Some(w) = self.opts.word.filter(|w| *w > 0) {
            // An explicit word size settles the width outright, and a short
            // value is zero-extended to fill it.
            return Ok(num_to_bytes(n).len().div_ceil(w).max(1) * w);
        }
        match n.bits_per_digit() {
            Some(bits) if 8 % bits == 0 => {
                let total = n.digits.len() * bits as usize;
                if total % 8 != 0 {
                    // An odd hex digit count has no byte boundary to swap on,
                    // and rounding it either way is a guess.
                    return Err(ConvError::NotWholeBytes {
                        token: n.text.clone(),
                        base: n.base,
                    });
                }
                Ok(total / 8)
            }
            // No width of its own. `check` refuses this configuration up
            // front, but the engine must not depend on having been asked:
            // inferring a width from the value here is exactly the silent
            // wrong answer the error exists to prevent.
            _ => Err(ConvError::NoByteWidth { format: Format::Positional(n.base).to_string() }),
        }
    }

    /// Put the value into, or take it out of, little-endian byte order.
    ///
    /// The swap is defined on bytes, so every arm has to say where its bytes
    /// and its width come from. Numbers swap per token; a run of bytes swaps
    /// as one run, or per `--word` chunk.
    fn reorder(&self, s: Stream, warnings: &mut Vec<ConvError>) -> Result<Stream, ConvError> {
        let word = self.opts.word.filter(|w| *w > 0);
        match s {
            Stream::Bytes(mut b) => {
                if swap_words(&mut b, word).is_err() {
                    let e = ConvError::RaggedWord {
                        len: b.len(),
                        word: word.unwrap_or(1),
                    };
                    if !self.opts.keep_going {
                        return Err(e);
                    }
                    warnings.push(e);
                }
                Ok(Stream::Bytes(b))
            }
            Stream::Nums(nums) => {
                let mut out = Vec::with_capacity(nums.len());
                for n in nums {
                    if n.neg {
                        return Err(ConvError::NegativeResult {
                            text: n.text.clone(),
                            wher: "a byte-order swap".to_string(),
                        });
                    }
                    let bytes = self
                        .byte_span(&n)
                        .and_then(|want| num_to_bytes_at(&n, want));
                    let mut bytes = match bytes {
                        Ok(b) => b,
                        Err(e) if self.opts.keep_going => {
                            warnings.push(e);
                            continue;
                        }
                        Err(e) => return Err(e),
                    };
                    // Padded to a multiple of the word size above, so the
                    // ragged case cannot arise here.
                    let _ = swap_words(&mut bytes, word);
                    out.push(num_from_bytes(&bytes, n.base, n.text));
                }
                Ok(Stream::Nums(out))
            }
            // Reversing code points is `rev`, not endianness.
            Stream::Codepoints(_) => Err(ConvError::EndianNeedsBytes),
        }
    }

    /// Evaluate one segment as an expression, giving a `Num` in the source
    /// base. `--word` doubles as the register width, which is the same claim
    /// about the same value it already makes for the byte-order swap.
    fn eval_segment(&self, seg: &str, base: u32) -> Result<Num, ConvError> {
        let word = self.opts.word.filter(|w| *w > 0);
        let text = seg.trim().to_string();
        let v = expr::eval(seg, base, word).map_err(|detail| ConvError::BadExpr {
            text: text.clone(),
            detail,
        })?;
        Ok(num_from_mag(&v, base, word, text))
    }

    /// Decode a chunk of source text into the intermediate form.
    fn decode(&self, input: &str, warnings: &mut Vec<ConvError>) -> Result<Stream, ConvError> {
        match self.from {
            Format::Positional(base) => {
                let mut nums = Vec::new();
                // Two levels, where there used to be one split on whitespace
                // and commas. A newline or a comma separates *records*; a space
                // does not, so `4438 + 1a` is one expression while `ff 10` is
                // still two values. For any input without an operator in it the
                // two splits together are exactly the old one.
                for seg in input.split(['\n', '\r', ',']) {
                    if seg.trim().is_empty() {
                        continue;
                    }
                    // `--strict` already means "reject the leniency
                    // affordances", and an expression is the largest one — so
                    // it is also the documented way back to the plain error.
                    if !self.opts.strict && expr::has_operator(seg) {
                        match self.eval_segment(seg, base) {
                            Ok(n) => {
                                nums.push(n);
                                continue;
                            }
                            // `-k` must never produce *less* than it used to.
                            // Before expressions existed this segment was a
                            // token list, so fall back to one and let the loop
                            // below report whichever tokens are actually bad.
                            Err(_) if self.opts.keep_going => {}
                            Err(e) => return Err(e),
                        }
                    }
                    for tok in seg.split_whitespace() {
                        match decode_num(tok, base, self.opts.strict) {
                            Ok(n) => nums.push(n),
                            Err(e) if self.opts.keep_going => warnings.push(e),
                            Err(e) => return Err(e),
                        }
                    }
                }
                Ok(Stream::Nums(nums))
            }
            Format::Char => {
                if self.char_is_bytes() {
                    Ok(Stream::Bytes(input.as_bytes().to_vec()))
                } else {
                    Ok(Stream::Codepoints(input.chars().collect()))
                }
            }
            Format::Esc => Ok(Stream::Bytes(decode_esc(input, self.opts.strict)?)),
            enc => Ok(Stream::Bytes(decode_encoding(input, enc, self.opts.strict)?)),
        }
    }

    /// Flatten the intermediate form to bytes, for byte-shaped targets.
    fn to_bytes(&self, s: &Stream) -> Result<Vec<u8>, ConvError> {
        Ok(match s {
            Stream::Bytes(b) => b.clone(),
            Stream::Nums(nums) => {
                // The one funnel for every byte-shaped target — char-as-bytes,
                // esc, base64, base32 — so the negative check belongs here
                // rather than four times over.
                if let Some(n) = nums.iter().find(|n| n.neg) {
                    return Err(ConvError::NegativeResult {
                        text: n.text.clone(),
                        wher: self.to.to_string(),
                    });
                }
                nums.iter().flat_map(num_to_bytes).collect()
            }
            Stream::Codepoints(chars) => chars.iter().collect::<String>().into_bytes(),
        })
    }

    /// Convert one chunk. Trailing bytes that form an incomplete UTF-8 sequence
    /// are held in `carry` for the next chunk; recoverable problems are pushed
    /// to `warnings` when `keep_going` is set.
    pub fn convert_chunk(
        &self,
        input: &str,
        carry: &mut Vec<u8>,
        warnings: &mut Vec<ConvError>,
    ) -> Result<String, ConvError> {
        let mut stream = self.decode(input, warnings)?;

        // Normalize the source's byte order in, and the target's out. Between
        // these two lines everything works in reading order and knows nothing
        // about endianness. When both ends are big-endian — which is every
        // conversion that existed before byte order did — neither pass runs.
        if self.opts.from_endian.is_little() {
            stream = self.reorder(stream, warnings)?;
        }
        if self.opts.to_endian.is_little() {
            stream = self.reorder(stream, warnings)?;
        }

        let delim = self.delim().to_string();

        match self.to {
            Format::Positional(base) => {
                let parts: Vec<String> = match &stream {
                    Stream::Nums(nums) => nums.iter().map(|n| self.num_to_string(n, base)).collect(),
                    Stream::Bytes(bytes) => {
                        bytes.iter().map(|&b| self.byte_to_string(b, base)).collect()
                    }
                    Stream::Codepoints(chars) => chars
                        .iter()
                        .map(|c| self.finish_digits(small_to_radix(*c as u128, base), false))
                        .collect(),
                };
                Ok(parts.join(&delim))
            }
            Format::Char => {
                if self.char_is_bytes() {
                    let mut bytes = std::mem::take(carry);
                    bytes.extend(self.to_bytes(&stream)?);
                    Ok(decode_utf8_incremental(bytes, carry))
                } else {
                    let mut out = String::new();
                    match &stream {
                        Stream::Nums(nums) => {
                            for n in nums {
                                // `to_mag` drops the sign, so -4 would quietly
                                // become U+0004 if this were not checked first.
                                if n.neg {
                                    return Err(ConvError::NegativeResult {
                                        text: n.text.clone(),
                                        wher: "a code point".to_string(),
                                    });
                                }
                                match n.to_mag().to_u32().and_then(char::from_u32) {
                                    Some(cp) => out.push(cp),
                                    None if self.opts.keep_going => {
                                        warnings.push(ConvError::NotACodepoint {
                                            token: n.text.clone(),
                                        });
                                    }
                                    None => {
                                        return Err(ConvError::NotACodepoint {
                                            token: n.text.clone(),
                                        });
                                    }
                                }
                            }
                        }
                        Stream::Bytes(b) => out.push_str(&String::from_utf8_lossy(b)),
                        Stream::Codepoints(c) => out.extend(c.iter()),
                    }
                    Ok(out)
                }
            }
            Format::Esc => {
                let bytes = self.to_bytes(&stream)?;
                Ok(encode_esc(&bytes, self.opts.upper))
            }
            enc => {
                let bytes = self.to_bytes(&stream)?;
                Ok(encoding_for(enc, true).encode(&bytes))
            }
        }
    }

    /// Convert a complete input in one shot, discarding warnings.
    pub fn convert(&self, input: &str) -> Result<String, ConvError> {
        self.convert_all(input).map(|(s, _)| s)
    }

    /// Convert a complete input in one shot, keeping any warnings.
    pub fn convert_all(&self, input: &str) -> Result<(String, Vec<ConvError>), ConvError> {
        let mut carry = Vec::new();
        let mut warnings = Vec::new();
        let mut out = self.convert_chunk(input, &mut carry, &mut warnings)?;
        if !carry.is_empty() {
            out.push_str(&String::from_utf8_lossy(&carry));
        }
        Ok((out, warnings))
    }
}

/// The intermediate form between decoding and encoding.
enum Stream {
    Nums(Vec<Num>),
    Bytes(Vec<u8>),
    Codepoints(Vec<char>),
}

fn group_digits(s: &str, g: usize) -> String {
    let chars: Vec<char> = s.chars().collect();
    let mut out = String::with_capacity(s.len() + s.len() / g);
    let first = chars.len() % g;
    let mut i = 0;
    if first > 0 {
        out.extend(&chars[..first]);
        i = first;
    }
    while i < chars.len() {
        if !out.is_empty() {
            out.push(' ');
        }
        out.extend(&chars[i..i + g]);
        i += g;
    }
    out
}

/// Decode bytes to text, holding back a trailing partial UTF-8 sequence so a
/// multi-byte character split across two flushes still comes out right.
fn decode_utf8_incremental(bytes: Vec<u8>, carry: &mut Vec<u8>) -> String {
    carry.clear();
    let mut out = String::new();
    let mut rest = &bytes[..];
    loop {
        match std::str::from_utf8(rest) {
            Ok(s) => {
                out.push_str(s);
                return out;
            }
            Err(e) => {
                let valid = e.valid_up_to();
                out.push_str(unsafe { std::str::from_utf8_unchecked(&rest[..valid]) });
                match e.error_len() {
                    // A genuinely invalid byte: substitute and carry on.
                    Some(n) => {
                        out.push(char::REPLACEMENT_CHARACTER);
                        rest = &rest[valid + n..];
                    }
                    // Truncated at the end: keep it for the next chunk.
                    None => {
                        carry.extend_from_slice(&rest[valid..]);
                        return out;
                    }
                }
            }
        }
    }
}

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

    fn conv(from: &str, to: &str, input: &str) -> String {
        with_opts(from, to, input, Options::default())
    }

    fn with_opts(from: &str, to: &str, input: &str, opts: Options) -> String {
        let c = Converter::new(
            Format::parse(from).unwrap(),
            Format::parse(to).unwrap(),
            opts,
        );
        c.convert(input).unwrap()
    }


    // ---- expression math

    fn err_of(from: &str, to: &str, input: &str, opts: Options) -> ConvError {
        let c = Converter::new(
            Format::parse(from).unwrap(),
            Format::parse(to).unwrap(),
            opts,
        );
        c.convert(input).expect_err(input)
    }

    /// The whole point: address math without two conversions around it.
    #[test]
    fn a_positional_value_may_be_an_expression() {
        assert_eq!(conv("hex", "hex", "4438+1a"), "4452");
        assert_eq!(conv("hex", "dec", "4438+1a"), "17490");
        assert_eq!(conv("hex", "hex", "(4500 - 4438)/2"), "64");
        assert_eq!(conv("dec", "hex", "1000*4"), "fa0");
        assert_eq!(conv("hex", "bin", "ff & 0f"), "1111");
    }

    /// An expression result has no *written* width, because nobody wrote its
    /// digits down — the same rule base 10 already follows.
    #[test]
    fn a_computed_value_has_no_natural_width() {
        assert_eq!(conv("hex", "bin", "0f"), "00001111");
        assert_eq!(conv("hex", "bin", "ff & 0f"), "1111");
    }

    /// `--word` is a register: the value wraps into it and is padded out to
    /// say how wide it is.
    #[test]
    fn a_word_makes_the_arithmetic_fixed_width() {
        let w = |n| Options { word: Some(n), ..Default::default() };
        assert_eq!(with_opts("hex", "hex", "4438 - 4500", w(2)), "ff38");
        assert_eq!(with_opts("hex", "hex", "0 - 1", w(2)), "ffff");
        assert_eq!(with_opts("hex", "hex", "ff & 0f", w(2)), "000f");
        assert_eq!(with_opts("hex", "bin", "1+0", w(2)), "0000000000000001");
        // Base 8 is a power of two but not byte-aligned, so it wraps without
        // gaining a digit width it cannot express.
        assert_eq!(with_opts("oct", "oct", "0 - 1", w(1)), "377");
    }

    /// Without a register there is nothing to wrap into, so the sign is real
    /// and gets printed — outside the `0x` prefix.
    #[test]
    fn a_negative_result_keeps_its_sign() {
        assert_eq!(conv("hex", "hex", "4438 - 4500"), "-c8");
        assert_eq!(conv("hex", "dec", "1 - 5"), "-4");
        let pre = Options { prefix: true, ..Default::default() };
        assert_eq!(with_opts("hex", "hex", "4438 - 4500", pre), "-0xc8");
    }

    /// `to_mag` discards the sign, so every byte-shaped target has to check
    /// `neg` itself. A miss here turns -4 into U+0004 without a word of
    /// warning, which is the one failure this feature must not have.
    #[test]
    fn a_negative_never_reaches_a_byte() {
        for to in ["char", "b64", "b32", "esc"] {
            assert!(
                matches!(
                    err_of("hex", to, "1 - 5", Options::default()),
                    ConvError::NegativeResult { .. }
                ),
                "hex2{to} let a negative through"
            );
        }
        // The byte-order path takes its width from bytes too.
        assert!(matches!(
            le("hex2lehex", "1 - 5"),
            Err(ConvError::NegativeResult { .. })
        ));
        // char as code points is a separate arm from char as bytes.
        let cp = Options { bytes_mode: Some(false), ..Default::default() };
        assert!(matches!(
            err_of("hex", "char", "1 - 5", cp),
            ConvError::NegativeResult { .. }
        ));
    }

    /// A newline or a comma separates records; a space does not.
    #[test]
    fn segments_split_on_records_not_spaces() {
        assert_eq!(conv("hex", "dec", "ff 10"), "255\n16");
        assert_eq!(conv("hex", "dec", "ff,10"), "255\n16");
        assert_eq!(conv("hex", "hex", "1+1, 2+2"), "2\n4");
        assert_eq!(conv("hex", "hex", "4438 + 1a"), "4452");
        assert_eq!(conv("hex", "hex", "1+1\n2+2"), "2\n4");
    }

    /// `--strict` already rejects the leniency affordances, and an expression
    /// is the largest one — so it is the way back to the plain error.
    #[test]
    fn strict_turns_expressions_back_into_bad_digits() {
        let s = Options { strict: true, ..Default::default() };
        assert!(matches!(
            err_of("hex", "hex", "4438+1a", s),
            ConvError::BadDigit { .. }
        ));
    }

    /// `-k` must never produce *less* than it did before expressions existed,
    /// so a segment that will not parse falls back to being a token list.
    #[test]
    fn keep_going_falls_back_to_a_token_list() {
        let k = Options { keep_going: true, ..Default::default() };
        assert_eq!(with_opts("hex", "dec", "ff 1+1 10", k), "255\n16");
    }

    #[test]
    fn a_broken_expression_names_the_problem() {
        assert!(matches!(
            err_of("hex", "hex", "10/0", Options::default()),
            ConvError::BadExpr { detail: crate::expr::ExprError::DivZero, .. }
        ));
    }

    /// `--word` says the same thing to the arithmetic and to the swap: this
    /// value is N bytes wide.
    #[test]
    fn a_word_composes_with_byte_order() {
        assert_eq!(worded("ledec2hex", "1+1", 4).unwrap(), "2000000");
        assert_eq!(worded("hex2lehex", "4438 - 4500", 2).unwrap(), "38ff");
    }

    // ---- escaped hex

    #[test]
    fn esc_escapes_every_byte() {
        assert_eq!(conv("char", "esc", "hello"), "\\x68\\x65\\x6c\\x6c\\x6f");
        assert_eq!(conv("hex", "esc", "41424344"), "\\x41\\x42\\x43\\x44");
        // Printable bytes are escaped too: uniform output round-trips, and
        // never leaves you wondering if a backslash was data.
        assert_eq!(conv("char", "esc", "A"), "\\x41");
    }

    #[test]
    fn esc_decodes_back() {
        assert_eq!(conv("esc", "char", "\\x68\\x65\\x6c\\x6c\\x6f"), "hello");
        assert_eq!(conv("esc", "hex", "\\x41\\x42"), "4142");
        // Round-tripping is the property that matters.
        let text = "flag{n0t_qu1t3_4_fl4g}";
        assert_eq!(conv("esc", "char", &conv("char", "esc", text)), text);
    }

    /// What you actually copy out of an exploit script is mixed: literal text
    /// with escapes threaded through it.
    #[test]
    fn esc_reads_mixed_input() {
        assert_eq!(conv("esc", "hex", "GET /\\r\\n"), "474554202f0d0a");
        assert_eq!(conv("esc", "char", "A\\x42C"), "ABC");
    }

    #[test]
    fn esc_rejects_a_malformed_escape() {
        let bad = |s: &str| {
            Converter::new(Format::Esc, Format::HEX, Options::default())
                .convert(s)
                .is_err()
        };
        assert!(bad("\\xZZ"), "ZZ is not hex");
        assert!(bad("\\x4"), "one digit is not a byte");
        assert!(bad("\\q"), "no such escape");
        assert!(bad("trailing \\"), "nothing after the backslash");
    }

    /// `--strict` means every byte is spelled out; literal text is not input.
    #[test]
    fn esc_strict_wants_only_escapes() {
        let strict = Options { strict: true, ..Default::default() };
        assert_eq!(with_opts("esc", "hex", "\\x41\\x42", strict.clone()), "4142");
        assert!(
            Converter::new(Format::Esc, Format::HEX, strict)
                .convert("A\\x42")
                .is_err()
        );
    }

    /// The whole point of the orthogonal byte-order design: it composes with a
    /// format that knew nothing about it.
    #[test]
    fn esc_composes_with_byte_order() {
        assert_eq!(le("lehex2esc", "0d0c0b0a").unwrap(), "\\x0a\\x0b\\x0c\\x0d");
        assert_eq!(le("leesc2hex", "\\x0d\\x0c\\x0b\\x0a").unwrap(), "0a0b0c0d");
        // p32(1234) — byte for byte what struct.pack('<I', 1234) gives.
        assert_eq!(worded("dec2leesc", "1234", 4).unwrap(), "\\xd2\\x04\\x00\\x00");
    }

    /// base64 has to see the whole stream to place its padding; esc does not,
    /// so it must not have been swept into the same bucket.
    #[test]
    fn esc_streams_unlike_the_padded_encodings() {
        let c = |f, t| Converter::new(f, t, Options::default()).can_stream();
        assert!(c(Format::Char, Format::Esc));
        assert!(c(Format::Esc, Format::HEX));
        assert!(!c(Format::Char, Format::B64));
    }

    // ---- byte order

    /// Convert through a command name, the way a shim would.
    fn le(name: &str, input: &str) -> Result<String, ConvError> {
        le_opts(name, input, Options::default())
    }

    fn le_opts(name: &str, input: &str, mut opts: Options) -> Result<String, ConvError> {
        let (from, to) = crate::names::resolve(name).unwrap();
        opts.from_endian = from.endian;
        opts.to_endian = to.endian;
        let c = Converter::new(from.format, to.format, opts);
        c.check()?;
        c.convert(input)
    }

    fn worded(name: &str, input: &str, word: usize) -> Result<String, ConvError> {
        le_opts(name, input, Options { word: Some(word), ..Default::default() })
    }

    #[test]
    fn little_endian_reverses_a_written_word() {
        // 0x0d0c0b0a read back to front is 0x0a0b0c0d.
        assert_eq!(le("lehex2dec", "0d0c0b0a").unwrap(), "168496141");
        assert_eq!(le("lehex2hex", "0d0c0b0a").unwrap(), "0a0b0c0d");
        assert_eq!(le("lehex2char", "6f6c6c6568").unwrap(), "hello");
        assert_eq!(le("hex2lebin", "ff00").unwrap(), "0000000011111111");
    }

    /// A single byte has no byte order, so the swap is a no-op rather than an
    /// error — `lehex2dec ff` must agree with `hex2dec ff`.
    #[test]
    fn one_byte_has_no_byte_order() {
        assert_eq!(le("lehex2dec", "ff").unwrap(), conv("hex", "dec", "ff"));
        assert_eq!(le("lehex2hex", "ff").unwrap(), "ff");
    }

    /// `be` is the default written down, so it must change nothing at all.
    #[test]
    fn big_endian_is_the_identity() {
        assert_eq!(le("behex2dec", "0d0c0b0a").unwrap(), conv("hex", "dec", "0d0c0b0a"));
    }

    /// Two swaps at the same width cancel.
    #[test]
    fn swapping_twice_is_the_identity() {
        assert_eq!(le("lehex2lehex", "0d0c0b0a").unwrap(), "0d0c0b0a");
    }

    /// Each token is its own value; the swap never runs across whitespace.
    #[test]
    fn little_endian_applies_per_token() {
        assert_eq!(le("lehex2hex", "0102 0304").unwrap(), "0201\n0403");
    }

    /// An odd hex digit count has no byte boundary to swap on, and rounding it
    /// either way would be a guess.
    #[test]
    fn a_half_byte_is_refused() {
        assert!(matches!(
            le("lehex2dec", "fff"),
            Err(ConvError::NotWholeBytes { .. })
        ));
        // ...but `-k` downgrades it, like every other token-level failure.
        let opts = Options { keep_going: true, ..Default::default() };
        assert_eq!(le_opts("lehex2dec", "fff 0d0c0b0a", opts).unwrap(), "168496141");
    }

    /// Base 10 has no width of its own: 255 is a byte and 256 is two, so the
    /// word size would otherwise depend on the value.
    #[test]
    fn a_base_without_a_byte_width_is_refused() {
        assert!(matches!(le("ledec2hex", "258"), Err(ConvError::NoByteWidth { .. })));
        assert!(matches!(le("dec2lehex", "1234"), Err(ConvError::NoByteWidth { .. })));
        // Base 8 is a power of two but 3 bits do not divide 8.
        assert!(matches!(le("leoct2hex", "777"), Err(ConvError::NoByteWidth { .. })));
        // A word size settles it.
        assert_eq!(worded("dec2lehex", "1234", 4).unwrap(), "d2040000");
        assert_eq!(worded("ledec2hex", "1234", 4).unwrap(), "d2040000");
    }

    /// `check` is a courtesy to the CLI, not the engine's only guard: a
    /// library caller that skips it must still not get a guessed width.
    #[test]
    fn the_engine_refuses_a_missing_width_even_without_check() {
        let opts = Options { from_endian: Endian::Little, ..Default::default() };
        let c = Converter::new(Format::DEC, Format::HEX, opts);
        assert!(matches!(c.convert("258"), Err(ConvError::NoByteWidth { .. })));
    }

    #[test]
    fn a_word_size_pins_the_width() {
        // `ff` fills a 4-byte word as 000000ff, which reversed is ff000000.
        assert_eq!(worded("lehex2dec", "ff", 4).unwrap(), "4278190080");
        // Words are swapped independently; their order is left alone.
        assert_eq!(worded("lehex2hex", "0d0c0b0a78563412", 4).unwrap(), "0a0b0c0d12345678");
        assert_eq!(worded("lehex2hex", "0d0c0b0a", 2).unwrap(), "0c0d0a0b");
    }

    /// Zero-padding a run of bytes would change its length, which is data
    /// corruption — so it is an error unless the caller asked to keep going.
    #[test]
    fn a_ragged_byte_run_is_refused() {
        assert!(matches!(
            worded("char2lehex", "hello", 4),
            Err(ConvError::RaggedWord { len: 5, word: 4 })
        ));
    }

    /// Reversing code points is `rev`, not endianness.
    #[test]
    fn code_points_have_no_byte_order() {
        assert!(matches!(
            le_opts(
                "char2ledec",
                "hi",
                Options { bytes_mode: Some(false), ..Default::default() }
            ),
            Err(ConvError::EndianNeedsBytes)
        ));
        // As bytes it is perfectly well defined.
        let opts = Options { bytes_mode: Some(true), ..Default::default() };
        assert_eq!(le_opts("char2ledec", "hi", opts).unwrap(), "105 104");
    }

    /// A base64 blob is one value, so the whole decoded run swaps together.
    #[test]
    fn an_encoding_blob_is_one_value() {
        assert_eq!(le("leb642hex", "AQAAAA==").unwrap(), "00000001");
    }

    /// A swap over a *run* of bytes cannot be done a chunk at a time, and what
    /// decides that is the source — not whichever side wears the `le`.
    #[test]
    fn a_swapped_byte_run_cannot_stream() {
        let streams = |name: &str| {
            let (from, to) = crate::names::resolve(name).unwrap();
            let opts = Options {
                from_endian: from.endian,
                to_endian: to.endian,
                ..Default::default()
            };
            Converter::new(from.format, to.format, opts).can_stream()
        };
        // char source: the run has no token boundaries to work with.
        assert!(!streams("char2lehex"));
        assert!(!streams("lechar2hex"));
        // Positional source: a token is complete before it is converted.
        assert!(streams("lehex2dec"));
        assert!(streams("hex2lechar"));
        // Nothing that streamed before byte order existed stops streaming.
        assert!(streams("char2hex"));
        assert!(streams("hex2char"));
    }

    /// The swap must stay linear; it is two extra passes, not a quadratic one.
    #[test]
    fn a_long_swapped_blob_is_not_quadratic() {
        let input = "0d0c0b0a".repeat(20_000);
        let out = le("lehex2hex", &input).unwrap();
        assert_eq!(out.len(), input.len());
    }

    // ---- path 1: power-of-two regrouping

    #[test]
    fn hex_to_bin_keeps_digit_width() {
        assert_eq!(conv("hex", "bin", "0f"), "00001111");
        assert_eq!(conv("hex", "bin", "f"), "1111");
        assert_eq!(conv("hex", "bin", "41 42"), "01000001\n01000010");
    }

    #[test]
    fn hex_to_oct_rounds_bit_width_up() {
        assert_eq!(conv("hex", "oct", "ff"), "377");
        assert_eq!(conv("hex", "oct", "1628"), "013050");
    }

    #[test]
    fn bin_to_hex_packs_nibbles() {
        assert_eq!(conv("bin", "hex", "0100000101000010"), "4142");
        assert_eq!(conv("bin", "hex", "1111"), "f");
    }

    #[test]
    fn no_width_strips_leading_zeros() {
        let opts = Options { no_width: true, ..Default::default() };
        assert_eq!(with_opts("hex", "bin", "0f", opts), "1111");
    }

    #[test]
    fn explicit_width_overrides_natural_width() {
        let opts = Options { width: Some(4), ..Default::default() };
        assert_eq!(with_opts("hex", "bin", "0f", opts), "1111");
        let opts = Options { width: Some(12), ..Default::default() };
        assert_eq!(with_opts("hex", "bin", "0f", opts), "000000001111");
    }

    // ---- paths 2 and 3: magnitude

    #[test]
    fn decimal_conversions() {
        assert_eq!(conv("dec", "hex", "255"), "ff");
        assert_eq!(conv("hex", "dec", "ff"), "255");
        assert_eq!(conv("dec", "bin", "5"), "101");
        assert_eq!(conv("36", "dec", "zz"), "1295");
        assert_eq!(conv("dec", "36", "1295"), "zz");
    }

    #[test]
    fn arbitrary_precision_beyond_u128() {
        // 2^128, which cannot round-trip through the u128 fast path.
        let big = "340282366920938463463374607431768211456";
        assert_eq!(conv("dec", "hex", big), "100000000000000000000000000000000");
        assert_eq!(conv("hex", "dec", "100000000000000000000000000000000"), big);
    }

    #[test]
    fn very_long_hex_blob_is_not_quadratic() {
        // Straight through the regrouping path; no bignum should be built.
        let blob = "ab".repeat(5000);
        let out = conv("hex", "bin", &blob);
        assert_eq!(out.len(), 40000);
        assert!(out.starts_with("10101011"));
    }

    // ---- char semantics

    #[test]
    fn dec_to_char_reads_code_points() {
        assert_eq!(conv("dec", "char", "104\n101\n108\n108\n111"), "hello");
        assert_eq!(conv("dec", "char", "128512"), "\u{1F600}");
    }

    #[test]
    fn hex_to_char_reads_bytes() {
        assert_eq!(conv("hex", "char", "68656c6c6f"), "hello");
        assert_eq!(conv("hex", "char", "68 65 6c 6c 6f"), "hello");
        assert_eq!(conv("bin", "char", "0100000101000010"), "AB");
    }

    #[test]
    fn char_to_numbers() {
        assert_eq!(conv("char", "hex", "hello"), "68656c6c6f");
        assert_eq!(conv("char", "dec", "hello"), "104 101 108 108 111");
        assert_eq!(conv("char", "bin", "A"), "01000001");
        assert_eq!(conv("char", "oct", "A"), "101");
    }

    #[test]
    fn bytes_mode_can_be_forced_either_way() {
        let opts = Options { bytes_mode: Some(false), ..Default::default() };
        assert_eq!(with_opts("hex", "char", "1F600", opts), "\u{1F600}");
        let opts = Options { bytes_mode: Some(true), ..Default::default() };
        assert_eq!(conv("dec", "char", "112"), "p");
        assert_eq!(with_opts("dec", "char", "112", opts), "p");
    }

    // ---- encodings

    #[test]
    fn base64_round_trip() {
        assert_eq!(conv("hex", "b64", "68656c6c6f"), "aGVsbG8=");
        assert_eq!(conv("b64", "char", "aGVsbG8="), "hello");
        assert_eq!(conv("char", "b64", "hello"), "aGVsbG8=");
        assert_eq!(conv("b64", "hex", "aGVsbG8="), "68656c6c6f");
    }

    #[test]
    fn base64_tolerates_missing_padding() {
        assert_eq!(conv("b64", "char", "aGVsbG8"), "hello");
    }

    #[test]
    fn base32_round_trip_and_case_leniency() {
        let encoded = conv("char", "b32", "hello");
        assert_eq!(conv("b32", "char", &encoded), "hello");
        assert_eq!(conv("b32", "char", &encoded.to_ascii_lowercase()), "hello");
    }

    #[test]
    fn leading_zero_bytes_survive_into_base64() {
        // 12 hex digits is 6 bytes, so the zero byte must not be dropped.
        assert_eq!(conv("hex", "b64", "0068656c6c6f"), "AGhlbGxv");
        assert_eq!(conv("hex", "b64", "68656c6c6f"), "aGVsbG8=");
    }

    // ---- formatting options

    #[test]
    fn grouping_and_case_and_prefix() {
        let opts = Options { group: Some(4), ..Default::default() };
        assert_eq!(with_opts("hex", "bin", "ff", opts), "1111 1111");
        let opts = Options { upper: true, ..Default::default() };
        assert_eq!(with_opts("dec", "hex", "255", opts), "FF");
        let opts = Options { prefix: true, ..Default::default() };
        assert_eq!(with_opts("dec", "hex", "255", opts), "0xff");
    }

    #[test]
    fn grouping_handles_uneven_leading_group() {
        assert_eq!(group_digits("11111", 4), "1 1111");
        assert_eq!(group_digits("11111111", 4), "1111 1111");
    }

    #[test]
    fn custom_delimiter() {
        let opts = Options { delim: Some(",".into()), ..Default::default() };
        assert_eq!(with_opts("dec", "hex", "255 16", opts), "ff,10");
    }

    // ---- input leniency

    #[test]
    fn accepts_prefixes_and_underscores() {
        assert_eq!(conv("hex", "dec", "0xff"), "255");
        assert_eq!(conv("bin", "dec", "0b1010"), "10");
        assert_eq!(conv("dec", "hex", "1_000"), "3e8");
        // A bare `0b` in hex is the number 11, not a prefix.
        assert_eq!(conv("hex", "dec", "0b"), "11");
    }

    #[test]
    fn commas_and_newlines_both_separate() {
        assert_eq!(conv("dec", "hex", "255,16"), "ff\n10");
        assert_eq!(conv("dec", "hex", "255\n16"), "ff\n10");
    }

    #[test]
    fn strict_mode_rejects_prefixes() {
        let opts = Options { strict: true, ..Default::default() };
        let c = Converter::new(Format::HEX, Format::DEC, opts);
        assert!(c.convert("0xff").is_err());
    }

    // ---- errors

    #[test]
    fn bad_digits_are_reported_with_context() {
        let c = Converter::new(Format::HEX, Format::BIN, Options::default());
        let err = c.convert("zz").unwrap_err();
        assert_eq!(
            err.to_string(),
            "'zz' is not valid base 16 (bad digit 'z')"
        );
    }

    #[test]
    fn out_of_range_code_points_are_rejected() {
        let c = Converter::new(Format::DEC, Format::Char, Options::default());
        assert!(c.convert("999999999").is_err());
    }

    // ---- streaming

    #[test]
    fn utf8_split_across_chunks_is_reassembled() {
        let c = Converter::new(Format::HEX, Format::Char, Options::default());
        let mut carry = Vec::new();
        let mut warn = Vec::new();
        // U+00E9 is 0xC3 0xA9, fed one byte per chunk.
        let a = c.convert_chunk("c3", &mut carry, &mut warn).unwrap();
        assert_eq!(a, "");
        assert_eq!(carry, vec![0xc3]);
        let b = c.convert_chunk("a9", &mut carry, &mut warn).unwrap();
        assert_eq!(b, "é");
        assert!(carry.is_empty());
    }

    #[test]
    fn keep_going_skips_bad_tokens() {
        let opts = Options { keep_going: true, ..Default::default() };
        let c = Converter::new(Format::HEX, Format::DEC, opts);
        let (out, warnings) = c.convert_all("ff zz 10").unwrap();
        assert_eq!(out, "255\n16");
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].to_string().contains("'zz'"));
    }

    #[test]
    fn buffering_is_limited_to_encoding_targets() {
        let c = Converter::new(Format::DEC, Format::Char, Options::default());
        assert!(!c.buffers_output());
        let c = Converter::new(Format::HEX, Format::B64, Options::default());
        assert!(c.buffers_output());
    }
}