toktier 0.3.3

Rust API preview for TokTier's exact, stateful tokenization runtime
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
//! The property-data guard of the fast CPU route.
//!
//! The fast CPU pre-tokenizer reads its character classes (General_Category,
//! White_Space, Script=Han) from the `icu_properties` and
//! `icu_properties_data` copies the build resolves, and the requirement on
//! them is a caret one. A build whose lockfile resolves another pair than
//! the judged one can therefore classify some code points differently from
//! the judged build, and the reference engine, which reads its own tables,
//! does not follow it there.
//!
//! [`property_guard_table`](self::table) is generated by
//! `tools/generate_property_guard.py`. For every pair Cargo could resolve
//! under the workspace requirement, that tool builds the engine's own
//! `unicode.rs` against the pair, dumps every class accessor for every code
//! point, and compares the dump with the judged pair's; the table lists the
//! copies of both crates it judged that way and one set of code points, the
//! union of all the pairs' differing sets. Outside that set every listed
//! pair gives the engine the same classes as the judged pair, so a text
//! holding none of its code points is encoded by the fast engine exactly as
//! a judged build would encode it, and a text holding one is sent to the
//! reference engine.
//!
//! This module holds the two answers the rest of the crate asks for:
//! [`holds_moved`], whether a text holds a code point of the set, and
//! [`decide_standing`], what a build's lockfile reading makes of its
//! property data ([`Standing`]).

#[path = "property_guard_table.rs"]
mod table;

use std::fmt;

use toktier_routing_core::NativeRouter;
use toktier_store_core::{
    AppendReport, BoundaryCut, Encoding, EngineError, SessionEncoder, TailState, WitnessCategory,
};

pub(crate) use table::{ADMITTED_COPIES, MOVED_CODE_POINTS, MOVED_RANGES};

/// The crate that carries the property code.
pub(crate) const PROPERTIES_CRATE: &str = "icu_properties";
/// The crate that carries the property data.
pub(crate) const DATA_CRATE: &str = "icu_properties_data";
/// The variable that names the governing lockfile.
pub(crate) const CARGO_LOCK_ENV: &str = "TOKTIER_CARGO_LOCK";
/// The variable with which the ICU4X data crates take their baked data from
/// a directory instead of their own sources, whatever the lockfile says.
pub(crate) const DATA_DIR_ENV: &str = "ICU4X_DATA_DIR";

/// Separates the records of the build script's property-data reading. The
/// two separators are the bytes the build script's other records use
/// (`behavior_version.rs`), named here by what they separate.
pub(crate) const RECORD_SEPARATOR: char = '\u{1f}';
/// Separates the fields of one record.
pub(crate) const FIELD_SEPARATOR: char = '\u{1e}';

// ---------------------------------------------------------------------------
// The set of code points
// ---------------------------------------------------------------------------

/// One past the largest code point.
const CODE_POINT_LIMIT: u32 = 0x11_0000;
/// Code points per block of the block bitmap: 64.
const BLOCK_SHIFT: u32 = 6;
/// Words of the block bitmap: one bit per 64 code points.
const BLOCK_WORDS: usize = (CODE_POINT_LIMIT >> BLOCK_SHIFT) as usize / 64;

/// Whether the table is sorted, disjoint, non-adjacent, inside the code
/// space, and counted right. Checked at compile time below.
const fn table_is_well_formed() -> bool {
    let mut index = 0;
    let mut count: u32 = 0;
    while index < MOVED_RANGES.len() {
        let (low, high) = MOVED_RANGES[index];
        if low > high || high >= CODE_POINT_LIMIT {
            return false;
        }
        if index > 0 && MOVED_RANGES[index - 1].1 + 1 >= low {
            return false;
        }
        count += high - low + 1;
        index += 1;
    }
    count == MOVED_CODE_POINTS
}

const _: () = assert!(
    table_is_well_formed(),
    "the property guard table is malformed"
);

/// The smallest code point of the set (`CODE_POINT_LIMIT` when it is empty).
const MIN_MOVED: u32 = if MOVED_RANGES.is_empty() {
    CODE_POINT_LIMIT
} else {
    MOVED_RANGES[0].0
};

/// The largest code point of the set (0 when it is empty).
const MAX_MOVED: u32 = if MOVED_RANGES.is_empty() {
    0
} else {
    MOVED_RANGES[MOVED_RANGES.len() - 1].1
};

/// One bit per 64-code-point block that holds a code point of the set.
const BLOCKS: [u64; BLOCK_WORDS] = {
    let mut blocks = [0u64; BLOCK_WORDS];
    let mut index = 0;
    while index < MOVED_RANGES.len() {
        let (low, high) = MOVED_RANGES[index];
        let mut block = low >> BLOCK_SHIFT;
        while block <= high >> BLOCK_SHIFT {
            blocks[(block / 64) as usize] |= 1 << (block % 64);
            block += 1;
        }
        index += 1;
    }
    blocks
};

#[inline(always)]
fn block_holds_moved(block: u32) -> bool {
    BLOCKS
        .get((block / 64) as usize)
        .is_some_and(|word| word & (1 << (block % 64)) != 0)
}

/// The code points a UTF-8 sequence starting with `byte` can encode, as an
/// inclusive range; `None` for a continuation byte and for bytes that start
/// no sequence.
const fn lead_span(byte: u8) -> Option<(u32, u32)> {
    let byte = byte as u32;
    match byte {
        0x00..=0x7F => Some((byte, byte)),
        0xC2..=0xDF => Some(((byte & 0x1F) << 6, ((byte & 0x1F) << 6) | 0x3F)),
        0xE0..=0xEF => Some(((byte & 0x0F) << 12, ((byte & 0x0F) << 12) | 0xFFF)),
        0xF0..=0xF4 => {
            let low = (byte & 0x07) << 18;
            let high = low | 0x3_FFFF;
            Some((
                low,
                if high < CODE_POINT_LIMIT {
                    high
                } else {
                    CODE_POINT_LIMIT - 1
                },
            ))
        }
        _ => None,
    }
}

/// For every byte value, whether a character that starts with it can be a
/// code point of the set. False for continuation bytes, so a byte for which
/// this holds starts a character.
const LEAD_MAY_HOLD: [bool; 256] = {
    let mut table = [false; 256];
    let mut byte = 0;
    while byte < 256 {
        if let Some((low, high)) = lead_span(byte as u8) {
            let mut index = 0;
            while index < MOVED_RANGES.len() {
                let (moved_low, moved_high) = MOVED_RANGES[index];
                if moved_low <= high && low <= moved_high {
                    table[byte] = true;
                }
                index += 1;
            }
        }
        byte += 1;
    }
    table
};

/// The smallest byte value for which [`LEAD_MAY_HOLD`] holds (0xFF when
/// none does). Every character that can be in the set starts with a byte
/// at or above it.
const LEAD_MIN: u8 = {
    let mut byte = 0;
    while byte < 255 && !LEAD_MAY_HOLD[byte] {
        byte += 1;
    }
    byte as u8
};

/// Whether the word-at-a-time skip applies: when `LEAD_MIN` is at or above
/// 0xC0, no ASCII byte and no continuation byte (0x80 to 0xBF) reaches it.
const WORD_SKIP: bool = LEAD_MIN >= 0xC0;

const ONES: u64 = 0x0101_0101_0101_0101;
const HIGH_BITS: u64 = 0x8080_8080_8080_8080;
const LOW_BITS: u64 = 0x7F7F_7F7F_7F7F_7F7F;
/// Added to the low seven bits of each byte so that bit 7 comes up exactly
/// when those bits reach `LEAD_MIN - 0x80`. Meaningful only when
/// [`WORD_SKIP`] holds (then it lies in 1..=0x40 and no byte carries into
/// the next).
const LEAD_BIAS: u64 = if WORD_SKIP {
    (0x100 - LEAD_MIN as u64) * ONES
} else {
    0
};

/// Whether some byte of `word` is at or above `LEAD_MIN` (with
/// [`WORD_SKIP`]).
#[inline(always)]
fn word_reaches_lead_min(word: u64) -> bool {
    word & HIGH_BITS & ((word & LOW_BITS) + LEAD_BIAS) != 0
}

/// Whether one code point is in the set.
#[inline]
pub(crate) fn is_moved(code_point: u32) -> bool {
    if !(MIN_MOVED..=MAX_MOVED).contains(&code_point)
        || !block_holds_moved(code_point >> BLOCK_SHIFT)
    {
        return false;
    }
    let index = MOVED_RANGES.partition_point(|&(_, high)| high < code_point);
    MOVED_RANGES
        .get(index)
        .is_some_and(|&(low, _)| low <= code_point)
}

/// The 64-code-point block and the byte length of the character that
/// starts at `start`, read from its leading bytes without decoding the last
/// one. `None` only for a sequence cut short, which a `str` never holds.
#[inline(always)]
fn block_at(bytes: &[u8], start: usize) -> Option<(u32, usize)> {
    let lead = u32::from(*bytes.get(start)?);
    let next = |offset: usize| {
        bytes
            .get(start + offset)
            .map(|&byte| u32::from(byte) & 0x3F)
    };
    Some(match lead {
        0x00..=0x7F => (lead >> BLOCK_SHIFT, 1),
        0xC0..=0xDF => (lead & 0x1F, 2),
        0xE0..=0xEF => (((lead & 0x0F) << 6) | next(1)?, 3),
        _ => (((lead & 0x07) << 12) | (next(1)? << 6) | next(2)?, 4),
    })
}

/// Whether `text` holds a code point whose engine class some admitted
/// property-data pair moves.
///
/// Eight bytes at a time, the scan skips every word whose bytes all lie
/// below the first byte any such code point can start with (so an ASCII
/// text, or one of Latin with accents, returns at once); in the other words
/// it looks at each byte, and a character whose leading byte can start one
/// is tested first by its 64-code-point block, from its leading bytes, and
/// only on a block that holds one by decoding it and searching the ranges.
/// A three-byte character found that way, and the three-byte characters
/// right after it, take that block test directly, one after the other.
pub(crate) fn holds_moved(text: &str) -> bool {
    let bytes = text.as_bytes();
    let mut position = 0;
    while position < bytes.len() {
        if WORD_SKIP {
            while let Some(word) = bytes
                .get(position..position + 8)
                .and_then(|chunk| <[u8; 8]>::try_from(chunk).ok())
            {
                if word_reaches_lead_min(u64::from_le_bytes(word)) {
                    break;
                }
                position += 8;
            }
        }
        let end = bytes.len().min(position + 8);
        let Some(start) = bytes
            .get(position..end)
            .and_then(|window| {
                window
                    .iter()
                    .position(|&byte| LEAD_MAY_HOLD[usize::from(byte)])
            })
            .map(|offset| position + offset)
        else {
            position = end;
            continue;
        };
        // `start` begins a character (a continuation byte never may hold).
        if bytes[start] & 0xF0 == 0xE0 {
            // A three-byte character (Devanagari and other Indic scripts,
            // part of Hangul): it and the three-byte characters that follow
            // it are tested one after the other, each by the 64-code-point
            // block its first two bytes name, without returning to the byte
            // search. A byte from 0xE0 to 0xEF only ever leads a character,
            // so each step lands on a character boundary.
            position = start;
            while let Some(&[lead, next, _]) = bytes.get(position..position + 3) {
                if lead & 0xF0 != 0xE0 {
                    break;
                }
                let block = (u32::from(lead & 0x0F) << 6) | u32::from(next & 0x3F);
                if block_holds_moved(block) {
                    match text.get(position..).and_then(|rest| rest.chars().next()) {
                        Some(character) if !is_moved(u32::from(character)) => {}
                        // A hit, or (unreachable for a `str`) no character here.
                        _ => return true,
                    }
                }
                position += 3;
            }
            if position == start {
                // A sequence cut short, unreachable for a `str`.
                return true;
            }
            continue;
        }
        let Some((block, width)) = block_at(bytes, start) else {
            // Unreachable for a `str`; answer in the safe direction.
            return true;
        };
        if block_holds_moved(block) {
            match text.get(start..).and_then(|rest| rest.chars().next()) {
                Some(character) if !is_moved(u32::from(character)) => {}
                // A hit, or (unreachable for a `str`) no character here.
                _ => return true,
            }
        }
        position = start + width;
    }
    false
}

// ---------------------------------------------------------------------------
// The standing of a build
// ---------------------------------------------------------------------------

/// How the build script located the lockfile it read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LocatedBy {
    /// `TOKTIER_CARGO_LOCK` named it.
    Named,
    /// A `Cargo.lock` above `OUT_DIR`.
    OutDir,
    /// Found only above this crate's manifest (the workspace fallback).
    /// Never counts as read: see [`decide_standing`].
    Manifest,
    /// No lockfile was located.
    None,
}

impl LocatedBy {
    /// Read the build script's word; an unknown word reads as `None`, which
    /// declines the fast route rather than admitting it.
    pub(crate) fn parse(word: &str) -> Self {
        match word {
            "named" => Self::Named,
            "out_dir" => Self::OutDir,
            "manifest" => Self::Manifest,
            _ => Self::None,
        }
    }
}

/// One copy of `icu_properties` or `icu_properties_data` in the governing
/// lockfile, as the build script recorded it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LockCopy {
    pub(crate) name: String,
    pub(crate) version: String,
    pub(crate) source: Option<String>,
    pub(crate) checksum: Option<String>,
}

/// Read the build script's property-data record: one record per copy,
/// separated by [`RECORD_SEPARATOR`], each `name`, `version`, `source`,
/// `checksum` separated by [`FIELD_SEPARATOR`] (an empty source or checksum
/// is an absent one). A record of another shape is refused.
pub(crate) fn parse_copies(recorded: &str) -> Result<Vec<LockCopy>, String> {
    if recorded.is_empty() {
        return Ok(Vec::new());
    }
    recorded
        .split(RECORD_SEPARATOR)
        .map(|record| {
            let fields: Vec<&str> = record.split(FIELD_SEPARATOR).collect();
            match fields.as_slice() {
                [name, version, source, checksum] if !name.is_empty() && !version.is_empty() => {
                    Ok(LockCopy {
                        name: (*name).to_owned(),
                        version: (*version).to_owned(),
                        source: (!source.is_empty()).then(|| (*source).to_owned()),
                        checksum: (!checksum.is_empty()).then(|| (*checksum).to_owned()),
                    })
                }
                _ => Err(format!(
                    "the build script's property-data record {record:?} is unreadable"
                )),
            }
        })
        .collect()
}

/// What a build's lockfile reading makes of its property data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Standing {
    /// Both crates are the judged registry copies and their reference
    /// records read certified: every call goes where it goes without the
    /// guard.
    Judged,
    /// Every copy is on the table: the accelerated routes run, and a text
    /// holding a code point of the set goes to the reference engine.
    Guarded {
        /// The resolved copies, as `name version` joined by `, `.
        resolved: String,
    },
    /// The lockfile was read and holds a copy the table does not speak for,
    /// or the compiled data was replaced at build time.
    Untabled {
        /// Which copy, and why.
        reason: String,
        /// What makes the build one the table speaks for.
        remedy: String,
    },
    /// An encode check contradicted a judged reading for this runtime.
    Contradicted { reason: String },
    /// No lockfile that governs this build was read.
    Unread {
        /// How the build script located the lockfile it did read, if any.
        located_by: LocatedBy,
    },
}

impl Standing {
    /// Whether the fast CPU route may run on this build (guarded or not).
    #[cfg(test)]
    pub(crate) fn admits_fast_route(&self) -> bool {
        matches!(self, Self::Judged | Self::Guarded { .. })
    }

    /// Whether texts must be scanned with [`holds_moved`].
    #[cfg(test)]
    pub(crate) fn is_guarded(&self) -> bool {
        matches!(self, Self::Guarded { .. })
    }
}

/// An untabled standing whose remedy is to align the lockfile; `copies`
/// are the copies of major version 2 the lockfile holds, as far as known.
fn untabled(reason: String, copies: &[LockCopy]) -> Standing {
    Standing::Untabled {
        reason,
        remedy: remedy_for(copies),
    }
}

/// The major version of the property crates the engine links: its
/// requirement is a caret one on 2.0.2.
const LINKED_MAJOR: &str = "2";

/// Whether a copy is of the major version the engine links. A copy of
/// another major version (an `icu_properties` 1.5 that an older dependency
/// brings in, say) is a separate crate to Cargo and is never the one the
/// engine reads its classes from.
fn is_linked_major(copy: &LockCopy) -> bool {
    copy.version.split(['.', '-', '+']).next() == Some(LINKED_MAJOR)
}

/// What to do about an untabled or unread build, in one sentence.
fn remedy() -> String {
    remedy_for(&[])
}

/// The same, naming each resolved copy of major version 2 in `copies` by
/// its version (`--package icu_properties@2.4.0`), so that the command is
/// not ambiguous when the lockfile also holds a copy of another major
/// version.
fn remedy_for(copies: &[LockCopy]) -> String {
    let judged: Vec<String> = ADMITTED_COPIES
        .iter()
        .filter(|copy| copy.judged)
        .map(|judged| {
            let package = match copies.iter().find(|copy| copy.name == judged.name) {
                Some(copy) => {
                    format!("{}@{}", judged.name, copy.version)
                }
                None => format!("{}@{LINKED_MAJOR}", judged.name),
            };
            format!(
                "`cargo update --package {package} --precise {}`",
                judged.version
            )
        })
        .collect();
    format!(
        "align the lockfile with the judged property data ({}), or set {CARGO_LOCK_ENV} at \
         build time to the absolute path of the lockfile that governs this build",
        judged.join(" and ")
    )
}

/// What `Policy::Experimental` does on an untabled or unread build.
const EXPERIMENTAL: &str = "under Policy::Experimental the route runs and only texts holding a \
                            listed code point go to the reference engine; the list was not \
                            made for this data, so the other ids are unchecked";

impl fmt::Display for Standing {
    /// The standing as `RuntimeBuildFacts` reports it.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Judged => formatter.write_str("judged"),
            Self::Contradicted { reason } => write!(
                formatter,
                "untabled: judged property-data reading contradicted by an encode check: {reason}; \
                 the fast CPU route is declined, including under Policy::Experimental; \
                 rebuild with the consuming build's actual lockfile (TOKTIER_CARGO_LOCK must \
                 be absolute), use --locked with cargo install --path, or align the actual \
                 property data with the judged copies"
            ),
            Self::Guarded { resolved } => write!(
                formatter,
                "guarded: the property data resolves to {resolved}; texts holding one of the \
                 {MOVED_CODE_POINTS} listed code points (every code point whose class differs \
                 from the judged data's in some listed copy) are encoded on the reference engine"
            ),
            Self::Untabled { reason, remedy } => write!(
                formatter,
                "untabled: {reason}, so the fast CPU route is not built ({EXPERIMENTAL}); \
                 {remedy}"
            ),
            Self::Unread { located_by } => {
                let how = match located_by {
                    LocatedBy::Manifest => {
                        "the only lockfile found lies above this crate's own manifest, and the \
                         build cannot tell whether that file governs it (it does for a build of \
                         this crate's own workspace, not for a build that consumes this crate \
                         from another tree)"
                    }
                    _ => {
                        "no lockfile governing this build was located, or the value of \
                         TOKTIER_CARGO_LOCK was refused (it must be an absolute path outside this \
                         crate's own directory)"
                    }
                };
                write!(
                    formatter,
                    "unread: {how}, so the property data this build resolved is unknown and the \
                     fast CPU route is not built ({EXPERIMENTAL}); {}",
                    remedy()
                )
            }
        }
    }
}

/// Decide a build's standing from what its build script read.
///
/// - `located_by`: how the governing lockfile was located;
/// - `recorded`: the build script's property-data record ([`parse_copies`]);
/// - `references_certified`: whether the existing reference records of both
///   crates read certified. When they do not, the standing is never
///   [`Standing::Judged`], whatever this reading says.
///
/// A lockfile found only above this crate's own manifest
/// ([`LocatedBy::Manifest`]) never counts as read. It is the right file for
/// a build of this crate's own workspace with a target directory outside
/// the tree, and the wrong one for a path or `git` consumer in the same
/// layout, and nothing a build can observe tells the two apart in every
/// case: Cargo hands the library `CARGO_PRIMARY_PACKAGE`, but does not
/// rebuild the library when that variable changes, so a library compiled
/// once keeps whichever answer it got first. Such a build reads
/// [`Standing::Unread`] until `TOKTIER_CARGO_LOCK` names its lockfile.
pub(crate) fn decide_standing(
    located_by: LocatedBy,
    recorded: &str,
    references_certified: bool,
) -> Standing {
    let read = match located_by {
        LocatedBy::Named | LocatedBy::OutDir => true,
        LocatedBy::Manifest | LocatedBy::None => false,
    };
    if !read {
        return Standing::Unread { located_by };
    }
    let copies = match parse_copies(recorded) {
        Ok(copies) => copies,
        Err(reason) => return untabled(reason, &[]),
    };
    if let Some(copy) = copies
        .iter()
        .find(|copy| copy.name != PROPERTIES_CRATE && copy.name != DATA_CRATE)
    {
        return untabled(
            format!(
                "the property-data record names another crate ({} {})",
                copy.name, copy.version
            ),
            &[],
        );
    }
    // Only copies of the major version the engine links decide; the others
    // stay in the record and are named beside the resolved copies.
    let (linked, others): (Vec<&LockCopy>, Vec<&LockCopy>) =
        copies.iter().partition(|copy| is_linked_major(copy));
    let linked_copies: Vec<LockCopy> = linked.iter().map(|copy| (*copy).clone()).collect();
    for name in [PROPERTIES_CRATE, DATA_CRATE] {
        if !linked.iter().any(|copy| copy.name == name) {
            return untabled(
                format!(
                    "the governing lockfile holds no copy of {name} at major version \
                     {LINKED_MAJOR}, the one the engine links"
                ),
                &linked_copies,
            );
        }
    }
    let mut all_judged = true;
    for copy in &linked {
        let label = format!("{} {}", copy.name, copy.version);
        if copy.source.as_deref() != Some(table::REGISTRY_SOURCE) {
            return untabled(
                format!("{label} does not come from the crates.io registry"),
                &linked_copies,
            );
        }
        let Some(checksum) = copy.checksum.as_deref() else {
            return untabled(
                format!("the governing lockfile gives no checksum for {label}"),
                &linked_copies,
            );
        };
        let Some(admitted) = ADMITTED_COPIES.iter().find(|admitted| {
            admitted.name == copy.name
                && admitted.version == copy.version
                && admitted.checksum == checksum
        }) else {
            return untabled(
                format!(
                    "{label} (checksum {checksum}) is not among the property-data copies this \
                     release was judged against"
                ),
                &linked_copies,
            );
        };
        all_judged &= admitted.judged;
    }
    if all_judged && references_certified {
        return Standing::Judged;
    }
    let label = |copies: &[&LockCopy]| {
        let mut labels: Vec<String> = copies
            .iter()
            .map(|copy| format!("{} {}", copy.name, copy.version))
            .collect();
        labels.sort();
        labels.join(", ")
    };
    let mut resolved = label(&linked);
    if !others.is_empty() {
        resolved.push_str(&format!(
            " (beside {}, which the engine does not link)",
            label(&others)
        ));
    }
    Standing::Guarded { resolved }
}

/// Decide a build's standing as [`decide_standing`] does, first asking
/// whether `ICU4X_DATA_DIR` was set when this crate was built
/// (`data_dir_set`).
///
/// Every listed version of `icu_properties_data` compiles the baked data of
/// that directory in place of its own when the variable is set. The
/// lockfile then still names the copy whose data is not the data compiled,
/// so no reading of the lockfile speaks for the build: it reads
/// [`Standing::Untabled`] with a reason and a remedy of its own.
pub(crate) fn decide_build_standing(
    data_dir_set: bool,
    located_by: LocatedBy,
    recorded: &str,
    references_certified: bool,
) -> Standing {
    if data_dir_set {
        return Standing::Untabled {
            reason: format!(
                "{DATA_DIR_ENV} was set when this crate was built, so the property data \
                 compiled into it is that directory's and not the data of the copies the \
                 lockfile names"
            ),
            remedy: format!(
                "unset {DATA_DIR_ENV} and rebuild, so the build compiles the data the lockfile \
                 names"
            ),
        };
    }
    decide_standing(located_by, recorded, references_certified)
}

// ---------------------------------------------------------------------------
// This build's standing and what each call does with it
// ---------------------------------------------------------------------------

/// How the build script located the lockfile it read, as recorded.
pub(crate) const LOCATED_BY_RECORD: &str = env!("TOKTIER_RUST_API_LOCK_LOCATED_BY");
/// The build script's property-data record ([`parse_copies`]).
pub(crate) const PROPERTY_DATA_RECORD: &str = env!("TOKTIER_RUST_API_PROPERTY_DATA");
/// `set` when `ICU4X_DATA_DIR` was set while this crate was built, empty
/// otherwise.
pub(crate) const DATA_DIR_RECORD: &str = env!("TOKTIER_RUST_API_PROPERTY_DATA_DIR");

/// Whether the existing reference records of both property crates read
/// certified. A crate with no record counts as not certified, so the two
/// readings can only disagree in the safe direction.
fn references_certified() -> bool {
    let records = crate::behavior_version::reference_facts();
    [PROPERTIES_CRATE, DATA_CRATE].iter().all(|name| {
        records
            .iter()
            .any(|record| record.package == *name && record.certified)
    })
}

/// This build's standing, decided once per process from what its build
/// script read.
pub(crate) fn standing() -> &'static Standing {
    static STANDING: std::sync::OnceLock<Standing> = std::sync::OnceLock::new();
    STANDING.get_or_init(|| {
        decide_build_standing(
            !DATA_DIR_RECORD.is_empty(),
            LocatedBy::parse(LOCATED_BY_RECORD),
            PROPERTY_DATA_RECORD,
            references_certified(),
        )
    })
}

/// What a tokenizer built under one standing and one policy does.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Handling {
    /// The calls go where they go without the guard: no scan, no second
    /// router.
    NoGuard,
    /// The accelerated routes run, and every text holding a code point of
    /// the set goes to a reference-only router.
    Guard,
    /// The fast CPU route is not built, for this reason.
    Decline(crate::ReasonCode),
}

/// The one place an untabled or unread build is handled.
///
/// [`Policy::Experimental`](crate::Policy::Experimental) runs both as
/// guarded builds; every other policy declines the fast CPU route there.
/// Running an unread build guarded under every policy instead would be the
/// `Standing::Unread` arm alone.
pub(crate) fn handling(standing: &Standing, policy: crate::Policy) -> Handling {
    let experimental = policy == crate::Policy::Experimental;
    match standing {
        Standing::Judged => Handling::NoGuard,
        Standing::Contradicted { .. } => {
            Handling::Decline(crate::ReasonCode::PropertyDataContradicted)
        }
        Standing::Guarded { .. } => Handling::Guard,
        Standing::Untabled { .. } if experimental => Handling::Guard,
        Standing::Unread { .. } if experimental => Handling::Guard,
        Standing::Untabled { .. } => Handling::Decline(crate::ReasonCode::PropertyDataUntabled),
        Standing::Unread { .. } => Handling::Decline(crate::ReasonCode::PropertyDataUnread),
    }
}

/// The router a text goes to, and whether the guard sent it there: the
/// reference-only router when there is one and `text` holds a code point
/// of the set, the ordinary router otherwise.
pub(crate) fn router_for<'a>(
    ordinary: &'a NativeRouter,
    reference_only: Option<&'a NativeRouter>,
    text: &str,
) -> (&'a NativeRouter, bool) {
    match reference_only {
        Some(reference_only) if holds_moved(text) => (reference_only, true),
        _ => (ordinary, false),
    }
}

/// The session engine of a tokenizer: the ordinary router, and on a
/// guarded tokenizer the reference-only router beside it.
///
/// Every store operation that encodes (seed, append, overwrite, and the
/// durable load) is handed this one type.
///
/// - `encode(text)` runs on the reference-only router when `text` holds a
///   code point of the set;
/// - `append(tail, delta)` runs on the reference-only router when the
///   unsealed tail or the delta holds one;
/// - `last_certified_boundary` answers no boundary for a tail that holds
///   one, and the ordinary router's answer otherwise;
/// - `witness_category` is the ordinary router's, so the stored records
///   keep one category whichever router served a call.
///
/// A seal is therefore only ever certified on a tail without such a code
/// point, by the code a judged build runs on the same characters. The tail
/// state is text, ids and character spans whichever engine filled it, so
/// the two routers may take turns on one session. A session whose unsealed
/// tail holds such a code point keeps its last seal, and every later append
/// re-encodes that whole tail on the reference engine: exact, at a cost that
/// grows with the tail until the session is overwritten.
pub(crate) struct GuardedEncoder<'a> {
    ordinary: &'a NativeRouter,
    reference_only: Option<&'a NativeRouter>,
    routed: std::cell::Cell<bool>,
}

impl<'a> GuardedEncoder<'a> {
    pub(crate) fn new(
        ordinary: &'a NativeRouter,
        reference_only: Option<&'a NativeRouter>,
    ) -> Self {
        Self {
            ordinary,
            reference_only,
            routed: std::cell::Cell::new(false),
        }
    }

    /// Whether any call through this value went to the reference-only
    /// router.
    pub(crate) fn guard_routed(&self) -> bool {
        self.routed.get()
    }

    fn pick(&self, hit: impl FnOnce() -> bool) -> &'a NativeRouter {
        match self.reference_only {
            Some(reference_only) if hit() => {
                self.routed.set(true);
                reference_only
            }
            _ => self.ordinary,
        }
    }
}

impl SessionEncoder for GuardedEncoder<'_> {
    fn encode(&self, text: &str) -> Result<Encoding, EngineError> {
        self.pick(|| holds_moved(text)).encode(text)
    }

    fn append(&self, tail: &mut TailState, delta: &str) -> Result<AppendReport, EngineError> {
        self.pick(|| holds_moved(tail.text()) || holds_moved(delta))
            .append(tail, delta)
    }

    fn last_certified_boundary(
        &self,
        tail: &TailState,
        floor_char: u64,
        ceil_char: u64,
    ) -> Result<Option<BoundaryCut>, EngineError> {
        if self.reference_only.is_some() && holds_moved(tail.text()) {
            return Ok(None);
        }
        self.ordinary
            .last_certified_boundary(tail, floor_char, ceil_char)
    }

    fn witness_category(&self) -> WitnessCategory {
        self.ordinary.witness_category()
    }
}

/// The guard's routes, sessions and standings through the public calls,
/// under a standing the test seam forces.
#[cfg(test)]
#[path = "property_guard_tests.rs"]
mod wiring_tests;

#[cfg(test)]
mod tests {
    use super::{
        decide_build_standing, decide_standing, holds_moved, is_moved, parse_copies, LocatedBy,
        Standing, ADMITTED_COPIES, DATA_CRATE, FIELD_SEPARATOR, MOVED_CODE_POINTS, MOVED_RANGES,
        PROPERTIES_CRATE, RECORD_SEPARATOR,
    };

    const REGISTRY: &str = "registry+https://github.com/rust-lang/crates.io-index";

    fn naive(code_point: u32) -> bool {
        MOVED_RANGES
            .iter()
            .any(|&(low, high)| (low..=high).contains(&code_point))
    }

    fn scalar(code_point: u32) -> Option<String> {
        char::from_u32(code_point).map(String::from)
    }

    /// The texts of the review that found the difference, and one for the
    /// one already-assigned code point whose category moved (U+0295, Ll at
    /// the judged version and Lo after it).
    const HITS: &[&str] = &[
        "1\u{11DE1}2345",
        "it's\u{323B0}'s \u{323B0}'ll",
        "abc \u{20C1}def ghi",
        "Hello \u{0295}\u{2022}\u{1D25}\u{2022}\u{0294} World a\u{0295}b A\u{0295}B",
    ];

    /// Texts of Unicode 16.0 that no admitted pair classifies differently.
    const CLEAN: &[&str] = &[
        "",
        "plain ascii text 12345",
        "caf\u{e9} na\u{ef}ve \u{fc}ber stra\u{df}e",
        "\u{4e2d}\u{6587}\u{6d4b}\u{8bd5} 12345 \u{30c6}\u{30b9}\u{30c8}",
        "\u{1F600} \u{1FAE9} \u{1FAC6} \u{1FABE} \u{1FADC}",
        "\u{0294} \u{0296}",
    ];

    #[test]
    fn the_table_is_the_generated_one() {
        assert!(!MOVED_RANGES.is_empty());
        assert_eq!(MOVED_RANGES[0], (0x0295, 0x0295));
        let total: u32 = MOVED_RANGES.iter().map(|&(low, high)| high - low + 1).sum();
        assert_eq!(total, MOVED_CODE_POINTS);
        for pair in MOVED_RANGES.windows(2) {
            assert!(pair[0].1 + 1 < pair[1].0, "{pair:?}");
        }
    }

    #[test]
    fn every_range_end_is_in_and_every_neighbour_is_out() {
        for &(low, high) in MOVED_RANGES {
            for code_point in [low, high] {
                assert!(is_moved(code_point), "U+{code_point:04X}");
                if let Some(text) = scalar(code_point) {
                    assert!(holds_moved(&text), "U+{code_point:04X}");
                }
            }
            for code_point in [low.wrapping_sub(1), high + 1] {
                assert!(!is_moved(code_point), "U+{code_point:04X}");
                if let Some(text) = scalar(code_point) {
                    assert!(!holds_moved(&text), "U+{code_point:04X}");
                }
            }
        }
    }

    #[test]
    fn every_code_point_answers_as_the_ranges_say() {
        for code_point in 0..0x11_0000 {
            let expected = naive(code_point);
            assert_eq!(is_moved(code_point), expected, "U+{code_point:04X}");
            if let Some(text) = scalar(code_point) {
                assert_eq!(holds_moved(&text), expected, "U+{code_point:04X}");
            }
        }
    }

    #[test]
    fn a_hit_is_found_at_every_offset_and_after_every_kind_of_prefix() {
        let prefixes = ["a", "\u{e9}", "\u{4e2d}", "\u{1F600}", "\u{0294}"];
        let mut probes: Vec<u32> = MOVED_RANGES.iter().flat_map(|&(l, h)| [l, h]).collect();
        probes.dedup();
        for &code_point in &probes {
            let Some(hit) = scalar(code_point) else {
                continue;
            };
            for prefix in prefixes {
                for repeat in 0..18 {
                    let before = prefix.repeat(repeat);
                    for after in ["", "x", "tail text after it", "\u{e9}\u{e9}"] {
                        let text = format!("{before}{hit}{after}");
                        assert!(holds_moved(&text), "{text:?}");
                        let clean = format!("{before}{after}");
                        assert!(!holds_moved(&clean), "{clean:?}");
                    }
                }
            }
        }
    }

    #[test]
    fn the_review_texts_are_hits_and_clean_texts_are_not() {
        for text in HITS {
            assert!(holds_moved(text), "{text:?}");
        }
        for text in CLEAN {
            assert!(!holds_moved(text), "{text:?}");
        }
        let long_clean = "word ".repeat(200_000);
        assert!(!holds_moved(&long_clean));
        let long_hit = format!("{long_clean}1\u{11DE1}2345");
        assert!(holds_moved(&long_hit));
    }

    // -- standing -----------------------------------------------------------

    fn judged(name: &str) -> &'static super::table::AdmittedCopy {
        ADMITTED_COPIES
            .iter()
            .find(|copy| copy.name == name && copy.judged)
            .expect("a judged copy")
    }

    fn tabled(name: &str, version: &str) -> &'static super::table::AdmittedCopy {
        ADMITTED_COPIES
            .iter()
            .find(|copy| copy.name == name && copy.version == version)
            .expect("an admitted copy")
    }

    fn record(name: &str, version: &str, source: &str, checksum: &str) -> String {
        [name, version, source, checksum].join(&FIELD_SEPARATOR.to_string())
    }

    fn of(copy: &super::table::AdmittedCopy) -> String {
        record(copy.name, copy.version, REGISTRY, copy.checksum)
    }

    fn records(parts: &[String]) -> String {
        parts.join(&RECORD_SEPARATOR.to_string())
    }

    fn judged_record() -> String {
        records(&[of(judged(PROPERTIES_CRATE)), of(judged(DATA_CRATE))])
    }

    fn guarded_record() -> String {
        records(&[
            of(tabled(PROPERTIES_CRATE, "2.3.0")),
            of(tabled(DATA_CRATE, "2.3.0")),
        ])
    }

    fn untabled(standing: &Standing) -> bool {
        matches!(standing, Standing::Untabled { .. })
    }

    #[test]
    fn the_judged_copies_are_the_workspace_lockfiles() {
        // The packaged byte copy of the workspace lockfile, present in a
        // checkout and in the published crate alike.
        let lock = include_str!("../data/build/judged_dependencies.lock");
        for name in [PROPERTIES_CRATE, DATA_CRATE] {
            let copy = judged(name);
            let block = format!(
                "name = \"{}\"\nversion = \"{}\"\nsource = \"{REGISTRY}\"\nchecksum = \"{}\"\n",
                copy.name, copy.version, copy.checksum
            );
            assert!(lock.contains(&block), "{block}");
            assert_eq!(
                ADMITTED_COPIES
                    .iter()
                    .filter(|other| other.name == name && other.judged)
                    .count(),
                1
            );
        }
    }

    #[test]
    fn a_located_lockfile_with_the_judged_copies_is_judged() {
        for located_by in [LocatedBy::Named, LocatedBy::OutDir] {
            assert_eq!(
                decide_standing(located_by, &judged_record(), true),
                Standing::Judged
            );
        }
    }

    #[test]
    fn the_workspace_fallback_never_counts_as_read() {
        // A lockfile found only above this crate's manifest reads Unread
        // whatever it holds, judged, guarded or off the table.
        for recorded in [judged_record(), guarded_record(), String::new()] {
            let standing = decide_standing(LocatedBy::Manifest, &recorded, true);
            assert_eq!(
                standing,
                Standing::Unread {
                    located_by: LocatedBy::Manifest
                }
            );
            assert!(!standing.admits_fast_route());
            assert!(standing.to_string().contains("TOKTIER_CARGO_LOCK"));
        }
        assert_eq!(LocatedBy::parse("manifest"), LocatedBy::Manifest);
    }

    #[test]
    fn no_located_lockfile_is_unread() {
        for recorded in [String::new(), judged_record()] {
            let standing = decide_standing(LocatedBy::None, &recorded, true);
            assert_eq!(
                standing,
                Standing::Unread {
                    located_by: LocatedBy::None
                }
            );
            assert!(!standing.admits_fast_route());
        }
        assert_eq!(LocatedBy::parse("elsewhere"), LocatedBy::None);
        assert_eq!(LocatedBy::parse(""), LocatedBy::None);
    }

    #[test]
    fn every_tabled_pair_is_guarded() {
        let standing = decide_standing(LocatedBy::OutDir, &guarded_record(), true);
        assert_eq!(
            standing,
            Standing::Guarded {
                resolved: "icu_properties 2.3.0, icu_properties_data 2.3.0".to_owned()
            }
        );
        assert!(standing.admits_fast_route());
        // A judged code copy beside a tabled data copy is not judged.
        let mixed = records(&[
            of(judged(PROPERTIES_CRATE)),
            of(tabled(DATA_CRATE, "2.0.0")),
        ]);
        assert!(decide_standing(LocatedBy::Named, &mixed, true).is_guarded());
    }

    #[test]
    fn uncertified_reference_records_are_never_judged() {
        let standing = decide_standing(LocatedBy::OutDir, &judged_record(), false);
        assert!(standing.is_guarded(), "{standing:?}");
    }

    #[test]
    fn two_copies_of_one_crate_are_judged_copy_by_copy() {
        let both_tabled = records(&[
            of(judged(PROPERTIES_CRATE)),
            of(judged(DATA_CRATE)),
            of(tabled(DATA_CRATE, "2.4.0")),
        ]);
        assert!(decide_standing(LocatedBy::OutDir, &both_tabled, true).is_guarded());
        // A copy at major version 2 off the table is untabled.
        let one_off = records(&[
            of(judged(PROPERTIES_CRATE)),
            of(judged(DATA_CRATE)),
            record(PROPERTIES_CRATE, "2.9.0", REGISTRY, &"a".repeat(64)),
        ]);
        assert!(untabled(&decide_standing(
            LocatedBy::OutDir,
            &one_off,
            true
        )));
    }

    #[test]
    fn only_copies_of_major_version_two_decide() {
        // Copies of another major version, as an older dependency brings
        // them in (with or without a registry source or checksum).
        let old = [
            record(PROPERTIES_CRATE, "1.5.1", REGISTRY, &"a".repeat(64)),
            record(DATA_CRATE, "1.5.1", REGISTRY, &"d".repeat(64)),
            record(PROPERTIES_CRATE, "3.0.0", "", ""),
        ];
        // Beside the judged pair: judged.
        let mut beside_judged = vec![of(judged(PROPERTIES_CRATE)), of(judged(DATA_CRATE))];
        beside_judged.extend(old.iter().cloned());
        assert_eq!(
            decide_standing(LocatedBy::OutDir, &records(&beside_judged), true),
            Standing::Judged
        );
        // Beside a listed newer pair: guarded, the others named.
        let mut beside_newer = vec![
            of(tabled(PROPERTIES_CRATE, "2.4.0")),
            of(tabled(DATA_CRATE, "2.4.0")),
        ];
        beside_newer.extend(old.iter().cloned());
        let standing = decide_standing(LocatedBy::Named, &records(&beside_newer), true);
        assert_eq!(
            standing,
            Standing::Guarded {
                resolved: "icu_properties 2.4.0, icu_properties_data 2.4.0 (beside \
                           icu_properties 1.5.1, icu_properties 3.0.0, icu_properties_data \
                           1.5.1, which the engine does not link)"
                    .to_owned()
            }
        );
        // No copy of major version 2 at all: untabled.
        for alone in [
            records(&old[..2]),
            records(&[record(PROPERTIES_CRATE, "3.0.0", REGISTRY, &"e".repeat(64))]),
            records(&[
                of(judged(PROPERTIES_CRATE)),
                record(DATA_CRATE, "1.5.1", REGISTRY, &"d".repeat(64)),
            ]),
        ] {
            let standing = decide_standing(LocatedBy::OutDir, &alone, true);
            assert!(untabled(&standing), "{alone:?}: {standing:?}");
            assert!(
                standing.to_string().contains("major version 2"),
                "{standing}"
            );
        }
    }

    #[test]
    fn the_remedy_names_the_resolved_copy_by_its_version() {
        let newer = records(&[
            of(judged(PROPERTIES_CRATE)),
            record(DATA_CRATE, "2.9.0", REGISTRY, &"b".repeat(64)),
            record(PROPERTIES_CRATE, "1.5.1", REGISTRY, &"a".repeat(64)),
        ]);
        let line = decide_standing(LocatedBy::OutDir, &newer, true).to_string();
        let data = judged(DATA_CRATE);
        let code = judged(PROPERTIES_CRATE);
        assert!(
            line.contains(&format!(
                "`cargo update --package icu_properties_data@2.9.0 --precise {}`",
                data.version
            )),
            "{line}"
        );
        // Even a copy already at the judged version needs a disambiguator
        // when another major version is present in the lockfile.
        assert!(
            line.contains(&format!(
                "`cargo update --package icu_properties@{} --precise {}`",
                code.version, code.version
            )),
            "{line}"
        );
        assert!(!line.contains("icu_properties@1.5.1"), "{line}");
    }

    #[test]
    fn copies_off_the_table_are_untabled() {
        let data = judged(DATA_CRATE);
        let code = of(judged(PROPERTIES_CRATE));
        let cases = [
            // A version the table does not list.
            records(&[
                code.clone(),
                record(DATA_CRATE, "2.5.0", REGISTRY, &"b".repeat(64)),
            ]),
            // A judged version with another checksum.
            records(&[
                code.clone(),
                record(DATA_CRATE, data.version, REGISTRY, &"c".repeat(64)),
            ]),
            // No checksum.
            records(&[code.clone(), record(DATA_CRATE, data.version, REGISTRY, "")]),
            // Another source.
            records(&[
                code.clone(),
                record(
                    DATA_CRATE,
                    data.version,
                    "git+https://example.invalid/icu4x#0",
                    data.checksum,
                ),
            ]),
            // A path copy (no source).
            records(&[code.clone(), record(DATA_CRATE, data.version, "", "")]),
            // A crate missing from the lockfile.
            code.clone(),
            of(data),
            String::new(),
            // A record of another shape.
            format!("{code}{FIELD_SEPARATOR}extra"),
            records(&[
                code.clone(),
                record("icu_other", "2.0.0", REGISTRY, data.checksum),
            ]),
        ];
        for recorded in &cases {
            for located_by in [LocatedBy::Named, LocatedBy::OutDir] {
                let standing = decide_standing(located_by, recorded, true);
                assert!(untabled(&standing), "{recorded:?}: {standing:?}");
                assert!(!standing.admits_fast_route());
            }
        }
    }

    #[test]
    fn a_replaced_data_directory_is_untabled_with_its_own_remedy() {
        // Whatever the lockfile says and however it was located.
        for located_by in [
            LocatedBy::Named,
            LocatedBy::OutDir,
            LocatedBy::Manifest,
            LocatedBy::None,
        ] {
            for recorded in [judged_record(), guarded_record(), String::new()] {
                let standing = decide_build_standing(true, located_by, &recorded, true);
                assert!(untabled(&standing), "{located_by:?}: {standing:?}");
                assert!(!standing.admits_fast_route());
                let line = standing.to_string();
                assert!(
                    line.starts_with("untabled: ICU4X_DATA_DIR was set"),
                    "{line}"
                );
                assert!(line.contains("unset ICU4X_DATA_DIR"), "{line}");
                assert!(!line.contains("cargo update"), "{line}");
            }
        }
        // Unset, the lockfile decides as before.
        assert_eq!(
            decide_build_standing(false, LocatedBy::OutDir, &judged_record(), true),
            Standing::Judged
        );
        assert!(
            decide_build_standing(false, LocatedBy::Named, &guarded_record(), true).is_guarded()
        );
    }

    #[test]
    fn the_record_reads_back_what_the_build_script_writes() {
        let copies = parse_copies(&judged_record()).expect("readable");
        assert_eq!(copies.len(), 2);
        assert_eq!(copies[0].name, PROPERTIES_CRATE);
        assert_eq!(copies[0].source.as_deref(), Some(REGISTRY));
        assert_eq!(parse_copies("").expect("empty"), Vec::new());
        assert!(parse_copies("icu_properties").is_err());
        let blank = record(DATA_CRATE, "2.0.1", "", "");
        let copies = parse_copies(&blank).expect("readable");
        assert_eq!(copies[0].source, None);
        assert_eq!(copies[0].checksum, None);
    }

    #[test]
    fn the_standing_names_the_remedy() {
        let untabled = decide_standing(LocatedBy::OutDir, "", true).to_string();
        let unread = decide_standing(LocatedBy::None, "", true).to_string();
        for line in [&untabled, &unread] {
            assert!(line.contains("TOKTIER_CARGO_LOCK"), "{line}");
            assert!(line.contains("absolute path"), "{line}");
            assert!(
                line.contains("cargo update --package icu_properties@2 --precise"),
                "{line}"
            );
            assert!(
                line.contains("cargo update --package icu_properties_data@2 --precise"),
                "{line}"
            );
        }
        assert!(untabled.starts_with("untabled: "));
        assert!(unread.starts_with("unread: "));
        assert_eq!(Standing::Judged.to_string(), "judged");
        let guarded = decide_standing(LocatedBy::OutDir, &guarded_record(), true);
        let line = guarded.to_string();
        assert!(line.starts_with("guarded: "), "{line}");
        assert!(line.contains(&MOVED_CODE_POINTS.to_string()), "{line}");
        assert!(line.contains("icu_properties_data 2.3.0"), "{line}");
    }
}

/// A small contradiction check on the already-admitted engine. A match only
/// retains the lockfile's standing; it never admits unknown data. These
/// contexts exercise number, letter/contraction and punctuation boundaries.
/// Each release must run them on every accelerated family with judged and
/// deliberately mismatched linked data. No check is added to an encode call.
pub(crate) fn confirm_encodes(
    family: &str,
    engine: &toktier_routing_core::FastCpuEngine,
    reference: &toktier_routing_core::ReferenceEngine,
) -> Option<Standing> {
    check_encodes(family, |text| {
        let fast = engine.encode_ids(text).map_err(|error| error.to_string())?;
        let expected = reference
            .encode_ids(text, false)
            .map_err(|error| error.to_string())?;
        Ok(fast == expected)
    })
}

fn check_encodes(
    family: &str,
    mut agrees: impl FnMut(&str) -> Result<bool, String>,
) -> Option<Standing> {
    // All four points were unassigned in the judged data and are assigned
    // in the listed copies from 2.1 onward, including 2.4.0. These are
    // negative witnesses, not a fingerprint of a complete data release.
    for text in [
        "1\u{11de1}2345",
        "it's\u{323b0}'s \u{323b0}'ll",
        "9\u{1e6e0}9\u{1e6e0}87654321 x",
        "abc \u{20c1}def ghi",
    ] {
        let reason = match agrees(text) {
            Ok(true) => continue,
            Ok(false) => format!("family {family}, probe {text:?}: fast and reference ids differ"),
            Err(error) => {
                format!("family {family}, probe {text:?}: check could not complete ({error})")
            }
        };
        return Some(Standing::Contradicted { reason });
    }
    None
}

#[cfg(test)]
mod encode_confirmation_tests {
    use super::*;
    #[test]
    fn all_four_probe_contexts_must_agree() {
        let mut texts = Vec::new();
        assert_eq!(
            check_encodes("test", |text| {
                texts.push(text.to_owned());
                Ok(true)
            }),
            None
        );
        assert_eq!(texts.len(), 4);
        assert!(texts.iter().all(|text| holds_moved(text)));
        for failed in 0..4 {
            let mut seen = 0;
            let result = check_encodes("test", |_| {
                let equal = seen != failed;
                seen += 1;
                Ok(equal)
            });
            assert_eq!(seen, failed + 1);
            let standing = result.expect("a mismatch must decline");
            assert!(standing.to_string().contains("ids differ"));
            for policy in [
                crate::Policy::Supported,
                crate::Policy::Experimental,
                crate::Policy::RequireAccelerated,
            ] {
                assert_eq!(
                    handling(&standing, policy),
                    Handling::Decline(crate::ReasonCode::PropertyDataContradicted)
                );
            }
        }
    }
    #[test]
    fn a_probe_error_declines_and_names_the_remedy() {
        let standing = check_encodes("test", |_| Err("injected fault".into())).unwrap();
        let line = standing.to_string();
        for needle in [
            "untabled:",
            "judged",
            "contradicted",
            "injected fault",
            "TOKTIER_CARGO_LOCK",
            "--locked",
        ] {
            assert!(line.contains(needle), "{line}");
        }
    }
}