rlucene 0.1.0-alpha.3

A Rust port of Apache Lucene, a full-text search engine library
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use crate::core::codecs::CodecUtil;
use crate::core::store::data_input_ext::DataInputExt;
use crate::core::store::output_stream_data_output::OutputStreamDataOutput;
use crate::core::store::{ByteBuffersDataOutput, DataInput, DataOutput};
use crate::core::util::IOUtils;
use crate::core::util::close::Closeable;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::fst_impl::bit_table_util::BitTableUtil;
use crate::core::util::fst_impl::fst_reader::FstReader;
use crate::core::util::fst_impl::on_heap_fst_store::OnHeapFSTStore;
use crate::core::util::fst_impl::outputs::{Outputs, OutputsBound};
use core::fmt;
use std::cell::RefCell;
use std::fmt::{Display, Formatter};
use std::fs::File;
use std::path::Path;
use std::rc::Rc;

pub struct FST<O, F>
where
  O: Outputs,
{
  pub metadata: FSTMetadata<O>,
  pub outputs: O,
  /// Storage is prepared before the FST becomes readable. Each lookup owns its cursor.
  pub fst_reader: F,
}

impl<O> FST<O, OnHeapFSTStore>
where
  O: Outputs,
{
  /// Load a previously saved FST with a DataInput for metadata using an
  /// [`OnHeapFSTStore`] with `maxBlockBits` set to
  /// [`DEFAULT_MAX_BLOCK_BITS`]
  pub fn from_on_heap_store<DI>(metadata: FSTMetadata<O>, input: &mut DI) -> Result<Self>
  where
    DI: DataInput,
  {
    let store = OnHeapFSTStore::new(DEFAULT_MAX_BLOCK_BITS, input, metadata.num_bytes)?;
    Ok(Self::new(metadata, store))
  }
}

impl<O, F> FST<O, F>
where
  O: Outputs,
{
  /// Create the FST with a metadata object and a reader.
  pub fn new(metadata: FSTMetadata<O>, fst_reader: F) -> Self {
    Self {
      outputs: metadata.outputs.clone(),
      metadata,
      fst_reader,
    }
  }

  /// Create an FST from metadata and reader. Returns `None` if the metadata
  /// is `None`.
  pub fn from_fst_reader(metadata: FSTMetadata<O>, fst_reader: F) -> Option<Self> {
    Some(Self::new(metadata, fst_reader))
  }

  pub fn num_bytes(&self) -> i64 {
    self.metadata.num_bytes
  }

  pub fn get_empty_output(&self) -> Option<&Option<O::V>> {
    self.metadata.empty_output.as_ref()
  }

  pub fn metadata(&self) -> &FSTMetadata<O> {
    &self.metadata
  }
}

impl<O, F> FST<O, F>
where
  O: Outputs,
  F: FstReader,
{
  /// Save the FST to DataOutput.
  ///
  /// # Arguments
  ///
  /// * `metaOut` - the DataOutput to write the metadata to
  /// * `out` - the DataOutput to write the FST bytes to
  pub fn save<DO, DO2>(&mut self, meta_out: &mut DO, out: &mut DO2) -> Result<()>
  where
    DO: DataOutput,
    DO2: DataOutput,
  {
    self.metadata.save(meta_out)?;
    self.fst_reader.write_to(out)
  }
  pub fn save_with_same_data_out<DO>(&self, out: &mut DO) -> Result<()>
  where
    DO: DataOutput,
  {
    self.metadata.save(out)?;
    self.fst_reader.write_to(out)
  }

  /// Writes the automaton to a file.
  pub fn save_to_path<P>(&mut self, path: P) -> Result<()>
  where
    P: AsRef<Path>,
  {
    let file = File::create(path)?;
    let mut out = OutputStreamDataOutput::new(file);
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
      self.save_with_same_data_out(&mut out)
    }));
    let close_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| out.close()));
    IOUtils::use_or_suppress_caught_result(result, close_result)
  }
  /// Reads the automaton from a file.
  pub fn read_from_path(_path: &Path, _outputs: Rc<RefCell<O>>) -> Result<Self> {
    todo!()
  }
  /// Reads one BYTE1/2/4 label from the provided DataInput.
  pub fn read_label<DI>(&self, input: &mut DI) -> Result<i32>
  where
    DI: DataInput,
  {
    let input_type = self.metadata.input_type;
    let version = self.metadata.version;

    let v = match input_type {
      InputType::Byte1 => input.read_byte()? as i32,
      InputType::Byte2 => {
        let raw = input.read_short()?;
        if version < VERSION_LITTLE_ENDIAN {
          i32::from(raw.swap_bytes() as u16)
        } else {
          raw as u16 as i32
        }
      },
      InputType::Byte4 => input.read_vint()?,
    };
    Ok(v)
  }
  /// Reads the presence bits of a direct-addressing node.
  /// Actually we don't read them here — we just record the bit-table start
  /// position and skip.
  fn read_presence_bytes<T>(&self, arc: &mut Arc<O::V>, reader: &mut T) -> Result<()>
  where
    T: BytesReader,
  {
    debug_assert!(arc.bytes_per_arc > 0);
    debug_assert_eq!(arc.node_flags, ARCS_FOR_DIRECT_ADDRESSING);

    arc.bit_table_start = reader.get_position();
    let skip_bytes = get_num_presence_bytes(arc.num_arcs);
    reader.skip_bytes(skip_bytes as i64)?;
    Ok(())
  }
  /// Fills the virtual start arc, i.e., an empty incoming arc to the FST's
  /// start node, reusing the caller's arc.
  pub fn get_first_arc(&self, arc: &mut Arc<O::V>) {
    let (flags, final_output) = self.first_arc_state();
    arc.flags = flags;
    match (arc.next_final_output.as_mut(), final_output) {
      (Some(current), Some(output)) => current.assign_from(output),
      (_, None) => arc.next_final_output = None,
      (None, Some(output)) => arc.next_final_output = Some(output.clone()),
    }
    arc.output = None;
    // If there are no nodes, ie, the FST only accepts the
    // empty string, then startNode is 0
    arc.target = self.metadata.start_node;
  }
  /// Returns the virtual start arc without constructing default output slots.
  pub fn get_first_arc_owned(&self) -> Arc<O::V> {
    let (flags, final_output) = self.first_arc_state();
    Arc {
      label: 0,
      output: None,
      target: self.metadata.start_node,
      flags,
      next_final_output: final_output.cloned(),
      next_arc: 0,
      node_flags: 0,
      bytes_per_arc: 0,
      pos_arcs_start: 0,
      arc_idx: 0,
      num_arcs: 0,
      bit_table_start: 0,
      first_label: 0,
      presence_index: 0,
    }
  }

  fn first_arc_state(&self) -> (u8, Option<&O::V>) {
    match self.metadata.empty_output.as_ref() {
      Some(empty_output) => {
        let mut flags = BIT_FINAL_ARC | BIT_LAST_ARC;
        if empty_output.is_some() {
          flags |= BIT_ARC_HAS_FINAL_OUTPUT;
        }
        (flags, empty_output.as_ref())
      },
      None => (BIT_LAST_ARC, None),
    }
  }
  /// Follows the `follow` arc and reads the last arc of its target; this
  /// changes the provided `arc` (2nd arg) in-place and returns it.
  ///
  /// # Returns
  ///
  /// Returns the second argument (`arc`).
  pub(crate) fn read_last_target_arc<'a, T>(
    &self,
    follow: &Arc<O::V>,
    arc: &'a mut Arc<O::V>,
    input: &mut T,
  ) -> Result<&'a mut Arc<O::V>>
  where
    T: BytesReader,
  {
    if !target_has_arcs(follow) {
      debug_assert!(follow.is_final());
      arc.label = END_LABEL;
      arc.target = FINAL_END_NODE;
      arc.output.assign_from(&follow.next_final_output);
      arc.flags = BIT_LAST_ARC;
      arc.node_flags = arc.flags;
      return Ok(arc);
    }

    input.set_position(follow.target());
    let flags = input.read_byte()?;
    arc.node_flags = flags;

    if flags == ARCS_FOR_BINARY_SEARCH
      || flags == ARCS_FOR_DIRECT_ADDRESSING
      || flags == ARCS_FOR_CONTINUOUS
    {
      // Special arc which is actually a node header for fixed length
      // arcs. Jump straight to end to find the last arc.
      arc.num_arcs = input.read_vint()?;
      arc.bytes_per_arc = input.read_vint()?;

      if flags == ARCS_FOR_DIRECT_ADDRESSING {
        read_presence_bytes(arc, input)?;
        arc.first_label = self.read_label(input)?;
        arc.pos_arcs_start = input.get_position();
        self.read_last_arc_by_direct_addressing(arc, input)?;
      } else if flags == ARCS_FOR_BINARY_SEARCH {
        arc.arc_idx = arc.num_arcs - 2;
        arc.pos_arcs_start = input.get_position();
        self.read_next_real_arc(arc, input)?;
      } else {
        arc.first_label = self.read_label(input)?;
        arc.pos_arcs_start = input.get_position();
        self.read_last_arc_by_continuous(arc, input)?;
      }
    } else {
      arc.flags = flags;
      arc.bytes_per_arc = 0;

      // Linear scan through variable-length arcs
      while !arc.is_last() {
        self.read_label(input)?;
        if arc.flag(BIT_ARC_HAS_OUTPUT) {
          self.outputs.skip_output(input)?;
        }
        if arc.flag(BIT_ARC_HAS_FINAL_OUTPUT) {
          self.outputs.skip_final_output(input)?;
        }
        if arc.flag(BIT_STOP_NODE) || arc.flag(BIT_TARGET_NEXT) {
          // no-op
        } else {
          self.read_unpacked_node_target(input)?;
        }
        arc.flags = input.read_byte()?;
      }
      // Undo the byte flags we read:
      input.skip_bytes(-1)?;
      arc.next_arc = input.get_position();
      self.read_next_real_arc(arc, input)?;
    }

    debug_assert!(arc.is_last());
    Ok(arc)
  }
  /// Reads an unpacked node target address (as a `vLong`) from the input.
  fn read_unpacked_node_target<T>(&self, reader: &mut T) -> Result<i64>
  where
    T: BytesReader,
  {
    reader.read_vlong()
  }

  pub(crate) fn find_target_arc_impl<'a, T, AF>(
    &self,
    label_to_match: i32,
    follow: AF,
    arc: &mut Arc<O::V>,
    input: &mut T,
  ) -> Result<Option<()>>
  where
    T: BytesReader,
    O::V: 'a,
    AF: Into<Option<&'a Arc<O::V>>>,
  {
    let follow = follow.into();
    let follow_target = follow.unwrap_or(arc).target();
    if label_to_match == END_LABEL {
      return if follow.unwrap_or(arc).is_final() {
        if follow_target <= 0 {
          arc.flags = BIT_LAST_ARC;
        } else {
          arc.flags = 0;
          arc.next_arc = follow_target;
        }
        arc.output = follow.unwrap_or(arc).next_final_output();
        arc.label = END_LABEL;
        arc.node_flags = arc.flags;
        Ok(Some(()))
      } else {
        Ok(None)
      };
    }

    if follow_target <= 0 {
      return Ok(None);
    }

    input.set_position(follow_target);

    let flags = input.read_byte()?;
    arc.node_flags = flags;

    if flags == ARCS_FOR_DIRECT_ADDRESSING {
      arc.num_arcs = input.read_vint()?;
      arc.bytes_per_arc = input.read_vint()?;
      self.read_presence_bytes(arc, input)?;
      arc.first_label = self.read_label(input)?;
      arc.pos_arcs_start = input.get_position();

      let arc_index = label_to_match - arc.first_label;
      if arc_index < 0 || arc_index >= arc.num_arcs {
        return Ok(None); // Before or after label range.
      } else if !BitTable::is_bit_set(arc_index, arc, input)? {
        return Ok(None); // Arc missing in the range.
      }
      return self
        .read_arc_by_direct_addressing(arc, input, arc_index)
        .map(Some);
    } else if flags == ARCS_FOR_BINARY_SEARCH {
      arc.num_arcs = input.read_vint()?;
      arc.bytes_per_arc = input.read_vint()?;
      arc.pos_arcs_start = input.get_position();
      // Array is sparse; do binary search:
      let mut low = 0;
      let mut high = arc.num_arcs - 1;
      while low <= high {
        let mid = (low + high) >> 1;
        input.set_position(arc.pos_arcs_start - (arc.bytes_per_arc * mid + 1) as i64);
        let mid_label = self.read_label(input)?;
        match mid_label.cmp(&label_to_match) {
          std::cmp::Ordering::Less => low = mid + 1,
          std::cmp::Ordering::Greater => high = mid - 1,
          std::cmp::Ordering::Equal => {
            arc.arc_idx = mid - 1;
            return self.read_next_real_arc(arc, input).map(Some);
          },
        }
      }
      return Ok(None);
    } else if flags == ARCS_FOR_CONTINUOUS {
      arc.num_arcs = input.read_vint()?;
      arc.bytes_per_arc = input.read_vint()?;
      arc.first_label = self.read_label(input)?;
      arc.pos_arcs_start = input.get_position();
      let arc_index = label_to_match - arc.first_label;
      if arc_index < 0 || arc_index >= arc.num_arcs {
        return Ok(None); // Before or after label range.
      }
      arc.arc_idx = arc_index - 1;
      return self.read_next_real_arc(arc, input).map(Some);
    }

    self.read_first_arc_info(follow_target, arc, input)?;
    input.set_position(arc.next_arc);
    loop {
      debug_assert_eq!(arc.bytes_per_arc, 0);
      arc.flags = input.read_byte()?;
      let pos = input.get_position();
      let label = self.read_label(input)?;
      if label == label_to_match {
        input.set_position(pos);
        return self.read_arc(arc, input).map(Some);
      } else if label > label_to_match || arc.is_last() {
        return Ok(None);
      } else {
        let flag = arc.flags;
        if flag_mod(flag, BIT_ARC_HAS_OUTPUT) {
          self.outputs.skip_output(input)?;
        }
        if flag_mod(flag, BIT_ARC_HAS_FINAL_OUTPUT) {
          self.outputs.skip_final_output(input)?;
        }
        if !flag_mod(flag, BIT_STOP_NODE) && !flag_mod(flag, BIT_TARGET_NEXT) {
          self.read_unpacked_node_target(input)?;
        }
      }
    }
  }

  /// Follow the `follow` arc and read the first arc of its target.
  pub fn read_first_target_arc<T>(
    &self,
    follow: &Arc<O::V>,
    arc: &mut Arc<O::V>,
    input: &mut T,
  ) -> Result<()>
  where
    T: BytesReader,
  {
    self.read_first_target_arc_impl(Some(follow), arc, input)
  }

  /// `None` follows the current arc in-place without copying its output owners.
  pub(crate) fn read_first_target_arc_impl<'a, T, AF>(
    &self,
    follow: AF,
    arc: &mut Arc<O::V>,
    input: &mut T,
  ) -> Result<()>
  where
    T: BytesReader,
    O::V: 'a,
    AF: Into<Option<&'a Arc<O::V>>>,
  {
    let follow = follow.into();
    let follow_target = follow.unwrap_or(arc).target;
    if follow.unwrap_or(arc).is_final() {
      // Insert "fake" final arc to END_LABEL
      arc.label = END_LABEL;
      let final_output = match follow {
        Some(follow) => &follow.next_final_output,
        None => &arc.next_final_output,
      };
      arc.output.assign_from(final_output);
      arc.flags = BIT_FINAL_ARC;

      if follow_target <= 0 {
        arc.flags |= BIT_LAST_ARC;
      } else {
        arc.next_arc = follow_target;
      }

      arc.target = FINAL_END_NODE;
      arc.node_flags = arc.flags;
      Ok(())
    } else {
      self.read_first_real_target_arc(follow_target, arc, input)
    }
  }
  fn read_first_arc_info<T>(
    &self,
    node_address: i64,
    arc: &mut Arc<O::V>,
    reader: &mut T,
  ) -> Result<()>
  where
    T: BytesReader,
  {
    reader.set_position(node_address);

    let flags = reader.read_byte()?;
    arc.node_flags = flags;

    if flags == ARCS_FOR_BINARY_SEARCH
      || flags == ARCS_FOR_DIRECT_ADDRESSING
      || flags == ARCS_FOR_CONTINUOUS
    {
      // Special arc which is actually a node header for fixed length
      // arcs.
      arc.num_arcs = reader.read_vint()?;
      arc.bytes_per_arc = reader.read_vint()?;
      arc.arc_idx = -1;

      if flags == ARCS_FOR_DIRECT_ADDRESSING {
        self.read_presence_bytes(arc, reader)?;
        arc.first_label = self.read_label(reader)?;
        arc.presence_index = -1;
      } else if flags == ARCS_FOR_CONTINUOUS {
        arc.first_label = self.read_label(reader)?;
      }

      arc.pos_arcs_start = reader.get_position();
    } else {
      arc.next_arc = node_address;
      arc.bytes_per_arc = 0;
    }

    Ok(())
  }
  pub fn read_first_real_target_arc<T>(
    &self,
    node_address: i64,
    arc: &mut Arc<O::V>,
    reader: &mut T,
  ) -> Result<()>
  where
    T: BytesReader,
  {
    self.read_first_arc_info(node_address, arc, reader)?;
    self.read_next_real_arc(arc, reader)
  }
  /// Returns whether `arc`'s target points to a node in expanded format
  /// (fixed length arcs).
  pub fn is_expanded_target<T>(&self, follow: &Arc<O::V>, reader: &mut T) -> Result<bool>
  where
    T: BytesReader,
  {
    if !target_has_arcs(follow) {
      Ok(false)
    } else {
      reader.set_position(follow.target);
      let flags = reader.read_byte()?;
      Ok(
        flags == ARCS_FOR_BINARY_SEARCH
          || flags == ARCS_FOR_DIRECT_ADDRESSING
          || flags == ARCS_FOR_CONTINUOUS,
      )
    }
  }
  /// In-place read; returns the arc.
  pub fn read_next_arc<T>(&self, arc: &mut Arc<O::V>, input: &mut T) -> Result<()>
  where
    T: BytesReader,
  {
    if arc.label() == END_LABEL {
      // This was a fake inserted "final" arc
      if arc.next_arc() <= 0 {
        return Err(LuceneError::illegal_argument(
          "cannot read_next_arc when arc.is_last()=true",
        ));
      }
      self.read_first_real_target_arc(arc.next_arc(), arc, input)
    } else {
      self.read_next_real_arc(arc, input)
    }
  }
  /// Peeks at next arc's label; does not alter arc.
  /// Do not call this if `arc.is_last()`!
  pub(crate) fn read_next_arc_label<T>(&self, arc: &Arc<O::V>, input: &mut T) -> Result<i32>
  where
    T: BytesReader,
  {
    debug_assert!(!arc.is_last());

    if arc.label() == END_LABEL {
      // Next arc is the first arc of a node.
      // Position to read the first arc label.
      input.set_position(arc.next_arc());
      let flags = input.read_byte()?;

      if flags == ARCS_FOR_BINARY_SEARCH
        || flags == ARCS_FOR_DIRECT_ADDRESSING
        || flags == ARCS_FOR_CONTINUOUS
      {
        // Special arc which is actually a node header for fixed length
        // arcs.
        let num_arcs = input.read_vint()?;
        input.read_vint()?; // Skip bytesPerArc.
        if flags == ARCS_FOR_BINARY_SEARCH {
          input.read_byte()?; // Skip arc flags.
        } else if flags == ARCS_FOR_DIRECT_ADDRESSING {
          input.skip_bytes(get_num_presence_bytes(num_arcs) as i64)?;
        } // Nothing to do for ARCS_FOR_CONTINUOUS
      }
    } else {
      match arc.node_flags() {
        ARCS_FOR_BINARY_SEARCH => {
          // Point to next arc, -1 to skip arc flags.
          let pos =
            arc.pos_arcs_start() - (1 + arc.arc_idx()) as i64 * arc.bytes_per_arc() as i64 - 1;
          input.set_position(pos);
        },
        ARCS_FOR_DIRECT_ADDRESSING => {
          // Direct addressing node. The label is not stored but
          // rather inferred based on first label
          // and arc index in the range.
          debug_assert!(BitTable::assert_is_valid(arc, input)?);
          debug_assert!(BitTable::is_bit_set(arc.arc_idx(), arc, input)?);
          let next_index = BitTable::next_bit_set(arc.arc_idx(), arc, input)?;
          debug_assert!(next_index != -1);
          return Ok(arc.first_label() + next_index);
        },
        ARCS_FOR_CONTINUOUS => {
          return Ok(arc.first_label() + arc.arc_idx() + 1);
        },
        _ => {
          // Variable length arcs - linear search.
          debug_assert_eq!(arc.bytes_per_arc(), 0);
          // Arcs have variable length.
          // Position to next arc, -1 to skip flags.
          input.set_position(arc.next_arc() - 1);
        },
      }
    }

    self.read_label(input)
  }
  /// Reads a binary search node arc by its index.
  ///
  /// # Arguments
  ///
  /// * `arc` - the arc to update
  /// * `in` - the bytes reader
  /// * `idx` - the arc index (must be within range)
  ///
  /// # Returns
  ///
  /// The updated arc
  pub fn read_arc_by_index<T>(&self, arc: &mut Arc<O::V>, input: &mut T, idx: i32) -> Result<()>
  where
    T: BytesReader,
  {
    debug_assert!(arc.bytes_per_arc() > 0);
    debug_assert_eq!(arc.node_flags(), ARCS_FOR_BINARY_SEARCH);
    debug_assert!(idx >= 0 && idx < arc.num_arcs());
    input.set_position(arc.pos_arcs_start() - idx as i64 * arc.bytes_per_arc() as i64);
    arc.arc_idx = idx;
    arc.flags = input.read_byte()?;
    self.read_arc(arc, input)
  }

  /// Reads a continuous node arc, with the provided index in the label range.
  ///
  /// `range_index` must be within the label range.
  pub fn read_arc_by_continuous<T>(
    &self,
    arc: &mut Arc<O::V>,
    reader: &mut T,
    range_index: i32,
  ) -> Result<()>
  where
    T: BytesReader,
  {
    debug_assert!(range_index >= 0 && range_index < arc.num_arcs);
    let pos = arc.pos_arcs_start - (range_index as i64 * arc.bytes_per_arc as i64);
    reader.set_position(pos);
    arc.arc_idx = range_index;
    arc.flags = reader.read_byte()?;
    self.read_arc(arc, reader)
  }
  /// Reads a present direct addressing node arc, with the provided index in
  /// the label range.
  ///
  /// `range_index` must point to a present arc; the actual offset is computed
  /// from presence bits.
  pub fn read_arc_by_direct_addressing<T>(
    &self,
    arc: &mut Arc<O::V>,
    reader: &mut T,
    range_index: i32,
  ) -> Result<()>
  where
    T: BytesReader,
  {
    debug_assert!(BitTable::assert_is_valid(arc, reader)?);
    debug_assert!(
      range_index >= 0 && range_index < arc.num_arcs,
      "range_index {} out of bounds (0..{})",
      range_index,
      arc.num_arcs
    );
    debug_assert!(
      BitTable::is_bit_set(range_index, arc, reader)?,
      "bit not set at index {range_index}"
    );

    let presence_index = BitTable::count_bits_upto(range_index, arc, reader)?;
    self.read_arc_by_direct_addressing_with_presence_index(arc, reader, range_index, presence_index)
  }
  /// Reads a present direct addressing node arc, with the provided index in
  /// the label range and its corresponding presence index (which is the
  /// count of presence bits before it).
  pub fn read_arc_by_direct_addressing_with_presence_index<T>(
    &self,
    arc: &mut Arc<O::V>,
    reader: &mut T,
    range_index: i32,
    presence_index: i32,
  ) -> Result<()>
  where
    T: BytesReader,
  {
    let pos = arc.pos_arcs_start - (presence_index as i64 * arc.bytes_per_arc as i64);
    reader.set_position(pos);
    arc.arc_idx = range_index;
    arc.presence_index = presence_index;
    arc.flags = reader.read_byte()?;
    self.read_arc(arc, reader)
  }

  /// Reads the last arc of a direct addressing node.
  ///
  /// This method is equivalent to calling
  /// [`read_arc_by_direct_addressing`](Self::read_arc_by_direct_addressing)
  /// with `range_index` equal to `arc.num_arcs() - 1`, but it is faster.
  pub fn read_last_arc_by_direct_addressing<T>(
    &self,
    arc: &mut Arc<O::V>,
    reader: &mut T,
  ) -> Result<()>
  where
    T: BytesReader,
  {
    debug_assert!(BitTable::assert_is_valid(arc, reader)?);

    let presence_index = BitTable::count_bits(arc, reader)? - 1;

    self.read_arc_by_direct_addressing_with_presence_index(
      arc,
      reader,
      arc.num_arcs - 1,
      presence_index,
    )
  }

  /// Reads the last arc of a continuous node.
  pub fn read_last_arc_by_continuous<T>(&self, arc: &mut Arc<O::V>, reader: &mut T) -> Result<()>
  where
    T: BytesReader,
  {
    self.read_arc_by_continuous(arc, reader, arc.num_arcs - 1)
  }
  /// Never returns `None`, but must not be called if `arc.is_last()` is true.
  pub fn read_next_real_arc<T>(&self, arc: &mut Arc<O::V>, reader: &mut T) -> Result<()>
  where
    T: BytesReader,
  {
    match arc.node_flags {
      ARCS_FOR_BINARY_SEARCH | ARCS_FOR_CONTINUOUS => {
        debug_assert!(arc.bytes_per_arc > 0);
        arc.arc_idx += 1;
        debug_assert!(arc.arc_idx >= 0 && arc.arc_idx < arc.num_arcs);
        let pos = arc.pos_arcs_start - (arc.arc_idx as i64 * arc.bytes_per_arc as i64);
        reader.set_position(pos);
        arc.flags = reader.read_byte()?;
      },

      ARCS_FOR_DIRECT_ADDRESSING => {
        debug_assert!(BitTable::assert_is_valid(arc, reader)?);
        debug_assert!(
          arc.arc_idx == -1 || BitTable::is_bit_set(arc.arc_idx, arc, reader)?,
          "arcIdx {} must be valid or unset",
          arc.arc_idx
        );
        let next_index = BitTable::next_bit_set(arc.arc_idx, arc, reader)?;
        return self.read_arc_by_direct_addressing_with_presence_index(
          arc,
          reader,
          next_index,
          arc.presence_index + 1,
        );
      },

      _ => {
        // Variable-length arcs (linear scan)
        debug_assert_eq!(arc.bytes_per_arc, 0);
        reader.set_position(arc.next_arc);
        arc.flags = reader.read_byte()?;
      },
    }

    self.read_arc(arc, reader)
  }

  // Reads an arc.
  ///
  /// Precondition: The arc flags byte has already been read and set;
  /// the given [`BytesReader`] is positioned just after the arc flags byte.
  pub fn read_arc<T>(&self, arc: &mut Arc<O::V>, reader: &mut T) -> Result<()>
  where
    T: BytesReader,
  {
    if arc.node_flags == ARCS_FOR_DIRECT_ADDRESSING || arc.node_flags == ARCS_FOR_CONTINUOUS {
      arc.label = arc.first_label() + arc.arc_idx();
    } else {
      arc.label = self.read_label(reader)?;
    }

    if arc.flag(BIT_ARC_HAS_OUTPUT) {
      arc.output = self.outputs.read(reader)?;
    } else {
      arc.output = None;
    }

    if arc.flag(BIT_ARC_HAS_FINAL_OUTPUT) {
      arc.next_final_output = self.outputs.read_final_output(reader)?;
    } else {
      arc.next_final_output = None;
    }

    if arc.flag(BIT_STOP_NODE) {
      arc.target = if arc.flag(BIT_FINAL_ARC) {
        FINAL_END_NODE
      } else {
        NON_FINAL_END_NODE
      };
      arc.next_arc = reader.get_position();
    } else if arc.flag(BIT_TARGET_NEXT) {
      arc.next_arc = reader.get_position();

      if !arc.flag(BIT_LAST_ARC) {
        if arc.bytes_per_arc() == 0 {
          self.seek_to_next_node(reader)?;
        } else {
          let num_arcs = if arc.node_flags == ARCS_FOR_DIRECT_ADDRESSING {
            BitTable::count_bits(arc, reader)?
          } else {
            arc.num_arcs()
          };
          let pos = arc.pos_arcs_start - (arc.bytes_per_arc as i64 * num_arcs as i64);
          reader.set_position(pos);
        }
      }

      arc.target = reader.get_position();
    } else {
      arc.target = self.read_unpacked_node_target(reader)?;
      arc.next_arc = reader.get_position();
    }
    Ok(())
  }
  /// Finds an arc leaving the `follow` arc with the specified label, updating
  /// `arc` in-place. This returns `None` if the arc was not found,
  /// otherwise returns the updated `arc`.
  ///
  /// # Arguments
  ///
  /// * `label_to_match` - The label to search for
  /// * `follow` - The arc from which to search
  /// * `arc` - The arc to update
  /// * `input` - The input stream to read from
  ///
  /// # Returns
  ///
  /// `Some(arc)` if the target arc is found, `None` otherwise
  ///
  /// # Errors
  ///
  /// Returns an error if reading from the input fails
  pub fn find_target_arc<T>(
    &self,
    label_to_match: i32,
    follow: &Arc<O::V>,
    arc: &mut Arc<O::V>,
    input: &mut T,
  ) -> Result<Option<()>>
  where
    T: BytesReader,
  {
    self.find_target_arc_impl(label_to_match, follow, arc, input)
  }

  /// Skips over a variable-length arc node until it reaches the last arc.
  pub fn seek_to_next_node<T>(&self, reader: &mut T) -> Result<()>
  where
    T: BytesReader,
  {
    loop {
      let flags = reader.read_byte()?;
      self.read_label(reader)?;

      if flags & BIT_ARC_HAS_OUTPUT != 0 {
        self.outputs.skip_output(reader)?;
      }

      if flags & BIT_ARC_HAS_FINAL_OUTPUT != 0 {
        self.outputs.skip_final_output(reader)?;
      }

      if !flag_mod(flags, BIT_STOP_NODE) && !flag_mod(flags, BIT_TARGET_NEXT) {
        self.read_unpacked_node_target(reader)?;
      }

      if flags & BIT_LAST_ARC != 0 {
        return Ok(());
      }
    }
  }
  /// Returns a [`BytesReader`] for this FST, positioned at position 0.
  pub fn get_bytes_reader(&self) -> Result<F::FstBytesReader> {
    self.fst_reader.get_reverse_bytes_reader()
  }
}

impl<O, F> Display for FST<O, F>
where
  O: Outputs,
{
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    write!(
      f,
      "{}(input={:?}, output={})",
      std::any::type_name::<Self>(),
      self.metadata.input_type,
      self.outputs
    )
  }
}

/// An FST arc whose output payload type is `T`.
/// The output fields use `None` for an empty output.
#[derive(Default, Clone, Debug)]
pub struct Arc<T> {
  // *** Arc fields.
  pub(crate) label: i32,
  pub(crate) output: Option<T>,
  target: i64,
  flags: u8,
  pub(crate) next_final_output: Option<T>,
  next_arc: i64,
  node_flags: u8,

  // *** Fields for arcs belonging to a node with fixed length arcs.
  // So only valid when bytes_per_arc != 0.
  // node_flags == ARCS_FOR_BINARY_SEARCH || node_flags ==
  // ARCS_FOR_DIRECT_ADDRESSING.
  bytes_per_arc: i32,
  pos_arcs_start: i64,
  arc_idx: i32,
  num_arcs: i32,

  // *** Fields for a direct addressing node. node_flags ==
  // ARCS_FOR_DIRECT_ADDRESSING.
  /// Start position in the [`BytesReader`] of the presence bits for a direct
  /// addressing node, aka the bit-table
  bit_table_start: i64,

  /// First label of a direct addressing node.
  first_label: i32,

  /// Index of the current label of a direct addressing node. While `arc_idx`
  /// is the current index in the label range, `presence_index` is its
  /// corresponding index in the list of actually present labels. It is
  /// equal to the number of bits set before the bit at `arc_idx`
  /// in the bit-table. This field is a cache to avoid counting bits
  /// repeatedly when iterating arcs.
  presence_index: i32,
}
impl<T> Arc<T> {
  // A private traversal slot starts without an encoded output. Supply its
  // empty values directly instead of allocating temporary default owners.
  pub(crate) fn with_outputs(output: Option<T>, next_final_output: Option<T>) -> Self {
    Self {
      label: 0,
      output,
      target: 0,
      flags: 0,
      next_final_output,
      next_arc: 0,
      node_flags: 0,
      bytes_per_arc: 0,
      pos_arcs_start: 0,
      arc_idx: 0,
      num_arcs: 0,
      bit_table_start: 0,
      first_label: 0,
      presence_index: 0,
    }
  }
  pub(crate) fn flag(&self, flag: u8) -> bool {
    flag_mod(self.flags, flag)
  }
  pub fn is_last(&self) -> bool {
    self.flag(BIT_LAST_ARC)
  }
  pub fn is_final(&self) -> bool {
    self.flag(BIT_FINAL_ARC)
  }

  pub fn label(&self) -> i32 {
    self.label
  }
  /// Ord/address to target node.
  pub fn target(&self) -> i64 {
    self.target
  }

  pub fn flags(&self) -> u8 {
    self.flags
  }

  /// Address in the byte buffer of the next arc; only used for lists of variable
  /// length arc. Or ord/address to the next node if label ==
  /// [`END_LABEL`].
  pub fn next_arc(&self) -> i64 {
    self.next_arc
  }

  /// Only valid if bytes_per_arc != 0.
  pub fn arc_idx(&self) -> i32 {
    self.arc_idx
  }

  /// Node header flags. Only meaningful to check if the value is either
  /// [`ARCS_FOR_BINARY_SEARCH`] or
  /// [`ARCS_FOR_DIRECT_ADDRESSING`]
  /// or [`ARCS_FOR_CONTINUOUS`] (other value
  /// when bytesPerArc == 0).
  pub fn node_flags(&self) -> u8 {
    self.node_flags
  }

  /// Start position of the arc array (only valid if bytes_per_arc != 0).
  pub fn pos_arcs_start(&self) -> i64 {
    self.pos_arcs_start
  }

  ///  Non-zero if this arc is part of a node with fixed length arcs, which
  /// means all arcs for the  node are encoded with a fixed number of
  /// bytes so that we binary search or direct address. We  do when there
  /// are enough arcs leaving one node. It wastes some bytes but gives faster
  ///  lookups.
  pub fn bytes_per_arc(&self) -> i32 {
    self.bytes_per_arc
  }

  /// How many arcs; only valid if bytesPerArc != 0 (fixed length arcs). For a
  /// node designed for binary search this is the array size. For a node
  /// designed for direct addressing, this is the label range.
  pub fn num_arcs(&self) -> i32 {
    self.num_arcs
  }

  /// First label of a direct addressing node. Only valid if nodeFlags ==
  /// [`ARCS_FOR_DIRECT_ADDRESSING`] or
  /// [`ARCS_FOR_CONTINUOUS`].
  pub fn first_label(&self) -> i32 {
    self.first_label
  }
}
impl<T: Clone> Arc<T> {
  /// Returns `self` after copying all fields from `other`.
  pub fn copy_from(&mut self, other: &Arc<T>) {
    self.label = other.label();
    self.target = other.target();
    self.flags = other.flags();
    self.output = other.output();
    self.next_final_output = other.next_final_output();
    self.next_arc = other.next_arc();
    self.node_flags = other.node_flags();
    self.bytes_per_arc = other.bytes_per_arc();
    // Fields for arcs belonging to a node with fixed length arcs.
    // We could avoid copying them if bytesPerArc() == 0 (this was the case
    // with previous code, and the current code
    // still supports that), but it may actually help external uses of FST
    // to have consistent arc state, and debugging
    // is easier.
    self.pos_arcs_start = other.pos_arcs_start();
    self.arc_idx = other.arc_idx();
    self.num_arcs = other.num_arcs();
    self.bit_table_start = other.bit_table_start;
    self.first_label = other.first_label();
    self.presence_index = other.presence_index;
  }
  pub fn output(&self) -> Option<T> {
    self.output.clone()
  }
  pub fn next_final_output(&self) -> Option<T> {
    self.next_final_output.clone()
  }
}
impl<T: Display> Display for Arc<T> {
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    write!(f, " target={}", self.target)?;
    write!(f, " label=0x{:x}", self.label)?;

    if self.flag(BIT_FINAL_ARC) {
      write!(f, " final")?;
    }
    if self.flag(BIT_LAST_ARC) {
      write!(f, " last")?;
    }
    if self.flag(BIT_TARGET_NEXT) {
      write!(f, " targetNext")?;
    }
    if self.flag(BIT_STOP_NODE) {
      write!(f, " stop")?;
    }
    if self.flag(BIT_ARC_HAS_OUTPUT)
      && let Some(output) = &self.output
    {
      write!(f, " output={output}")?;
    }
    if self.flag(BIT_ARC_HAS_FINAL_OUTPUT)
      && let Some(output) = &self.next_final_output
    {
      write!(f, " nextFinalOutput={output}")?;
    }
    if self.bytes_per_arc() != 0 {
      let node_flag_str = match self.node_flags {
        ARCS_FOR_DIRECT_ADDRESSING => "da",
        ARCS_FOR_CONTINUOUS => "cs",
        _ => "bs",
      };
      write!(
        f,
        " arcArray(idx={} of {})({})",
        self.arc_idx, self.num_arcs, node_flag_str
      )?;
    }

    Ok(())
  }
}
pub(crate) struct BitTable;
impl BitTable {
  /// See [`BitTableUtil::is_bit_set`].
  pub(crate) fn is_bit_set<T, T2>(bit_index: i32, arc: &Arc<T>, reader: &mut T2) -> Result<bool>
  where
    T2: BytesReader,
  {
    debug_assert_eq!(arc.node_flags(), ARCS_FOR_DIRECT_ADDRESSING);
    reader.set_position(arc.bit_table_start);
    BitTableUtil::is_bit_set(bit_index, reader)
  }

  /// See [`BitTableUtil::count_bits`]. The count of bit set is the number of
  /// arcs of a direct addressing node.
  pub(crate) fn count_bits<R, T>(arc: &Arc<T>, reader: &mut R) -> Result<i32>
  where
    R: BytesReader,
  {
    debug_assert_eq!(arc.node_flags(), ARCS_FOR_DIRECT_ADDRESSING);
    reader.set_position(arc.bit_table_start);
    let num_presence_bytes = get_num_presence_bytes(arc.num_arcs());
    BitTableUtil::count_bits(num_presence_bytes, reader)
  }
  /// See [`BitTableUtil::count_bits_upto`].
  pub(crate) fn count_bits_upto<T, T2>(bit_index: i32, arc: &Arc<T>, reader: &mut T2) -> Result<i32>
  where
    T2: BytesReader,
  {
    debug_assert_eq!(arc.node_flags(), ARCS_FOR_DIRECT_ADDRESSING);
    reader.set_position(arc.bit_table_start);
    BitTableUtil::count_bits_upto(bit_index, reader)
  }

  /// See [`BitTableUtil::next_bit_set`].
  pub(crate) fn next_bit_set<T, T2>(bit_index: i32, arc: &Arc<T>, reader: &mut T2) -> Result<i32>
  where
    T2: BytesReader,
  {
    debug_assert_eq!(arc.node_flags(), ARCS_FOR_DIRECT_ADDRESSING);
    reader.set_position(arc.bit_table_start);
    let num_bytes = get_num_presence_bytes(arc.num_arcs());
    BitTableUtil::next_bit_set(bit_index, num_bytes, reader)
  }

  /// See [`BitTableUtil::previous_bit_set`].
  pub(crate) fn previous_bit_set<T, T2>(
    bit_index: i32,
    arc: &Arc<T>,
    reader: &mut T2,
  ) -> Result<i32>
  where
    T2: BytesReader,
  {
    debug_assert_eq!(arc.node_flags(), ARCS_FOR_DIRECT_ADDRESSING);
    reader.set_position(arc.bit_table_start);
    BitTableUtil::previous_bit_set(bit_index, reader)
  }

  /// Asserts the bit-table of the provided [`Arc`] is valid.
  pub(crate) fn assert_is_valid<T, T2>(arc: &Arc<T>, reader: &mut T2) -> Result<bool>
  where
    T2: BytesReader,
  {
    debug_assert!(arc.bytes_per_arc() > 0);
    debug_assert_eq!(arc.node_flags(), ARCS_FOR_DIRECT_ADDRESSING);

    // First bit must be set
    debug_assert!(Self::is_bit_set(0, arc, reader)?);

    // Last bit must be set
    debug_assert!(Self::is_bit_set(arc.num_arcs() - 1, arc, reader)?);

    // No bit set after the last arc
    debug_assert_eq!(Self::next_bit_set(arc.num_arcs() - 1, arc, reader)?, -1);

    Ok(true)
  }
}

/// Represents the FST metadata.
///
/// `T` is the FST output type.
#[derive(Default)]
pub struct FSTMetadata<O>
where
  O: Outputs,
{
  pub input_type: InputType,
  pub outputs: O,
  pub version: i32,
  /// If `Some`, this FST accepts the empty string and produces this
  /// output.
  pub empty_output: Option<Option<O::V>>,
  pub start_node: i64,
  pub num_bytes: i64,
}
impl<O: Outputs> FSTMetadata<O> {
  pub fn new(
    input_type: InputType,
    outputs: O,
    empty_output: Option<Option<O::V>>,
    start_node: i64,
    version: i32,
    num_bytes: i64,
  ) -> Self {
    Self {
      input_type,
      outputs,
      version,
      empty_output,
      start_node,
      num_bytes,
    }
  }

  /// Returns the version constant of the binary format this FST was written
  /// in. See the static version constants in [`FST`] such as
  /// [`VERSION_CONTINUOUS_ARCS`].
  pub fn version(&self) -> i32 {
    self.version
  }

  pub fn empty_output(&self) -> Option<&Option<O::V>> {
    self.empty_output.as_ref()
  }

  pub fn num_bytes(&self) -> i64 {
    self.num_bytes
  }
  /// Save the metadata to a [`DataOutput`].
  ///
  /// # Arguments
  ///
  /// * `meta_out` - The [`DataOutput`] to write the metadata to.
  pub fn save<DO>(&self, meta_out: &mut DO) -> Result<()>
  where
    DO: DataOutput,
  {
    CodecUtil::write_header(meta_out, FILE_FORMAT_NAME, VERSION_CURRENT)?;

    if let Some(ref empty_output) = self.empty_output {
      // Accepts empty string
      meta_out.write_byte(1)?;

      // Serialize empty-string output
      let mut ros = ByteBuffersDataOutput::new();
      self.outputs.write_final_output(empty_output, &mut ros)?;
      let mut empty_output_bytes = ros.into_array();
      let empty_len = empty_output_bytes.len();
      // reverse
      let stop_at = empty_len / 2;
      for i in 0..stop_at {
        empty_output_bytes.swap(i, empty_len - i - 1);
      }

      meta_out.write_vint(empty_len as i32)?;
      debug_assert!(empty_output_bytes.len() <= i32::MAX as usize);
      meta_out.write_bytes_range(&empty_output_bytes, 0, empty_len)?;
    } else {
      meta_out.write_byte(0)?;
    }

    let t = match self.input_type {
      InputType::Byte1 => 0u8,
      InputType::Byte2 => 1u8,
      InputType::Byte4 => 2u8,
    };
    meta_out.write_byte(t)?;
    meta_out.write_vlong(self.start_node)?;
    meta_out.write_vlong(self.num_bytes)?;

    Ok(())
  }
}

/// Specifies allowed range of each int input label for this FST.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InputType {
  #[default]
  Byte1,
  Byte2,
  Byte4,
}

/// Reads bytes stored in an FST.
pub trait BytesReader: DataInput {
  /// Get current read position.
  fn get_position(&self) -> i64;

  /// Set current read position.
  fn set_position(&mut self, pos: i64);
}

pub enum BytesReaderEnum2<A, B> {
  A(A),
  B(B),
}

impl<A, B> crate::core::util::close::Closeable for BytesReaderEnum2<A, B> {}

impl<A, B> DataInput for BytesReaderEnum2<A, B>
where
  A: BytesReader,
  B: BytesReader,
{
  fn read_byte(&mut self) -> Result<u8> {
    match self {
      BytesReaderEnum2::A(reader) => reader.read_byte(),
      BytesReaderEnum2::B(reader) => reader.read_byte(),
    }
  }

  fn get_bytes<'a>(&'a mut self, len: usize) -> Result<std::borrow::Cow<'a, [u8]>> {
    match self {
      BytesReaderEnum2::A(reader) => DataInput::get_bytes(reader, len),
      BytesReaderEnum2::B(reader) => DataInput::get_bytes(reader, len),
    }
  }

  fn read_bytes(&mut self, b: &mut [u8], offset: usize, len: usize) -> Result<()> {
    match self {
      BytesReaderEnum2::A(reader) => reader.read_bytes(b, offset, len),
      BytesReaderEnum2::B(reader) => reader.read_bytes(b, offset, len),
    }
  }

  fn read_group_vint(&mut self, dst: &mut [i32], offset: usize) -> Result<()> {
    match self {
      BytesReaderEnum2::A(reader) => reader.read_group_vint(dst, offset),
      BytesReaderEnum2::B(reader) => reader.read_group_vint(dst, offset),
    }
  }

  fn skip_bytes(&mut self, num_bytes: i64) -> Result<()> {
    match self {
      BytesReaderEnum2::A(reader) => reader.skip_bytes(num_bytes),
      BytesReaderEnum2::B(reader) => reader.skip_bytes(num_bytes),
    }
  }
}

impl<A, B> DataInputExt for BytesReaderEnum2<A, B>
where
  A: BytesReader,
  B: BytesReader,
{
}

impl<A, B> Display for BytesReaderEnum2<A, B>
where
  A: BytesReader,
  B: BytesReader,
{
  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
    match self {
      BytesReaderEnum2::A(reader) => {
        write!(f, "BytesReaderEnum(F: {})", reader.get_position())
      },
      BytesReaderEnum2::B(reader) => {
        write!(f, "BytesReaderEnum(S: {})", reader.get_position())
      },
    }
  }
}

impl<A, B> BytesReader for BytesReaderEnum2<A, B>
where
  A: BytesReader,
  B: BytesReader,
{
  fn get_position(&self) -> i64 {
    match self {
      BytesReaderEnum2::A(reader) => reader.get_position(),
      BytesReaderEnum2::B(reader) => reader.get_position(),
    }
  }

  fn set_position(&mut self, pos: i64) {
    match self {
      BytesReaderEnum2::A(reader) => reader.set_position(pos),
      BytesReaderEnum2::B(reader) => reader.set_position(pos),
    }
  }
}

use crate::core::util::fst_impl::fst_compiler::get_on_heap_reader_writer;

pub(crate) const BIT_FINAL_ARC: u8 = 1 << 0;
pub(crate) const BIT_LAST_ARC: u8 = 1 << 1;
pub(crate) const BIT_TARGET_NEXT: u8 = 1 << 2;

pub(crate) const BIT_STOP_NODE: u8 = 1 << 3;

/// This flag is set if the arc has an output.
pub const BIT_ARC_HAS_OUTPUT: u8 = 1 << 4;
pub(crate) const BIT_ARC_HAS_FINAL_OUTPUT: u8 = 1 << 5;

/// Value of the arc flags to declare a node with fixed length (sparse) arcs
/// designed for binary search.
pub const ARCS_FOR_BINARY_SEARCH: u8 = BIT_ARC_HAS_FINAL_OUTPUT;

/// Value of the arc flags to declare a node with fixed length dense arcs
/// and bit table designed for direct addressing.
pub const ARCS_FOR_DIRECT_ADDRESSING: u8 = 1 << 6;

///  Value of the arc flags to declare a node with continuous arcs designed
/// for pos the arc directly  with labelToPos - firstLabel. like
/// [`ARCS_FOR_BINARY_SEARCH`] we use flag
/// combinations  that will not occur at the same time.
pub const ARCS_FOR_CONTINUOUS: u8 = ARCS_FOR_DIRECT_ADDRESSING + ARCS_FOR_BINARY_SEARCH;

/// Format name for the FST file.
const FILE_FORMAT_NAME: &str = "FST";

/// First supported version (Lucene 7.0).
pub const VERSION_START: i32 = 6;
// Version 7 introduced direct addressing for arcs, but it's not recorded
// here because it doesn't need version checks on the read side, it uses
// new flag values on arcs instead.
const VERSION_LITTLE_ENDIAN: i32 = 8;

/// Version that started storing continuous arcs.
pub const VERSION_CONTINUOUS_ARCS: i32 = 9;

/// Current format version.
pub const VERSION_CURRENT: i32 = VERSION_CONTINUOUS_ARCS;

/// Version that was used for Lucene 9.0.
pub const VERSION_90: i32 = VERSION_LITTLE_ENDIAN;

/// Represents a final virtual node with no arcs (never serialized).
pub(crate) const FINAL_END_NODE: i64 = -1;

/// Represents a non-final virtual node with no arcs (never serialized).
pub(crate) const NON_FINAL_END_NODE: i64 = 0;

/// If arc has this label then that arc is final/accepted.
pub const END_LABEL: i32 = -1;
#[cfg(target_pointer_width = "64")]
pub const DEFAULT_MAX_BLOCK_BITS: i32 = 30;

#[cfg(not(target_pointer_width = "64"))]
pub const DEFAULT_MAX_BLOCK_BITS: i32 = 28;
#[inline]
pub(crate) fn flag_mod(flags: u8, bit: u8) -> bool {
  (flags & bit) != 0
}

/// Read the FST metadata from DataInput
///
/// # Type Parameters
///
/// * `T` - the output type
///
/// # Arguments
///
/// * `metaIn` - the DataInput of the metadata
/// * `outputs` - the FST outputs
///
/// # Returns
///
/// the FST metadata
///
/// # Errors
///
/// Returns an error if parsing fails.
pub fn read_metadata<O, DI>(meta_in: &mut DI, outputs: O) -> Result<FSTMetadata<O>>
where
  O: Outputs,
  DI: DataInput,
{
  // NOTE: only reads formats VERSION_START up to VERSION_CURRENT; we
  // don't have back-compat promise for FSTs (they are
  // experimental), but we are sometimes able to offer it
  let version = CodecUtil::check_header(meta_in, FILE_FORMAT_NAME, VERSION_START, VERSION_CURRENT)?;

  let mut empty_output: Option<Option<O::V>> = None;

  if meta_in.read_byte()? == 1 {
    // Accepts empty string
    // 1 KB blocks:
    let mut empty_bytes = get_on_heap_reader_writer(10)?;
    let num_bytes = meta_in.read_vint()?;
    if num_bytes <= 0 || num_bytes > crate::core::store::data_output::COPY_BUFFER_SIZE as i32 {
      empty_bytes.copy_bytes(meta_in, num_bytes as usize)?;
    } else {
      // This temporary store uses a contiguous reader with the encoded length.
      // Build its final owner directly, preserving the same get_bytes request.
      let bytes = match meta_in.get_bytes(num_bytes as usize)? {
        std::borrow::Cow::Owned(mut bytes) if bytes.len() >= num_bytes as usize => {
          bytes.truncate(num_bytes as usize);
          bytes
        },
        bytes => bytes[..num_bytes as usize].to_vec(),
      };
      empty_bytes.byte_buffer = Some(Rc::new(bytes));
    }
    empty_bytes.freeze()?;
    // De-serialize empty-string output:
    let mut reader = empty_bytes.get_reverse_bytes_reader()?;
    // NoOutputs uses 0 bytes when writing its output,
    // so we have to check here else BytesStore gets angry:
    if num_bytes > 0 {
      reader.set_position((num_bytes - 1) as i64);
    }
    empty_output = Some(outputs.read_final_output(&mut reader)?);
  }
  let input_type = match meta_in.read_byte()? {
    0 => InputType::Byte1,
    1 => InputType::Byte2,
    2 => InputType::Byte4,
    invalid => {
      return Err(LuceneError::corrupt_index(format!(
        "invalid input type {invalid} (resource={meta_in})"
      )));
    },
  };

  let start_node = meta_in.read_vlong()?;
  let num_bytes = meta_in.read_vlong()?;

  Ok(FSTMetadata::new(
    input_type,
    outputs,
    empty_output,
    start_node,
    version,
    num_bytes,
  ))
}

/// Returns `true` if the node at this address has any outgoing arcs.
pub fn target_has_arcs<T>(arc: &Arc<T>) -> bool {
  arc.target() > 0
}
/// Gets the number of bytes required to flag the presence of each arc in
/// the given label range, one bit per arc.
pub(crate) fn get_num_presence_bytes(label_range: i32) -> i32 {
  debug_assert!(label_range >= 0);
  (label_range + 7) >> 3
}
/// Reads the presence bits of a direct-addressing node. Actually we don't
/// read them here, we just keep the pointer to the bit-table start and
/// we skip them.
pub(crate) fn read_presence_bytes<T, T2>(arc: &mut Arc<T>, reader: &mut T2) -> Result<()>
where
  T2: BytesReader,
{
  debug_assert!(arc.bytes_per_arc() > 0);
  debug_assert_eq!(arc.node_flags(), ARCS_FOR_DIRECT_ADDRESSING);
  arc.bit_table_start = reader.get_position();
  let skip = get_num_presence_bytes(arc.num_arcs());
  reader.skip_bytes(skip as i64)
}
/// Reads the end arc based on the `follow` arc.
/// If `follow` is final, this sets up an artificial END_LABEL arc in-place
/// and returns it. Otherwise, returns `None`.
///
/// # Arguments
///
/// * `follow` - The arc to follow
/// * `arc` - The arc to fill and return
///
/// # Returns
///
/// The updated `arc` if `follow` is final, otherwise `None`
pub(crate) fn read_end_arc<T>(follow: &Arc<T>, arc: &mut Arc<T>) -> Option<()>
where
  T: Clone,
{
  if follow.is_final() {
    if follow.target() <= 0 {
      arc.flags = BIT_LAST_ARC;
    } else {
      arc.flags = 0;
      // NOTE: nextArc is a node (not an address!) in this case:
      arc.next_arc = follow.target();
    }
    arc.output = follow.next_final_output();
    arc.label = END_LABEL;
    Some(())
  } else {
    None
  }
}