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
/*
 * 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 std::fmt::{Display, Formatter};

use smallvec::SmallVec;

use crate::core::store::{ByteArrayDataOutput, DataOutput, IndexOutput};
use crate::core::util::accountable::Accountable;
use crate::core::util::array_util::ArrayUtil;
use crate::core::util::close::Closeable;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::fst_impl::dummy::dummy_bytes_reader::DummyBytesReader;
use crate::core::util::fst_impl::fst::{
  ARCS_FOR_BINARY_SEARCH, ARCS_FOR_CONTINUOUS, ARCS_FOR_DIRECT_ADDRESSING,
  BIT_ARC_HAS_FINAL_OUTPUT, BIT_ARC_HAS_OUTPUT, BIT_FINAL_ARC, BIT_LAST_ARC, BIT_STOP_NODE,
  BIT_TARGET_NEXT, BytesReaderEnum2, FINAL_END_NODE, FST, FSTMetadata, InputType,
  NON_FINAL_END_NODE, VERSION_90, VERSION_CONTINUOUS_ARCS, VERSION_CURRENT, get_num_presence_bytes,
};
use crate::core::util::fst_impl::fst_reader::FstReader;
use crate::core::util::fst_impl::growable_byte_array_data_output::GrowableByteArrayDataOutput;
use crate::core::util::fst_impl::node_hash::NodeHash;
use crate::core::util::fst_impl::outputs::{Outputs, OutputsBound};
use crate::core::util::fst_impl::read_write_data_output::ReadWriteDataOutput;
use crate::core::util::fst_impl::reverse_bytes_reader::ReverseBytesReader;
use crate::core::util::ints_ref::IntsRef;
use crate::core::util::ints_ref_builder::IntsRefBuilder;
use crate::core::util::{SliceCopyOps, TryIntoInt};

/// Builds a minimal FST (maps an [`IntsRef`] term to an arbitrary output) from
/// pre-sorted terms with outputs. The FST becomes an FSA if you use
/// [`NoOutputs`](crate::core::util::fst_impl::no_outputs::NoOutputs). The FST is written on-the-fly into a compact serialized format
/// byte array, which can be saved to / loaded from a [`Directory`](crate::core::store::directory::Directory) or used
/// directly for traversal. The FST is always finite (no cycles).
///
///
/// **NOTE**: The algorithm is described at:
/// <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.24.3698>
///
///
/// The parameterized type `T` is the output type. See the implementations of
/// [`Outputs`].
///
///
/// FSTs larger than 2.1GB are now possible (as of Lucene 4.2). FSTs containing
/// more than 2.1B nodes are also now possible, however they cannot be packed.
///
///
/// It now supports 3 different workflows:
///
/// - Build FST and use it immediately entirely in RAM and then discard it
/// - Build FST and use it immediately entirely in RAM and also save it to other
///   [`DataOutput`], and load it later and use it
/// - Build FST but stream it immediately to disk (except the `FSTMetaData`, to
///   be saved at the end). In order to use it, you need to construct the
///   corresponding [`DataInput`](crate::core::store::data_input::DataInput) and use the FST loading method to read it.
pub struct FSTCompiler<O, DO>
where
  O: Outputs,
  DO: IndexOutput,
{
  pub(crate) dedup_hash: Option<NodeHash<O::V>>,
  /// A temporary FST used during building for NodeHash cache.
  pub(crate) fst: FST<O, NullFSTReader>,
  /// Node deduplication hash table.
  /// Last input added.
  pub(crate) last_input: IntsRefBuilder<Vec<i32>>,
  /// Whether the initial padding byte needs to be written.
  pub(crate) padding_byte_pending: bool,

  /// Used for the BIT_TARGET_NEXT optimization (whereby
  /// instead of storing the address of the target node for
  /// a given arc, we mark a single bit noting that the next
  /// node in the byte buffer is the target node):
  pub(crate) last_frozen_node: i64,
  /// Reused temporarily while building the FST:
  // Arc lengths have already passed the existing i32 conversion check.
  pub(crate) arc_sizes: Vec<[i32; 2]>,
  pub(crate) fixed_length_arcs_buffer: FixedLengthArcsBuffer,
  pub(crate) arc_count: i64,
  pub(crate) node_count: i64,
  pub(crate) binary_search_node_count: i64,
  pub(crate) direct_addressing_node_count: i64,
  pub(crate) continuous_node_count: i64,
  pub(crate) allow_fixed_length_arcs: bool,
  pub(crate) direct_addressing_max_oversizing_factor: f32,
  pub(crate) version: i32,
  pub(crate) direct_addressing_expansion_credit: i64,
  pub(crate) data_output: DataOutputEnum<DO>,
  pub(crate) scratch_bytes: GrowableByteArrayDataOutput,
  pub(crate) num_bytes_written: i64,
  /// Current frontier. Every allocated slot contains a reusable node.
  pub(crate) frontier: Vec<UnCompiledNode<O::V>>,
}
impl<O, DO> FSTCompiler<O, DO>
where
  O: Outputs,
  DO: IndexOutput,
{
  fn new(
    input_type: InputType,
    suffix_ram_limit_mb: f64,
    outputs: O,
    allow_fixed_length_arcs: bool,
    data_output: DataOutputEnum<DO>,
    direct_addressing_max_oversizing_factor: f32,
    version: i32,
  ) -> Result<Self> {
    let dedup_hash = if suffix_ram_limit_mb < 0.0 {
      return Err(LuceneError::illegal_argument(format!(
        "ramLimitMB must be >= 0; got: {suffix_ram_limit_mb}"
      )));
    } else if suffix_ram_limit_mb > 0f64 {
      Some(NodeHash::new(suffix_ram_limit_mb)?)
    } else {
      None
    };

    let num_bytes_written = 1; // pad 1 byte, written lazily
    let padding_byte_pending = true;

    let fst_meta = FSTMetadata::new(input_type, outputs, None, -1, version, 0);
    let fst = FST::new(fst_meta, NullFSTReader);
    let mut frontier = Vec::with_capacity(16);
    frontier.push(UnCompiledNode::new(0));
    Ok(Self {
      dedup_hash,
      fst,
      last_input: IntsRefBuilder::default(),
      padding_byte_pending,
      last_frozen_node: 0,
      arc_sizes: vec![],
      fixed_length_arcs_buffer: FixedLengthArcsBuffer::new(),
      arc_count: 0,
      node_count: 0,
      binary_search_node_count: 0,
      direct_addressing_node_count: 0,
      continuous_node_count: 0,
      allow_fixed_length_arcs,
      direct_addressing_max_oversizing_factor,
      version,
      direct_addressing_expansion_credit: 0,
      data_output,
      scratch_bytes: GrowableByteArrayDataOutput::new(),
      num_bytes_written,
      frontier,
    })
  }
  fn compile_node(&mut self, node_in_idx: usize) -> Result<CompiledNode> {
    let num_arcs = self.frontier[node_in_idx].num_arcs;

    let bytes_pos_start = self.num_bytes_written;

    let node = match self.dedup_hash.is_some() {
      true => {
        if num_arcs == 0 {
          let node = self.add_node(node_in_idx)?;
          self.last_frozen_node = node;
          node
        } else {
          NodeHash::add(node_in_idx, self)?
        }
      },
      false => self.add_node(node_in_idx)?,
    };

    debug_assert!(node != -2);

    let bytes_pos_end = self.num_bytes_written;
    if bytes_pos_end != bytes_pos_start {
      // The FST added a new node:
      debug_assert!(bytes_pos_end > bytes_pos_start);
      self.last_frozen_node = node;
    }

    Ok(CompiledNode { node })
  }
  fn freeze_tail(&mut self, prefix_len_plus1: usize) -> Result<()> {
    let (len, down_to) = { (self.last_input.length(), prefix_len_plus1.max(1)) };

    let mut idx = len;
    while idx >= down_to {
      let (label, next_final_output, is_final, prev_idx) = {
        let node = &mut self.frontier[idx];
        let prev_idx = idx - 1;

        let next_final_output = if self.dedup_hash.is_none() {
          node.output.take()
        } else {
          None
        };
        // We "fake" the node as being final if it has no
        // outgoing arcs; in theory we could leave it
        // as non-final (the FST can represent this), but
        // FSTEnum, Util, etc., have trouble w/ non-final
        // dead-end states:
        let is_final = node.is_final || node.num_arcs == 0;
        let label = self.last_input.int_at(prev_idx);
        (label, next_final_output, is_final, prev_idx)
      };
      let compiled = self.compile_node(idx)?;
      let node = &mut self.frontier[idx];
      let next_final_output = next_final_output.or_else(|| node.output.take());
      node.clear();
      let parent = &mut self.frontier[prev_idx];
      // this node makes it and we now compile it.  first,
      // compile any targets that were previously
      // undecided:
      parent.replace_last(
        label,
        NodeEnum::CompiledNode(compiled),
        next_final_output,
        is_final,
      );
      idx -= 1;
    }

    Ok(())
  }
  /// Add the next input/output pair. The provided input must be sorted after
  /// the previous one according to [`IntsRef::cmp`]. It's also OK to add
  /// the same input twice in a row with different outputs, as long as
  /// [`Outputs`] implements the [`Outputs::merge`] method. Note
  /// that input is fully consumed after this method returns (so the caller is
  /// free to reuse), but output is not. So if your outputs are changeable
  /// (e.g. [`ByteSequenceOutputs`](crate::core::util::fst_impl::byte_sequence_outputs::ByteSequenceOutputs)
  /// or
  /// [`IntSequenceOutputs`](crate::core::util::fst_impl::int_sequence_outputs::IntSequenceOutputs)), then you cannot reuse them across calls.
  /// Empty outputs must be supplied as `None`; `Some` contains a nonempty payload.
  pub fn add(&mut self, input: &IntsRef<Vec<i32>>, mut output: Option<O::V>) -> Result<()> {
    let ints = &input.ints;

    debug_assert!(
      self.last_input.length() == 0 || *input >= *self.last_input.get(),
      "inputs are added out of order lastInput={:?} vs input={:?}",
      self.last_input.get(),
      input
    );

    if input.length == 0 {
      // empty input: only allowed as first input.  we have
      // to special case this because the packed FST
      // format cannot represent the empty input since
      // 'finalness' is stored on the incoming arc, not on
      // the node
      self.frontier[0].is_final = true;
      self.set_empty_output(output)?;
      return Ok(());
    }

    // Compare shared prefix length
    let mut pos1 = 0;
    let mut pos2 = input.offset;
    let pos1_stop = self.last_input.length().min(input.length);
    while pos1 < pos1_stop && self.last_input.int_at(pos1) == ints[pos2] {
      pos1 += 1;
      pos2 += 1;
    }
    let prefix_len_plus1 = pos1 + 1;

    if self.frontier.len() < (input.length + 1) {
      let old_len = self.frontier.len();
      let min_size = input.length + 1;
      if self.frontier.capacity().min(ArrayUtil::MAX_ARRAY_LENGTH) < min_size {
        let capacity = ArrayUtil::oversize(min_size, std::mem::size_of::<UnCompiledNode<O::V>>())?;
        self.frontier.reserve_exact(capacity - old_len);
      }
      self
        .frontier
        .extend((old_len..min_size).map(UnCompiledNode::new));
    }
    // minimize/compile states from previous input's
    // orphan'd suffix
    self.freeze_tail(prefix_len_plus1)?;
    // init tail states for current input
    let offset = input.offset;
    for idx in prefix_len_plus1..=input.length {
      let label = ints[offset + idx - 1];
      let un_compiled = NodeEnum::UnCompiledNode;
      self.frontier[idx - 1].add_arc(label, un_compiled)?;
    }

    let last_input_len = self.last_input.length();
    let last_node = &mut self.frontier[input.length];
    if last_input_len != input.length || prefix_len_plus1 != input.length + 1 {
      last_node.is_final = true;
      last_node.output = None;
    }
    // push conflicting outputs forward, only as far as
    // needed
    let outputs = &self.fst.outputs;
    for idx in 1..prefix_len_plus1 {
      let (parents, nodes) = self.frontier.split_at_mut(idx);
      let parent = &mut parents[idx - 1];
      let node = &mut nodes[0];
      let label = ints[offset + idx - 1];
      let last_output = parent.get_last_output(label);

      if last_output.is_some() {
        let common_output_prefix = outputs.common(&output, last_output);

        let word_suffix = outputs.subtract(last_output, &common_output_prefix);

        let common_output_prefix = parent.set_last_output(label, common_output_prefix);
        node.prepend_output(&word_suffix, outputs);
        outputs.subtract_assign(&mut output, common_output_prefix);
      } else {
        outputs.subtract_assign(&mut output, &None);
      }
    }
    if self.last_input.length() == input.length && prefix_len_plus1 == input.length + 1 {
      // same input more than 1 time in a row,
      // mapping to multiple outputs
      let last_node = &self.frontier[input.length];
      let v = self.fst.outputs.merge(&last_node.output, &output)?;
      self.frontier[input.length].output = v;
    } else {
      // this new arc is private to this new input; set its
      // arc output to the leftover output:
      let label = ints[input.offset + prefix_len_plus1 - 1];
      let _ = self.frontier[prefix_len_plus1 - 1].set_last_output(label, output);
    }

    // Save last input
    if self.last_input.ints().len() >= input.length {
      self.last_input.ints()[pos1..input.length]
        .copy_from_slice(&ints[input.offset + pos1..input.offset + input.length]);
      self.last_input.set_length(input.length);
    } else {
      self.last_input.copy_ints_ref(input)?;
    }
    Ok(())
  }
  /// Returns the metadata of the final FST. NOTE: this will return None if
  /// nothing is accepted by the FST themselves.
  ///
  /// To create the FST, you need to:
  ///
  /// - If an FST reader data output was used, such as the one returned by
  ///   [`get_on_heap_reader_writer`]
  ///
  /// ```text
  /// let fst_metadata = fst_compiler.compile()?.expect("FST must accept at least one input");
  /// let fst = FST::from_fst_reader(fst_metadata, fst_compiler.get_fst_reader()?)
  ///     .expect("FST metadata must describe a non-empty FST");
  /// ```
  ///
  /// - If a non-FSTReader DataOutput was used, such as
  ///   [`IndexOutput`], you need to
  ///   first create the corresponding
  ///   [`DataInput`](crate::core::store::data_input::DataInput), such as
  ///   [`IndexInput`](crate::core::store::data_input::DataInput) then pass it to
  ///   the FST construct
  pub fn compile(&mut self) -> Result<Option<FSTMetadata<O>>> {
    // Minimize nodes in the last word's suffix
    self.freeze_tail(0)?;
    if self.frontier[0].num_arcs == 0 {
      if self.fst.metadata.empty_output.is_none() {
        // return None for completely empty FST which accepts nothing
        return Ok(None);
      } else {
        // we haven't written the padding byte so far, but the FST is
        // still valid
        self.write_padding_byte()?;
      }
    }
    let compiled_root = self.compile_node(0)?;
    self.frontier[0].clear();
    self.finish(compiled_root.node)?;
    let v = std::mem::take(&mut self.fst.metadata);
    Ok(Some(v))
  }

  pub fn close_data_output(&mut self) -> Result<()> {
    self.data_output.close()
  }

  // serializes new node by appending its bytes to the end
  // of the current byte buffer
  pub(crate) fn add_node(&mut self, node_in_idx: usize) -> Result<i64> {
    let node_in = &self.frontier[node_in_idx];
    if node_in.num_arcs == 0 {
      return Ok(if node_in.is_final {
        FINAL_END_NODE
      } else {
        NON_FINAL_END_NODE
      });
    }
    // reset the scratch writer to prepare for new write
    self.scratch_bytes.set_position(0)?;

    let do_fixed_length_arcs = self.should_expand_node_with_fixed_length_arcs(node_in);
    if do_fixed_length_arcs {
      self.arc_sizes.clear();
      ArrayUtil::grow_capacity(&mut self.arc_sizes, node_in.num_arcs)?;
    }

    self.arc_count += node_in.num_arcs as i64;

    let last_arc = node_in.num_arcs - 1;
    let mut last_arc_start = 0;
    let mut max_bytes_per_arc = 0;
    let mut max_bytes_per_arc_without_label = 0;

    for (arc_idx, arc) in node_in.arcs.iter().enumerate().take(node_in.num_arcs) {
      match &arc.target {
        NodeEnum::CompiledNode(target) => {
          let mut flags = 0;

          if arc_idx == last_arc {
            flags |= BIT_LAST_ARC;
          }

          if self.last_frozen_node == target.node && !do_fixed_length_arcs {
            flags |= BIT_TARGET_NEXT;
          }

          if arc.is_final {
            flags |= BIT_FINAL_ARC;
            if !arc.next_final_output.is_none() {
              flags |= BIT_ARC_HAS_FINAL_OUTPUT;
            }
          } else {
            debug_assert!(arc.next_final_output.is_none());
          }

          let target_has_arcs = target.node > 0;
          if !target_has_arcs {
            flags |= BIT_STOP_NODE;
          }

          // `arc.output` is not mutated while this arc is serialized, so the
          // no-output check only needs to be evaluated once.
          let arc_has_output = !arc.output.is_none();
          if arc_has_output {
            flags |= BIT_ARC_HAS_OUTPUT;
          }

          self.scratch_bytes.write_byte(flags)?;

          let label_start = self.scratch_bytes.get_position();
          // this code should be keep same with `self.write_label`;
          {
            debug_assert!(arc.label >= 0, "v = {}", arc.label);

            match self.fst.metadata.input_type {
              InputType::Byte1 => {
                debug_assert!(arc.label <= 255, "v = {}", arc.label);
                self.scratch_bytes.write_byte(arc.label as u8)?;
              },
              InputType::Byte2 => {
                debug_assert!(arc.label <= 65535, "v = {}", arc.label);
                self.scratch_bytes.write_short(arc.label as i16)?;
              },
              InputType::Byte4 => {
                self.scratch_bytes.write_vint(arc.label)?;
              },
            }
          }
          let label_end = self.scratch_bytes.get_position();
          let num_label_bytes = (label_end - label_start) as i32;

          if arc_has_output {
            self
              .fst
              .outputs
              .write(&arc.output, &mut self.scratch_bytes)?;
          }

          if !arc.next_final_output.is_none() {
            self
              .fst
              .outputs
              .write_final_output(&arc.next_final_output, &mut self.scratch_bytes)?;
          }

          if target_has_arcs && (flags & BIT_TARGET_NEXT) == 0 {
            self.scratch_bytes.write_vlong(target.node)?;
          }

          if do_fixed_length_arcs {
            let arc_length = self.scratch_bytes.get_position() - last_arc_start;
            let num_arc_bytes: i32 = arc_length.try_convert()?;
            self.arc_sizes.push([num_arc_bytes, num_label_bytes]);
            last_arc_start = self.scratch_bytes.get_position();
            max_bytes_per_arc = max_bytes_per_arc.max(num_arc_bytes);
            max_bytes_per_arc_without_label =
              max_bytes_per_arc_without_label.max(num_arc_bytes - num_label_bytes);
          }
        },
        NodeEnum::UnCompiledNode => {
          return Err(LuceneError::illegal_state("should be compiled"));
        },
      }
    }
    /*
     *
     * LUCENE-4682: what is a fair heuristic here?
     * It could involve some of these:
     * 1. how "busy" the node is: nodeIn.inputCount relative to frontier[0].inputCount?
     * 2. how much binSearch saves over scan: nodeIn.numArcs
     * 3. waste: numBytes vs numBytesExpanded
     *
     * the one below just looks at #3
    if (doFixedLengthArcs) {
      // rough heuristic: make this 1.25 "waste factor" a parameter to the phd ctor????
      int numBytes = lastArcStart - startAddress;
      int numBytesExpanded = maxBytesPerArc * nodeIn.numArcs;
      if (numBytesExpanded > numBytes*1.25) {
        doFixedLengthArcs = false;
      }
    }
     */
    if do_fixed_length_arcs {
      debug_assert!(max_bytes_per_arc > 0);
      let label_range = node_in.arcs[last_arc].label - node_in.arcs[0].label + 1;
      debug_assert!(label_range > 0);
      let continuous_label = label_range == node_in.num_arcs as i32;
      if continuous_label && self.version >= VERSION_CONTINUOUS_ARCS {
        self.write_node_for_direct_addressing_or_continuous(
          node_in_idx,
          max_bytes_per_arc_without_label,
          label_range,
          true,
        )?;
        self.continuous_node_count += 1;
      } else if self.should_expand_node_with_direct_addressing(
        node_in_idx,
        max_bytes_per_arc,
        max_bytes_per_arc_without_label,
        label_range,
      )? {
        self.write_node_for_direct_addressing_or_continuous(
          node_in_idx,
          max_bytes_per_arc_without_label,
          label_range,
          false,
        )?;
        self.direct_addressing_node_count += 1;
      } else {
        self.write_node_for_binary_search(node_in_idx, max_bytes_per_arc)?;
        self.binary_search_node_count += 1;
      }
    }

    self.reverse_scratch_bytes();
    // write the padding byte if needed
    if self.padding_byte_pending {
      self.write_padding_byte()?;
    }

    self
      .scratch_bytes
      .write_to_data_output(&mut self.data_output)?;
    self.num_bytes_written += self.scratch_bytes.get_position() as i64;

    self.node_count += 1;
    Ok(self.num_bytes_written - 1)
  }
  /// Get the respective [`DataOutputEnum`]. To call this method, you need
  /// to use the default [`DataOutput`] or
  /// [`get_on_heap_reader_writer`],
  /// otherwise an error will be returned.
  pub fn get_fst_reader(&mut self) -> Result<DataOutputEnum<DO>> {
    let is_fst_reader = match self.data_output {
      DataOutputEnum::FromDir(_) => false,
      DataOutputEnum::ReadWriter(_) => true,
    };
    if is_fst_reader {
      let v = std::mem::replace(
        &mut self.data_output,
        DataOutputEnum::ReadWriter(ReadWriteDataOutput::default()),
      );
      Ok(v)
    } else {
      Err(LuceneError::illegal_state(format!(
        "The DataOutput must implement FSTReader, but got {}",
        self.data_output
      )))
    }
  }
  pub fn get_direct_addressing_max_oversizing_factor(&self) -> f32 {
    self.direct_addressing_max_oversizing_factor
  }

  pub fn get_node_count(&self) -> i64 {
    1 + self.node_count
  }

  pub fn get_arc_count(&self) -> i64 {
    self.arc_count
  }
  /// Write the padding byte, ensure no node gets address 0 which is reserved
  /// to mean the stop state w/ no arcs
  fn write_padding_byte(&mut self) -> Result<()> {
    debug_assert!(self.padding_byte_pending);
    self.data_output.write_byte(0)?;
    self.padding_byte_pending = false;
    Ok(())
  }
  //
  // Due to Rust's borrowing rules, this method performs a mutable operation
  // within logic that holds an immutable reference to self. Therefore, we
  // manually inlined this function into the code.
  #[allow(dead_code)]
  fn write_label(&mut self, _v: i32) -> Result<()> {
    Ok(())
  }

  /// Returns whether the given node should be expanded with fixed length
  /// arcs. Nodes will be expanded depending on their depth (distance from
  /// the root node) and their number of arcs.
  ///
  ///
  /// Nodes with fixed length arcs use more space, because they encode all
  /// arcs with a fixed number of bytes, but they allow either binary
  /// search or direct addressing on the arcs (instead of linear scan) on
  /// lookup by arc label.
  fn should_expand_node_with_fixed_length_arcs(&self, node: &UnCompiledNode<O::V>) -> bool {
    self.allow_fixed_length_arcs
      && (((node.depth as usize) <= FIXED_LENGTH_ARC_SHALLOW_DEPTH
        && node.num_arcs >= FIXED_LENGTH_ARC_SHALLOW_NUM_ARCS)
        || node.num_arcs >= FIXED_LENGTH_ARC_DEEP_NUM_ARCS)
  }
  /// Returns whether the given node should be expanded with direct addressing
  /// instead of binary search.
  ///
  ///
  /// Prefer direct addressing for performance if it does not oversize binary
  /// search byte size too much, so that the arcs can be directly
  /// addressed by label.
  ///
  ///
  /// # See also
  ///
  /// [`FSTCompiler::get_direct_addressing_max_oversizing_factor`](Self::get_direct_addressing_max_oversizing_factor)
  fn should_expand_node_with_direct_addressing(
    &mut self,
    node_in_idx: usize,
    num_bytes_per_arc: i32,
    max_bytes_per_arc_without_label: i32,
    label_range: i32,
  ) -> Result<bool> {
    // Anticipate precisely the size of the encodings.
    let node_in = &self.frontier[node_in_idx];
    let size_for_binary_search = num_bytes_per_arc * node_in.num_arcs as i32;
    let size_for_direct_addressing = get_num_presence_bytes(label_range)
      + self.arc_sizes[0][1]
      + max_bytes_per_arc_without_label * node_in.num_arcs as i32;

    // Determine the allowed oversize compared to binary search.
    // This is defined by a parameter of FST Builder (default 1: no
    // oversize).
    let allowed_oversize =
      (size_for_binary_search as f32 * self.get_direct_addressing_max_oversizing_factor()) as i32;
    let expansion_cost = size_for_direct_addressing - allowed_oversize;

    // Select direct addressing if either:
    // - Direct addressing size is smaller than binary search. In this case,
    //   increment the credit by the reduced size (to use it later).
    // - Direct addressing size is larger than binary search, but the positive
    //   credit allows the oversizing. In this case, decrement the credit by the
    //   oversize.
    // In addition, do not try to oversize to a clearly too large node size
    // (this is the DIRECT_ADDRESSING_MAX_OVERSIZE_WITH_CREDIT_FACTOR
    // parameter).
    if expansion_cost == 0
      || (self.direct_addressing_expansion_credit >= expansion_cost as i64
        && size_for_direct_addressing
          <= (allowed_oversize as f32 * DIRECT_ADDRESSING_MAX_OVERSIZE_WITH_CREDIT_FACTOR) as i32)
    {
      self.direct_addressing_expansion_credit -= expansion_cost as i64;
      return Ok(true);
    }

    Ok(false)
  }
  fn write_node_for_binary_search(
    &mut self,
    node_in_idx: usize,
    max_bytes_per_arc: i32,
  ) -> Result<()> {
    // Build the header in a buffer.
    // It is a false/special arc which is in fact a node header with node
    // flags followed by node metadata.
    // self.fixed_length_arcs_buffer.reset_position();
    self.fixed_length_arcs_buffer.reset_position()?;
    self
      .fixed_length_arcs_buffer
      .write_byte(ARCS_FOR_BINARY_SEARCH)?;
    let node_in = &self.frontier[node_in_idx];
    self
      .fixed_length_arcs_buffer
      .write_vint(node_in.num_arcs as i32)?;
    self
      .fixed_length_arcs_buffer
      .write_vint(max_bytes_per_arc)?;

    let header_len = self.fixed_length_arcs_buffer.get_position();
    // Expand the arcs in place, backwards.
    let src_pos = self.scratch_bytes.get_position();
    let dest_pos = header_len + (node_in.num_arcs as i32 * max_bytes_per_arc) as usize;

    debug_assert!(dest_pos >= src_pos);

    if dest_pos > src_pos {
      self.scratch_bytes.set_position(dest_pos)?;
      let scratch_bytes = self.scratch_bytes.get_bytes();
      let arc_bytes = &self.arc_sizes;
      let mut src_pos = src_pos;
      let mut dest_pos = dest_pos;
      let max_bytes_per_arc = max_bytes_per_arc as usize;
      for arc_idx in (0..node_in.num_arcs).rev() {
        dest_pos -= max_bytes_per_arc;
        let arc_len = arc_bytes[arc_idx][0] as usize;
        src_pos -= arc_len;
        if src_pos != dest_pos {
          debug_assert!(
            dest_pos >= src_pos,
            "dest_pos={} < src_pos={} at arc_idx={}, max_bytes_per_arc={}, arc_len={}, num_arcs={}",
            dest_pos,
            src_pos,
            arc_idx,
            max_bytes_per_arc,
            arc_len,
            node_in.num_arcs
          );
          scratch_bytes.copy_within(src_pos..src_pos + arc_len, dest_pos);
        }
      }
    }

    // Write header at the beginning
    self
      .scratch_bytes
      .get_bytes()
      .copy_from(&self.fixed_length_arcs_buffer.get_bytes()[..header_len], 0);

    Ok(())
  }
  /// Reverse the scratch bytes in place. This operation does not affect
  /// `scratch_bytes.get_position()`.
  fn reverse_scratch_bytes(&mut self) {
    let pos = self.scratch_bytes.get_position();
    self.scratch_bytes.get_bytes()[..pos].reverse();
  }
  /// Write bytes from a source slice to the scratch bytes. The written
  /// bytes must fit within what was already written in the scratch bytes.
  ///
  ///
  /// This operation does not affect `scratch_bytes.get_position()`.
  ///
  ///
  /// # Arguments
  ///
  /// * `dest_pos` - the position in the scratch bytes
  /// * `bytes` - the source byte array
  /// * `offset` - the offset inside the source byte array
  /// * `length` - the number of bytes to write
  #[allow(dead_code)]
  fn write_scratch_bytes(&mut self, _dest_pos: i32, _bytes: &[u8], _offset: i32, _length: i32) {
    // Not Implement in Rust Lucene
  }
  fn write_node_for_direct_addressing_or_continuous(
    &mut self,
    node_in_idx: usize,
    max_bytes_per_arc_without_label: i32,
    label_range: i32,
    continuous: bool,
  ) -> Result<()> {
    // Expand the arcs backwards in a buffer because we remove the labels.
    // So the obtained arcs might occupy less space. This is the reason why
    // this whole method is more complex.
    // Drop the label bytes since we can infer the label based on the arc
    // index, the presence bits, and the first label. Keep the first
    // label.
    let header_max_len = 11;
    let num_presence_bytes = if continuous {
      0
    } else {
      get_num_presence_bytes(label_range) as usize
    };

    let mut src_pos = self.scratch_bytes.get_position();
    let node_in = &self.frontier[node_in_idx];
    let total_arc_bytes =
      (self.arc_sizes[0][1] + node_in.num_arcs as i32 * max_bytes_per_arc_without_label) as usize;

    let mut buffer_offset = header_max_len + num_presence_bytes + total_arc_bytes;
    self
      .fixed_length_arcs_buffer
      .ensure_capacity(buffer_offset)?;
    let buffer = self.fixed_length_arcs_buffer.get_bytes();
    // Copy the arcs to the buffer, dropping all labels except first one.
    for arc_idx in (0..node_in.num_arcs).rev() {
      buffer_offset -= max_bytes_per_arc_without_label as usize;
      let src_arc_len = self.arc_sizes[arc_idx][0] as usize;
      src_pos -= src_arc_len;
      let label_len = self.arc_sizes[arc_idx][1] as usize;
      self
        .scratch_bytes
        .write_to(src_pos, buffer, buffer_offset, 1);
      // Skip the label, copy the remaining.
      let remaining_len = src_arc_len - 1 - label_len;
      if remaining_len != 0 {
        self.scratch_bytes.write_to(
          src_pos + 1 + label_len,
          buffer,
          buffer_offset + 1,
          remaining_len,
        );
      }

      // Copy label for first arc only
      if arc_idx == 0 {
        buffer_offset -= label_len;
        self
          .scratch_bytes
          .write_to(src_pos + 1, buffer, buffer_offset, label_len);
      }
    }

    debug_assert_eq!(
      buffer_offset,
      header_max_len + num_presence_bytes,
      "buffer_offset mismatch"
    );
    // Build the header in the buffer.
    // It is a false/special arc which is in fact a node header with node
    // flags followed by node metadata.
    // Write header
    self.fixed_length_arcs_buffer.reset_position()?;
    self.fixed_length_arcs_buffer.write_byte(if continuous {
      ARCS_FOR_CONTINUOUS
    } else {
      ARCS_FOR_DIRECT_ADDRESSING
    })?;
    self.fixed_length_arcs_buffer.write_vint(label_range)?; // labelRange instead of numArcs.
    self
      .fixed_length_arcs_buffer
      .write_vint(max_bytes_per_arc_without_label)?; // maxBytesPerArcWithoutLabel instead of maxBytesPerArc.
    let header_len = self.fixed_length_arcs_buffer.get_position();

    self.scratch_bytes.set_position(0)?;
    self.scratch_bytes.write_bytes_range(
      self.fixed_length_arcs_buffer.get_bytes(),
      0,
      header_len,
    )?;

    // Write presence bits if not continuous
    if !continuous {
      self.write_presence_bits(node_in_idx)?;
      debug_assert_eq!(
        self.scratch_bytes.get_position(),
        header_len + num_presence_bytes
      );
    }

    // Write first label + arcs
    self.scratch_bytes.write_bytes_range(
      self.fixed_length_arcs_buffer.get_bytes(),
      buffer_offset,
      total_arc_bytes,
    )?;

    debug_assert_eq!(
      self.scratch_bytes.get_position(),
      header_len + num_presence_bytes + total_arc_bytes
    );
    Ok(())
  }

  fn write_presence_bits(&mut self, node_in_idx: usize) -> Result<()> {
    let mut presence_bits: u8 = 1; // The first arc is always present.
    let mut presence_index = 0;
    let node_in = &self.frontier[node_in_idx];
    let mut previous_label = node_in.arcs[0].label;

    let byte_size = i8::BITS as i32;
    for arc_idx in 1..node_in.num_arcs {
      let label = node_in.arcs[arc_idx].label;
      debug_assert!(label > previous_label);
      presence_index += label - previous_label;
      while presence_index >= byte_size {
        self.scratch_bytes.write_byte(presence_bits)?;
        presence_bits = 0;
        presence_index -= byte_size;
      }
      // Set the bit at presenceIndex to flag that the corresponding arc
      // is present.
      presence_bits |= 1 << presence_index;
      previous_label = label;
    }

    debug_assert!({
      let last_label = node_in.arcs[node_in.num_arcs - 1].label;
      let first_label = node_in.arcs[0].label;
      presence_index == (last_label - first_label) % 8
    });
    debug_assert!(presence_bits != 0); // The last byte is not 0.
    debug_assert!((presence_bits & (1 << presence_index)) != 0); // The last arc is always present.

    self.scratch_bytes.write_byte(presence_bits)?;
    Ok(())
  }
  pub(crate) fn set_empty_output(&mut self, v: Option<O::V>) -> Result<()> {
    if let Some(existing) = &mut self.fst.metadata.empty_output {
      self.fst.metadata.empty_output = Some(self.fst.outputs.merge(existing, &v)?);
    } else {
      self.fst.metadata.empty_output = Some(v);
    }
    Ok(())
  }
  /// Finish Data Writing
  ///
  /// # Warning
  ///
  /// If Data written to file (See:DataOutputEnum::FromDir) ,The actual data
  /// is not flushed to the underlying file until the [`FSTCompiler`] is
  /// dropped. If you need to ensure the data is written before the
  /// compiler is dropped, consider manually finalizing or flushing the
  /// data, or ensure the compiler goes out of scope.
  ///
  /// This method does not guarantee that the data has been persisted on disk.
  pub(crate) fn finish(&mut self, mut new_start_node: i64) -> Result<()> {
    debug_assert!(new_start_node <= self.num_bytes_written);

    if self.fst.metadata.start_node != -1 {
      return Err(LuceneError::illegal_state("already finished"));
    }

    if new_start_node == FINAL_END_NODE && self.fst.metadata.empty_output.is_some() {
      new_start_node = 0;
    }

    self.fst.metadata.start_node = new_start_node;
    self.fst.metadata.num_bytes = self.num_bytes_written;

    // Freeze the data output if it's a read-write buffer
    match self.data_output {
      DataOutputEnum::FromDir(_) => {
        // file flush by when Drop FSTCompiler
      },
      DataOutputEnum::ReadWriter(ref mut rw) => {
        rw.freeze()?;
      },
    }

    Ok(())
  }
  /// Returns the estimated heap memory used by the in-construction FST.
  pub fn fst_ram_bytes_used(&self) -> Result<i64> {
    let mut ram_bytes_used = self.scratch_bytes.ram_bytes_used()?;
    ram_bytes_used += self.data_output.ram_bytes_used()?;
    Ok(ram_bytes_used)
  }

  /// Returns the current byte size of the FST being built.
  pub fn fst_size_in_bytes(&self) -> i64 {
    self.num_bytes_written
  }
}

/// This struct is used for FST backed by non-FSTReader DataOutput. It does not
/// allow getting the reverse BytesReader nor writing to a DataOutput.
pub(crate) struct NullFSTReader;
impl Accountable for NullFSTReader {
  fn ram_bytes_used(&self) -> Result<i64> {
    Ok(0)
  }
}
impl FstReader for NullFSTReader {
  type FstBytesReader = DummyBytesReader;

  fn get_reverse_bytes_reader(&self) -> Result<Self::FstBytesReader> {
    Err(LuceneError::unsupported_operation(
      "FST was not constructed with getOnHeapReaderWriter()",
    ))
  }

  fn write_to<DO>(&self, _out: &mut DO) -> Result<()>
  where
    DO: DataOutput,
  {
    Err(LuceneError::unsupported_operation(
      "FST was not constructed with getOnHeapReaderWriter()",
    ))
  }
}
/// Fluent-style builder for constructing an [`FSTCompiler`].
///
/// Creates an FST/FSA builder with all possible tuning and construction tweaks.
/// Read parameter documentation carefully.
pub struct Builder<O, DO>
where
  O: Outputs,
  DO: IndexOutput,
{
  input_type: InputType,
  outputs: O,
  suffix_ram_limit_mb: f64,
  allow_fixed_length_arcs: bool,
  data_output: Option<DataOutputEnum<DO>>,
  direct_addressing_max_oversizing_factor: f32,
  version: i32,
}
impl<O, DO> Builder<O, DO>
where
  O: Outputs,
  DO: IndexOutput,
{
  /// Creates a new [`Builder`] with the given input type and outputs.
  ///
  /// - `input_type`: The input type (transition labels). Can be any variant
  ///   of [`InputType`]. Shorter types consume less memory. Strings
  ///   (character sequences) are typically represented using
  ///   [`InputType::Byte4`] for full Unicode codepoints.
  ///
  /// - `outputs`: The output type for each input sequence. Applies only when
  ///   building an FST. For FSA, use
  ///   [`NoOutputs::get_singleton`](crate::core::util::fst_impl::no_outputs::NoOutputs::get_singleton)
  ///   and `None` for its empty outputs
  ///   as the singleton output.
  pub fn new(input_type: InputType, outputs: O) -> Self {
    Self {
      input_type,
      outputs,
      suffix_ram_limit_mb: 32.0,
      allow_fixed_length_arcs: true,
      data_output: None,
      direct_addressing_max_oversizing_factor: DIRECT_ADDRESSING_MAX_OVERSIZING_FACTOR,
      version: VERSION_CURRENT,
    }
  }
  /// Sets the approximate maximum amount of RAM (in MB) to use for holding
  /// the suffix cache.
  ///
  /// This cache enables the FST to share common suffixes. Passing
  /// `f64::INFINITY` keeps all suffixes, resulting in an exactly minimal
  /// FST. The actual memory usage in that case will be bounded by the
  /// number of unique suffixes.
  ///
  /// If a smaller value is passed, the least recently used suffixes are
  /// discarded, reducing suffix sharing and producing a non-minimal FST.
  /// The larger the limit, the closer the result will be to the minimal
  /// FST, with diminishing returns.
  ///
  /// Pass `0.0` to disable suffix sharing entirely (may result in a
  /// substantially larger FST).
  ///
  /// Note: this is an approximate limit. The implementation uses hash tables
  /// to map suffixes and estimates overhead from unused slots.
  ///
  /// Default: `32.0`
  pub fn suffix_ram_limit_mb(&mut self, mb: f64) -> Result<()> {
    if mb < 0f64 {
      return Err(LuceneError::illegal_argument(format!(
        "suffix_ram_limit_mb must be >= 0; got: {mb}"
      )));
    }
    self.suffix_ram_limit_mb = mb;
    Ok(())
  }

  /// Controls whether fixed-length arc optimization (binary search or direct
  /// addressing) is enabled.
  ///
  /// Disabling this makes the resulting FST smaller but slower to traverse.
  ///
  /// Default: `true`
  pub fn allow_fixed_length_arcs(&mut self, allow: bool) {
    self.allow_fixed_length_arcs = allow;
  }

  /// Set the [`DataOutput`] which is used for low-level writing of FST. If
  /// you want the FST to be immediately readable, you need to use
  /// [`get_on_heap_reader_writer`].
  ///
  /// Otherwise you need to construct the corresponding
  /// [`DataInput`](crate::core::store::data_input::DataInput) and use the FST
  /// loading method to read it.
  ///
  /// # Arguments
  ///
  /// * `data_output` - the [`DataOutput`]
  ///
  /// # Returns
  ///
  /// This builder.
  ///
  /// # See also
  ///
  /// [`get_on_heap_reader_writer`]
  pub fn data_output(&mut self, data_output: DataOutputEnum<DO>) {
    self.data_output = Some(data_output);
  }
  /// Overrides the default maximum oversizing of fixed array allowed to
  /// enable direct addressing of arcs instead of binary search.
  ///
  /// Setting this factor to a negative value (e.g. `-1`) effectively disables
  /// direct addressing, only binary search nodes will be created.
  ///
  /// This factor does not determine whether to encode a node with a list of
  /// variable length arcs or with fixed length arcs. It only determines
  /// the effective encoding of a node that is already known to be encoded
  /// with fixed length arcs.
  ///
  ///
  /// Default = `1`.
  pub fn with_direct_addressing_max_oversizing_factor(&mut self, factor: f32) {
    self.direct_addressing_max_oversizing_factor = factor;
  }
  ///  Expert: Set the codec version.
  pub fn with_version(&mut self, version: i32) -> Result<()> {
    if !(VERSION_90..=VERSION_CURRENT).contains(&version) {
      return Err(LuceneError::illegal_argument(format!(
        "Version must be in range [{} - {}]; got: {}",
        VERSION_90, VERSION_CURRENT, version
      )));
    }
    self.version = version;
    Ok(())
  }
  /// Creates a new [`FSTCompiler`].
  pub fn build(mut self) -> Result<FSTCompiler<O, DO>> {
    let data_output = match self.data_output.take() {
      Some(data_output) => data_output,
      None => DataOutputEnum::ReadWriter(get_on_heap_reader_writer(15)?),
    };
    FSTCompiler::new(
      self.input_type,
      self.suffix_ram_limit_mb,
      self.outputs,
      self.allow_fixed_length_arcs,
      data_output,
      self.direct_addressing_max_oversizing_factor,
      self.version,
    )
  }
}
pub enum DataOutputEnum<O> {
  FromDir(O),
  ReadWriter(ReadWriteDataOutput),
}
impl<O> Display for DataOutputEnum<O>
where
  O: Display,
{
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    match self {
      DataOutputEnum::FromDir(data_output) => {
        write!(f, "{data_output}")
      },
      DataOutputEnum::ReadWriter(_) => {
        write!(f, "ReadWriteDataOutput")
      },
    }
  }
}

impl<O> Accountable for DataOutputEnum<O> {
  fn ram_bytes_used(&self) -> Result<i64> {
    match self {
      DataOutputEnum::FromDir(_) => Ok(0),
      DataOutputEnum::ReadWriter(data_output) => data_output.ram_bytes_used(),
    }
  }
}

impl<O> Closeable for DataOutputEnum<O>
where
  O: Closeable,
{
  fn close(&mut self) -> Result<()> {
    match self {
      DataOutputEnum::FromDir(data_output) => data_output.close(),
      DataOutputEnum::ReadWriter(_) => Ok(()),
    }
  }
}

impl<O> FstReader for DataOutputEnum<O> {
  type FstBytesReader = ReverseBytesReader;

  fn get_reverse_bytes_reader(&self) -> Result<Self::FstBytesReader> {
    match self {
      DataOutputEnum::FromDir(_) => Err(LuceneError::unsupported_operation("")),
      DataOutputEnum::ReadWriter(rw) => match rw.get_reverse_bytes_reader()? {
        BytesReaderEnum2::A(_) => Err(LuceneError::illegal_state(
          "FSTCompiler reader must use a contiguous byte buffer",
        )),
        BytesReaderEnum2::B(reader) => Ok(reader),
      },
    }
  }

  fn write_to<DO>(&self, out: &mut DO) -> Result<()>
  where
    DO: DataOutput,
  {
    match self {
      DataOutputEnum::FromDir(_) => Err(LuceneError::unsupported_operation("")),
      DataOutputEnum::ReadWriter(rw) => rw.write_to(out),
    }
  }
}
impl<O> DataOutput for DataOutputEnum<O>
where
  O: DataOutput,
{
  fn write_byte(&mut self, b: u8) -> Result<()> {
    match self {
      DataOutputEnum::FromDir(data_output) => data_output.write_byte(b),
      DataOutputEnum::ReadWriter(rw) => rw.write_byte(b),
    }
  }

  fn write_bytes_range(&mut self, b: &[u8], offset: usize, length: usize) -> Result<()> {
    match self {
      DataOutputEnum::FromDir(data_output) => data_output.write_bytes_range(b, offset, length),
      DataOutputEnum::ReadWriter(rw) => rw.write_bytes_range(b, offset, length),
    }
  }
}
/// Expert: holds a pending (seen but not yet serialized) arc.
/// `T` is the payload type; an empty output is stored as `None`.
pub(crate) struct Arc<T> {
  pub label: i32, // really an "unsigned" byte
  pub target: NodeEnum,
  pub is_final: bool,
  pub output: Option<T>,
  pub next_final_output: Option<T>,
}
/// # NOTE:
/// Not many instances of Node or CompiledNode are in
/// memory while the FST is being built; it's only the
/// current "frontier":
#[allow(dead_code)] // Retained Node trait and is_compiled implementations currently have no callers.
pub(crate) trait Node {
  fn is_compiled(&self) -> bool;
}
pub(crate) enum NodeEnum {
  // Distinguish an uncompiled-node reference until the arc is compiled.
  UnCompiledNode,
  CompiledNode(CompiledNode),
}
impl Node for NodeEnum {
  fn is_compiled(&self) -> bool {
    match self {
      NodeEnum::UnCompiledNode => false,
      NodeEnum::CompiledNode(node) => node.is_compiled(),
    }
  }
}
pub(crate) struct CompiledNode {
  pub(crate) node: i64,
}
impl Node for CompiledNode {
  fn is_compiled(&self) -> bool {
    true
  }
}
/// Expert: holds a pending (seen but not yet serialized) Node.
/// `T` is the payload type; the node and its arcs store optional outputs.
pub(crate) struct UnCompiledNode<T> {
  pub(crate) num_arcs: usize,
  pub(crate) arcs: SmallVec<[Arc<T>; 1]>,
  pub(crate) output: Option<T>,
  pub(crate) is_final: bool,

  /// This node's depth, starting from the automaton root.
  pub depth: i32,
}
impl<T> UnCompiledNode<T>
where
  T: OutputsBound,
{
  /// Creates a new uncompiled node.
  ///
  /// # Parameters
  /// - `depth`: The node's depth starting from the automaton root. Needed for
  ///   LUCENE-2934 (node expansion based on conditions other than the fanout
  ///   size).
  pub(crate) fn new(depth: usize) -> Self {
    Self {
      num_arcs: 0,
      arcs: SmallVec::new(),
      output: None,
      is_final: false,
      depth: depth as i32,
    }
  }

  pub(crate) fn clear(&mut self) {
    self.num_arcs = 0;
    self.is_final = false;
    self.output = None;
    // We don't clear the depth here because it never changes
    // for nodes on the frontier (even when reused).
  }

  pub(crate) fn get_last_output(&self, label_to_match: i32) -> &Option<T> {
    debug_assert!(self.num_arcs > 0);
    debug_assert!(self.arcs[self.num_arcs - 1].label == label_to_match);
    &self.arcs[self.num_arcs - 1].output
  }

  pub(crate) fn add_arc(&mut self, label: i32, target: NodeEnum) -> Result<()> {
    debug_assert!(label >= 0);
    debug_assert!(
      self.num_arcs == 0 || label > self.arcs[self.num_arcs - 1].label,
      "arc[numArcs-1].label={} new label={} numArcs={}",
      self.arcs[self.num_arcs - 1].label,
      label,
      self.num_arcs
    );

    if self.num_arcs == self.arcs.len() {
      self.arcs.push(Arc {
        label,
        target,
        is_final: false,
        output: None,
        next_final_output: None,
      });
      self.num_arcs += 1;
      return Ok(());
    }

    let arc = &mut self.arcs[self.num_arcs];
    self.num_arcs += 1;
    arc.label = label;
    arc.target = target;
    arc.output = None;
    arc.next_final_output = None;
    arc.is_final = false;
    Ok(())
  }
  pub(crate) fn replace_last(
    &mut self,
    label_to_match: i32,
    target: NodeEnum,
    next_final_output: Option<T>,
    is_final: bool,
  ) {
    debug_assert!(self.num_arcs > 0);
    let arc = &mut self.arcs[self.num_arcs - 1];
    debug_assert_eq!(
      arc.label, label_to_match,
      "arc.label={} vs {}",
      arc.label, label_to_match
    );
    arc.target = target;
    arc.next_final_output = next_final_output;
    arc.is_final = is_final;
  }

  pub(crate) fn set_last_output(
    &mut self,
    label_to_match: i32,
    new_output: Option<T>,
  ) -> &Option<T> {
    debug_assert!(self.num_arcs > 0);
    let arc = &mut self.arcs[self.num_arcs - 1];
    debug_assert_eq!(arc.label, label_to_match);
    arc.output = new_output;
    &arc.output
  }

  /// Pushes an output prefix forward onto all arcs.
  pub(crate) fn prepend_output<O>(&mut self, output_prefix: &Option<O::V>, outputs: &O)
  where
    O: Outputs<V = T>,
  {
    for i in 0..self.num_arcs {
      let current = &mut self.arcs[i].output;
      match outputs.add(output_prefix, current) {
        None => *current = None,
        Some(std::borrow::Cow::Borrowed(next))
          if current
            .as_ref()
            .is_some_and(|value| std::ptr::eq(next, value)) => {},
        Some(std::borrow::Cow::Borrowed(next)) => *current = Some(next.clone()),
        Some(std::borrow::Cow::Owned(next)) => *current = Some(next),
      }
    }

    if self.is_final {
      match outputs.add(output_prefix, &self.output) {
        None => self.output = None,
        Some(std::borrow::Cow::Borrowed(next))
          if self
            .output
            .as_ref()
            .is_some_and(|value| std::ptr::eq(next, value)) => {},
        Some(std::borrow::Cow::Borrowed(next)) => self.output = Some(next.clone()),
        Some(std::borrow::Cow::Owned(next)) => self.output = Some(next),
      }
    }
  }
}
impl<T> Node for UnCompiledNode<T>
where
  T: OutputsBound,
{
  fn is_compiled(&self) -> bool {
    false
  }
}

/// Reusable buffer for building nodes with fixed length arcs (binary search or
/// direct addressing).
pub(crate) struct FixedLengthArcsBuffer {
  bado: ByteArrayDataOutput<Vec<u8>>,
}
impl FixedLengthArcsBuffer {
  pub(crate) fn new() -> Self {
    // Initial capacity is the max length required for the header of a node
    // with fixed length arcs: header(byte) + numArcs(vint) +
    // numBytes(vint)
    let bytes = Vec::new();
    let bado = ByteArrayDataOutput::with_bytes(bytes);
    Self { bado }
  }
  /// Ensures the capacity of the internal byte array. Enlarges it if needed.
  pub(crate) fn ensure_capacity(&mut self, capacity: usize) -> Result<()> {
    if self.bado.bytes.len() < capacity {
      ArrayUtil::grow_no_copy(&mut self.bado.bytes, capacity, || 0)?;
      self.bado.reset()?;
    }
    Ok(())
  }

  pub(crate) fn reset_position(&mut self) -> Result<()> {
    if self.bado.bytes.is_empty() {
      self.ensure_capacity(11)?;
      return Ok(());
    }
    self.bado.reset()
  }

  pub(crate) fn write_byte(&mut self, b: u8) -> Result<()> {
    self.bado.write_byte(b)
  }

  pub(crate) fn write_vint(&mut self, i: i32) -> Result<()> {
    self.bado.write_vint(i)
  }

  pub(crate) fn get_position(&self) -> usize {
    self.bado.get_position()
  }

  /// Gets the internal byte array.
  pub(crate) fn get_bytes(&mut self) -> &mut [u8] {
    &mut self.bado.bytes
  }
}

/// Maximum oversizing factor allowed for direct addressing.
pub(crate) const DIRECT_ADDRESSING_MAX_OVERSIZING_FACTOR: f32 = 1.0;

/// Minimum depth at which fixed-length arcs are considered for shallow
/// nodes.
///
/// See [`FSTCompiler::should_expand_node_with_fixed_length_arcs`](FSTCompiler::should_expand_node_with_fixed_length_arcs)..
pub(crate) const FIXED_LENGTH_ARC_SHALLOW_DEPTH: usize = 3;

/// Minimum number of arcs required to consider fixed-length arcs at shallow
/// depth.
///
/// See [`FSTCompiler::should_expand_node_with_fixed_length_arcs`](FSTCompiler::should_expand_node_with_fixed_length_arcs)..
pub(crate) const FIXED_LENGTH_ARC_SHALLOW_NUM_ARCS: usize = 5;

/// Minimum number of arcs required to consider fixed-length arcs at deep
/// depth.
///
/// See [`FSTCompiler::should_expand_node_with_fixed_length_arcs`](FSTCompiler::should_expand_node_with_fixed_length_arcs).
pub(crate) const FIXED_LENGTH_ARC_DEEP_NUM_ARCS: usize = 10;

/// Maximum oversizing factor allowed for direct addressing compared to
/// binary search when expansion credits allow the oversizing. This
/// factor prevents expansions that are obviously too costly even if
/// there are sufficient credits.
///
/// See [`FSTCompiler::should_expand_node_with_direct_addressing`](FSTCompiler::should_expand_node_with_direct_addressing).
const DIRECT_ADDRESSING_MAX_OVERSIZE_WITH_CREDIT_FACTOR: f32 = 1.66;
pub fn get_on_heap_reader_writer(block_bits: i32) -> Result<ReadWriteDataOutput> {
  ReadWriteDataOutput::new(block_bits, true)
}