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
/*
 * 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::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::Arc;

use parking_lot::Mutex;

use crate::core::codecs::Codecs;
use crate::core::codecs::codec;
use crate::core::codecs::segment_info_format::SegmentInfoFormat;
use crate::core::codecs::{Codec, CodecUtil};
use crate::core::index::IndexFileNames;
use crate::core::index::index_commit::IndexCommit;

use crate::core::index::index_file_names::base36;
use crate::core::index::index_writer::get_actual_max_docs;
use crate::core::index::segment_commit_info::SegmentCommitInfo;
use crate::core::store::check_sum_index_input::ChecksumIndexInput;
use crate::core::store::directory::Directory;
use crate::core::store::{DataInput, IO_CONTEXT_DEFAULT, IndexOutput};
use crate::core::util::close::{Closeable, CloseableRef};
use crate::core::util::error::lucene_error::{LuceneError, LuceneErrorKind, Result};
use crate::core::util::output_enum::OutputEnum;
use crate::core::util::{
  HasIdentity, IOUtils, LATEST, MIN_SUPPORTED_MAJOR, StringHelper, TryIntoInt, Version,
};
#[cfg(test)]
use crate::test_framework::core::util::failure_context::{
  ExecutionMethod, ExecutionOwner, ExecutionScope,
};
use std::io::{Error, ErrorKind, Write};

static INFO_STREAM: Mutex<Option<OutputEnum>> = Mutex::new(None);

/// A collection of [`SegmentInfo`](crate::core::index::segment_info::SegmentInfo) objects with methods for operating on those
/// segments in relation to the file system.
///
/// The active segments in the index are stored in the segment info file,
/// `segments_N`. There may be one or more `segments_N` files in the index;
/// however, the one with the largest generation is the active one (when older
/// `segments_N` files are present it's because they temporarily cannot be
/// deleted, or a custom
/// [`IndexDeletionPolicy`](crate::core::index::index_deletion_policy) is in use).
/// This file lists each segment by name and has details about the codec and
/// generation of deletes.
///
/// Files:
///
/// - `segments_N`: Header, LuceneVersion, Version, NameCounter, SegCount,
///   MinSegmentLuceneVersion, `<SegName, SegID, SegCodec, DelGen,
///   DeletionCount, FieldInfosGen, DocValuesGen,
///   UpdatesFiles><sup>SegCount</sup>, CommitUserData, Footer
///
/// Data types:
///
/// - `Header` -> [`IndexHeader`](CodecUtil::write_index_header)
/// - `LuceneVersion` -> Which Lucene code [`Version`] was used for this commit,
///   written as three
///   [`DataOutput::write_vint`](crate::core::store::data_output::DataOutput::write_vint):
///   major, minor, bugfix
/// - `MinSegmentLuceneVersion` -> Lucene code [`Version`] of the oldest
///   segment, written as three
///   [`DataOutput::write_vint`](crate::core::store::data_output::DataOutput::write_vint):
///   major, minor, bugfix; this is only written only if there's at least one
///   segment
/// - `NameCounter`, `SegCount`, `DeletionCount` ->
///   [`DataOutput::write_int`](crate::core::store::data_output::DataOutput::write_int)
/// - `Generation`, `Version`, `DelGen`, [`Checksum`](crate::core::store::checksum::Checksum),
///   `FieldInfosGen`,
///   `DocValuesGen` ->
///   [`DataOutput::write_long`](crate::core::store::data_output::DataOutput::write_long)
/// - `SegID` ->
///   [`DataOutput::write_byte`](crate::core::store::data_output::DataOutput::write_byte)
/// - `SegName`, `SegCodec` ->
///   [`DataOutput::write_string`](crate::core::store::data_output::DataOutput::write_string)
/// - `CommitUserData` ->
///   [`DataOutput::write_map_of_strings`](crate::core::store::data_output::DataOutput::write_map_of_strings)
/// - `UpdatesFiles` ->
///   Map<[`DataOutput::write_int`](crate::core::store::data_output::DataOutput::write_int),
///   [`DataOutput::write_set_of_strings`](crate::core::store::data_output::DataOutput::write_set_of_strings)>
/// - `Footer` -> [`CodecUtil::write_footer`]
///
/// Field Descriptions:
///
/// - `Version` counts how often the index has been changed by adding or
///   deleting documents.
/// - `NameCounter` is used to generate names for new segment files.
/// - `SegName` is the name of the segment, and is used as the file name prefix
///   for all of the files that compose the segment's index.
/// - `DelGen` is the generation count of the delete file. If this is `-1`,
///   there are no deletes. Anything above zero means there are deletes stored
///   by [`LiveDocsFormat`](crate::core::codecs::live_docs_format).
/// - `DeletionCount` records the number of deleted documents in this segment.
/// - `SegCodec` is the [`Codec::get_name`] of the codec that encoded this segment.
/// - `SegID` is the identifier of the Codec that encoded this segment.
/// - `CommitUserData` stores optional user-supplied opaque
///   [`HashMap<String, String>`] data that was passed to
///   [`IndexWriter::set_live_commit_data`](crate::core::index::index_writer::IndexWriter::set_live_commit_data).
/// - `FieldInfosGen` is the generation count of the fieldInfos file. If this is
///   `-1`, there are no updates to the fieldInfos in that segment. Anything
///   above zero means there are updates to fieldInfos stored by
///   [`FieldInfosFormat`](crate::core::codecs::field_infos_format::FieldInfosFormat).
/// - `DocValuesGen` is the generation count of the updatable DocValues. If this
///   is `-1`, there are no updates to DocValues in that segment. Anything above
///   zero means there are updates to DocValues stored by
///   [`DocValuesFormat`](crate::core::codecs::doc_values_format::DocValuesFormat).
/// - `UpdatesFiles` stores the set of files that were updated in that segment
///   per field.
///
/// # Note
/// This module is experimental and subject to change.
pub struct SegmentInfos<D> {
  /// Used to name new segments.
  pub counter: i64,
  /// Counts how often the index has been changed.
  pub version: i64,
  /// Generation of the "segments_N" for the next commit.
  generation: i64,
  /// Generation of the "segments_N" file we last successfully read or wrote.
  last_generation: i64,
  /// Opaque `HashMap<String, String>` that user can specify during
  /// `IndexWriter.commit`.
  pub user_data: HashMap<String, String>,
  /// List of [`SegmentCommitInfo`](crate::core::index::segment_commit_info::SegmentCommitInfo) objects.
  pub(crate) segments: Vec<SegmentCommitInfo<D>>,
  /// [`SegmentCommitInfo`](crate::core::index::segment_commit_info::SegmentCommitInfo)s removed from `segments` but still needed by
  /// concurrent reader-pool work.
  pub(crate) dropped_segment_commit_infos: HashMap<Arc<str>, SegmentCommitInfo<D>>,
  /// ID for this commit; only written starting with Lucene 5.0.
  id: Option<[u8; StringHelper::ID_LENGTH]>,
  /// Which Lucene version wrote this commit?
  lucene_version: Option<Version>,
  /// Version of the oldest segment in the index, or `None` if there are no
  /// segments.
  min_segment_lucene_version: Option<Version>,
  /// The Lucene version major that was used to create the index.
  index_created_version_major: i32,
  // Only true after prepareCommit has been called and
  // before finishCommit is called
  pub(crate) pending_commit: bool,
}

impl<D> SegmentInfos<D> {
  /// Creates a new instance.
  ///
  /// # Arguments
  /// - `index_created_version_major`: The Lucene version major at index
  ///   creation time, or 6 if the index was created before 7.0.
  pub fn new(index_created_version_major: i32) -> Result<SegmentInfos<D>> {
    if index_created_version_major > LATEST.major {
      return Err(LuceneError::illegal_argument(format!(
        "indexCreatedVersionMajor is in the future: {index_created_version_major}"
      )));
    }
    if index_created_version_major < 6 {
      return Err(LuceneError::illegal_argument(format!(
        "indexCreatedVersionMajor must be >= 6, got: {index_created_version_major}"
      )));
    }

    Ok(SegmentInfos {
      counter: 0,
      version: 0,
      generation: 0,
      last_generation: 0,
      user_data: HashMap::new(),
      segments: Vec::new(),
      dropped_segment_commit_infos: HashMap::new(),
      id: None,
      lucene_version: None,
      min_segment_lucene_version: None,
      index_created_version_major,
      pending_commit: false,
    })
  }
  /// Returns [`SegmentCommitInfo`] at the provided index.
  /// Returns the [`SegmentCommitInfo`] for the given ID, looking in live
  /// segments first and then in segments retained after being dropped.
  pub fn index_of(&self, seg_id: &str) -> Option<&SegmentCommitInfo<D>> {
    self
      .segments
      .iter()
      .find(|sci| sci.info.get_id_key() == seg_id)
      .or_else(|| self.dropped_segment_commit_infos.get(seg_id))
  }

  /// Returns the live [`SegmentCommitInfo`](crate::core::index::segment_commit_info::SegmentCommitInfo) for the given ID.
  pub(crate) fn index_of_live(&self, seg_id: &str) -> Option<&SegmentCommitInfo<D>> {
    self
      .segments
      .iter()
      .find(|sci| sci.info.get_id_key() == seg_id)
  }
  pub fn info(&self, i: usize) -> Option<&SegmentCommitInfo<D>> {
    self.segments.get(i)
  }
  #[cfg(test)]
  pub fn info_idx_mut(&mut self, i: usize) -> Option<&mut SegmentCommitInfo<D>> {
    self.segments.get_mut(i)
  }
  /// Returns the mutable [`SegmentCommitInfo`] for the given ID, looking in live
  /// segments first and then in segments retained after being dropped.
  pub fn index_of_mut(&mut self, seg_id: &str) -> Option<&mut SegmentCommitInfo<D>> {
    if let Some(index) = self
      .segments
      .iter()
      .position(|sci| sci.info.get_id_key() == seg_id)
    {
      return self.segments.get_mut(index);
    }
    self.dropped_segment_commit_infos.get_mut(seg_id)
  }

  /// Get the segments_N filename in use by this segment infos.
  pub fn get_segments_file_name(&self) -> Option<String> {
    IndexFileNames::file_name_from_generation(IndexFileNames::SEGMENTS, "", self.last_generation)
  }

  /// Returns the generation of the next pending `segments_N` that will be
  /// written.
  pub fn get_next_pending_generation(&self) -> i64 {
    if self.generation == -1 {
      1
    } else {
      self.generation + 1
    }
  }

  /// Since Lucene 5.0, every commit (`segments_N`) writes a unique id. This
  /// will return that id.
  pub fn get_id(&self) -> Option<&[u8; StringHelper::ID_LENGTH]> {
    self.id.as_ref()
  }
  /// Read a particular `segmentFileName`. This may return an error if a commit
  /// is in process.
  ///
  /// # Arguments
  ///
  /// - [`Directory`]: Directory containing the segment file.
  /// - `Segment_file_name`: The segment file to load.
  ///
  /// # Errors
  ///
  /// - Returns [`LuceneErrorKind::CorruptIndex`] if the index is corrupt.
  /// - Returns [`LuceneError`] for any low-level IO error.
  pub fn read_commit(directory: Arc<D>, segment_file_name: &str) -> Result<SegmentInfos<D>>
  where
    D: Directory,
  {
    Self::read_commit_with_file_min_version(directory, segment_file_name, *MIN_SUPPORTED_MAJOR)
  }

  /// Reads a particular `segmentFileName`, as long as the commits
  /// [`SegmentInfos::get_index_created_version_major`](SegmentInfos::get_index_created_version_major)
  /// is strictly greater than the provided minimum supported major version.
  ///
  /// If the commits version is older,
  /// [`LuceneErrorKind::IndexFormatTooOld`]
  /// will be returned.
  /// Note that this may return an `Err` if a commit is in process.
  pub fn read_commit_with_file_min_version(
    directory: Arc<D>,
    segment_file_name: &str,
    min_supported_major_version: i32,
  ) -> Result<SegmentInfos<D>>
  where
    D: Directory,
  {
    let generation = generation_from_segments_file_name(segment_file_name)?;
    let mut input = directory.open_checksum_input(segment_file_name)?;

    let read_result =
      std::panic::catch_unwind(std::panic::AssertUnwindSafe(
        || match SegmentInfos::read_commit_impl(
          directory.clone(),
          &mut input,
          generation,
          min_supported_major_version,
        ) {
          Err(error) => {
            let is_unexpected_file_read_error = match error.kind() {
              LuceneErrorKind::Eof(_) | LuceneErrorKind::NoSuchFile(_) => true,
              LuceneErrorKind::Io { source, .. } | LuceneErrorKind::IoWithPath { source, .. } => {
                matches!(
                  source.kind(),
                  ErrorKind::NotFound | ErrorKind::UnexpectedEof
                )
              },
              _ => false,
            };
            if is_unexpected_file_read_error {
              let mut corrupt_index_error = LuceneError::corrupt_index(format!(
                "Unexpected file read error while reading index. (resource={input})"
              ));
              corrupt_index_error.add_suppressed(error);
              Err(corrupt_index_error)
            } else {
              Err(error)
            }
          },
          result => result,
        },
      ));
    let close_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| input.close()));
    IOUtils::use_or_suppress_caught_result(read_result, close_result)
  }

  /// Read the commit from the provided [`ChecksumIndexInput`].
  pub fn read_commit_with_input<II>(
    directory: Arc<D>,
    input: &mut II,
    generation: i64,
  ) -> Result<Self>
  where
    D: Directory,
    II: ChecksumIndexInput,
  {
    Self::read_commit_impl(directory, input, generation, *MIN_SUPPORTED_MAJOR)
  }
  /// Read the commit from the provided [`ChecksumIndexInput`].
  pub fn read_commit_impl<II>(
    directory: Arc<D>,
    input: &mut II,
    generation: i64,
    min_supported_major_version: i32,
  ) -> Result<Self>
  where
    D: Directory,
    II: ChecksumIndexInput,
  {
    let mut format = -1;
    let read_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<Self> {
      // NOTE: as long as we want to return index_format_too_old (vs
      // corrupt_index), we need to read the magic ourselves.
      let magic = CodecUtil::read_be_int(input)?;
      if magic != CodecUtil::CODEC_MAGIC {
        return Err(LuceneError::index_format_too_old_with_version(
          input,
          magic,
          CodecUtil::CODEC_MAGIC,
          CodecUtil::CODEC_MAGIC,
        ));
      }
      format = CodecUtil::check_header_no_magic(input, "segments", VERSION_74, VERSION_CURRENT)?;

      // Read the ID
      let mut id = [0u8; StringHelper::ID_LENGTH];
      let id_len = id.len();
      debug_assert!(id_len <= i32::MAX as usize);
      input.read_bytes(&mut id, 0, id_len)?;
      CodecUtil::check_index_header_suffix(input, base36(generation, &mut [0; 14]))?;

      let lucene_version =
        Version::from_bits(input.read_vint()?, input.read_vint()?, input.read_vint()?)?;

      let index_created_version = input.read_vint()?;
      debug_assert!(index_created_version >= 0);
      if lucene_version.major < index_created_version {
        return Err(LuceneError::corrupt_index(format!(
          "Creation version [{index_created_version}] can't be greater than the version that wrote the segment infos: [{lucene_version}]"
        )));
      }

      if index_created_version < min_supported_major_version {
        let reason = format!(
          "This index was initially created with Lucene {}.x while the current version is {} and Lucene only supports reading {}",
          index_created_version,
          *LATEST,
          if min_supported_major_version == *MIN_SUPPORTED_MAJOR {
            "the current and previous major versions".to_string()
          } else {
            format!("from version {min_supported_major_version} upwards")
          }
        );
        return Err(LuceneError::index_format_too_old(input, reason));
      }

      let mut infos = Self::new(index_created_version)?;
      infos.id = Some(id);
      infos.generation = generation;
      infos.last_generation = generation;
      infos.lucene_version = Some(lucene_version);
      Self::parse_segment_infos(directory, input, &mut infos, format)?;
      Ok(infos)
    }));

    if format >= VERSION_74 {
      match read_result {
        Ok(Ok(infos)) => {
          CodecUtil::check_footer_with_error::<(), _>(input, None)?;
          Ok(infos)
        },
        read_result => {
          CodecUtil::check_footer_with_error(input, Some(read_result))?;
          Err(LuceneError::illegal_state(
            "footer check returned after a prior segment infos read failure",
          ))
        },
      }
    } else {
      IOUtils::rethrow_always(read_result)
    }
  }
  pub fn parse_segment_infos<DI>(
    directory: Arc<D>,
    input: &mut DI,
    infos: &mut SegmentInfos<D>,
    format: i32,
  ) -> Result<()>
  where
    D: Directory,
    DI: DataInput,
  {
    infos.version = CodecUtil::read_be_long(input)?;
    let counter_value = input.read_vlong()?;
    debug_assert!(counter_value >= 0);
    infos.counter = counter_value;

    let num_segments = CodecUtil::read_be_int(input)?;
    if num_segments < 0 {
      return Err(LuceneError::corrupt_index(format!(
        "Invalid segment count: {num_segments} (resource={input})"
      )));
    }

    if num_segments > 0 {
      // Read minSegmentLuceneVersion
      infos.min_segment_lucene_version = Some(Version::from_bits(
        input.read_vint()?,
        input.read_vint()?,
        input.read_vint()?,
      )?);
    }

    let mut total_docs = 0i64;
    let mut seg_name = String::new();

    for _ in 0..num_segments {
      match input.read_string()? {
        Cow::Borrowed(name) => name.clone_into(&mut seg_name),
        Cow::Owned(name) => seg_name = name,
      }
      let mut segment_id = [0u8; StringHelper::ID_LENGTH];
      let segment_id_len = segment_id.len();
      debug_assert!(segment_id_len <= i32::MAX as usize);
      input.read_bytes(&mut segment_id, 0, segment_id_len)?;
      let codec = Self::read_codec(input)?;
      let mut info = codec.segment_info_format().read(
        directory.clone(),
        &seg_name,
        &segment_id,
        IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?,
      )?;
      info.set_codec(codec)?;

      let max_doc = info.max_doc()?;
      total_docs += i64::from(max_doc);

      let del_gen = CodecUtil::read_be_long(input)?;
      let del_count = CodecUtil::read_be_int(input)?;
      if del_count < 0 || del_count > max_doc {
        return Err(LuceneError::corrupt_index(format!(
          "Invalid deletion count: {del_count} vs maxDoc={max_doc}, (resource={input})"
        )));
      }
      let field_infos_gen = CodecUtil::read_be_long(input)?;
      let dv_gen = CodecUtil::read_be_long(input)?;
      let soft_del_count = CodecUtil::read_be_int(input)?;
      if soft_del_count < 0 || soft_del_count > max_doc {
        return Err(LuceneError::corrupt_index(format!(
          "Invalid soft deletion count: {soft_del_count} vs maxDoc={max_doc}, (resource={input})"
        )));
      }

      let combined_del_count = soft_del_count.wrapping_add(del_count);
      if combined_del_count > max_doc {
        return Err(LuceneError::corrupt_index(format!(
          "Invalid combined deletion count: {} vs maxDoc={}, (resource={})",
          combined_del_count, max_doc, input
        )));
      }

      let sci_id = if format > VERSION_74 {
        match input.read_byte()? {
          1 => {
            let mut id = [0u8; StringHelper::ID_LENGTH];
            let id_len = id.len();
            debug_assert!(id_len <= i32::MAX as usize);
            input.read_bytes(&mut id, 0, id_len)?;
            Some(id)
          },
          0 => None,
          marker => {
            return Err(LuceneError::corrupt_index(format!(
              "Invalid SegmentCommitInfo ID marker: {marker}"
            )));
          },
        }
      } else {
        None
      };

      let info = Arc::new(info);
      let mut si_per_commit = SegmentCommitInfo::new(
        info,
        del_count,
        soft_del_count,
        del_gen,
        field_infos_gen,
        dv_gen,
        sci_id,
      );
      si_per_commit.set_owned_field_infos_files(input.read_set_of_strings()?);
      let num_dv_fields = CodecUtil::read_be_int(input)?;
      let dv_update_files = if num_dv_fields == 0 {
        HashMap::new()
      } else {
        // num_dv_fields comes from the input and may be corrupted.
        let mut map = HashMap::new();
        for _ in 0..num_dv_fields {
          map.insert(CodecUtil::read_be_int(input)?, input.read_set_of_strings()?);
        }
        map
      };
      si_per_commit.set_doc_values_updates_files(std::borrow::Cow::Owned(dv_update_files));
      let segment_index = infos.segments.len();
      infos.add(si_per_commit)?;

      let info = &infos.segments[segment_index].info;
      let segment_version = info.get_version_ref().ok_or_else(|| {
        LuceneError::corrupt_index(format!(
          "segment {} does not record a Lucene version (resource={})",
          info, input
        ))
      })?;
      let min_segment_lucene_version =
        infos.min_segment_lucene_version.as_ref().ok_or_else(|| {
          LuceneError::corrupt_index(format!(
            "segments file does not record minSegmentLuceneVersion (resource={input})"
          ))
        })?;
      if !segment_version.on_or_after(min_segment_lucene_version) {
        return Err(LuceneError::corrupt_index(format!(
          "segments file recorded minSegmentLuceneVersion={} but segment={} has older version={} (resource={})",
          min_segment_lucene_version, info, segment_version, input
        )));
      }

      if infos.index_created_version_major >= 7
        && segment_version.major < infos.index_created_version_major
      {
        return Err(LuceneError::corrupt_index(format!(
          "segments file recorded indexCreatedVersionMajor={} but segment={} has older version={} (resource={})",
          infos.index_created_version_major, info, segment_version, input
        )));
      }

      if infos.index_created_version_major >= 7 && info.get_min_version_ref().is_none() {
        return Err(LuceneError::corrupt_index(format!(
          "segments infos must record minVersion with indexCreatedVersionMajor={} (resource={})",
          infos.index_created_version_major, input
        )));
      }
    }
    infos.user_data = input.read_map_of_strings()?;
    // LUCENE-6299: check we are in bounds
    if total_docs > i64::from(get_actual_max_docs()) {
      return Err(LuceneError::corrupt_index(format!(
        "Too many documents: an index cannot exceed {} but readers have total maxDoc={}",
        get_actual_max_docs(),
        total_docs
      )));
    }
    Ok(())
  }

  pub fn read_codec<DI>(input: &mut DI) -> Result<Codecs>
  where
    DI: DataInput,
  {
    let name = input.read_string()?;
    match codec::for_name(&name) {
      Err(error)
        if matches!(error.kind(), LuceneErrorKind::IllegalArgument(_))
          && name.starts_with("Lucene") =>
      {
        Err(LuceneError::illegal_argument(format!(
          "Could not load codec '{name}'. Did you forget to add lucene-backward-codecs.jar?"
        )))
      },
      result => result,
    }
  }
  /// Find the latest commit (`segments_N` file) and load all
  /// [`SegmentCommitInfo`]s.
  pub fn read_latest_commit(directory: Arc<D>) -> Result<SegmentInfos<D>>
  where
    D: Directory,
  {
    Self::read_latest_commit_with_min_version(directory, *MIN_SUPPORTED_MAJOR)
  }

  /// Find the latest commit (`segments_N` file) with a minimum supported
  /// major version and load all [`SegmentCommitInfo`]s.
  pub fn read_latest_commit_with_min_version(
    directory: Arc<D>,
    min_supported_major_version: i32,
  ) -> Result<SegmentInfos<D>>
  where
    D: Directory,
  {
    let mut find_segments_file = FindSegmentsFileImpl {
      dir: directory,
      min_supported_major_version,
    };
    find_segments_file.run()
  }

  fn write_with_directory<D2>(&mut self, directory: &D2) -> Result<()>
  where
    D2: Directory,
  {
    let next_generation = self.get_next_pending_generation();
    let segment_file_name_wrap = IndexFileNames::file_name_from_generation(
      IndexFileNames::PENDING_SEGMENTS,
      "",
      next_generation,
    );
    let segment_file_name = segment_file_name_wrap.ok_or_else(|| {
      LuceneError::illegal_state(format!(
        "invalid pending segments generation: {next_generation}"
      ))
    })?;

    // Always advance the generation on writing
    self.generation = next_generation;

    let mut success = false;
    let mut segn_output = None;
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> {
      segn_output = Some(directory.create_output(
        &segment_file_name,
        IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?,
      )?);
      let segn_output = segn_output
        .as_mut()
        .ok_or_else(|| LuceneError::illegal_state("pending segments output is missing"))?;
      self.write(segn_output)?;
      segn_output.close()?;
      directory.sync(std::slice::from_ref(&segment_file_name))?;
      success = true;
      Ok(())
    }));
    if success {
      self.pending_commit = true;
    } else {
      // We hit an error above; try to close the file but suppress any non-tragic error.
      IOUtils::close_while_handling_exception(segn_output.as_mut());
      // Try not to leave a truncated segments_N file in the index.
      IOUtils::delete_files_ignoring_exceptions(directory, std::iter::once(&segment_file_name));
    }
    unwrap_caught_result!(result)
  }

  /// Write the current [`SegmentInfos`] to the provided [`IndexOutput`].
  ///
  /// # Errors
  ///
  /// Returns a [`LuceneError`] if there is an issue writing the segment
  /// information.
  pub fn write<IO>(&self, out: &mut IO) -> Result<()>
  where
    IO: IndexOutput,
  {
    let mut generation_digits = [0; 14];
    let v = base36(self.generation, &mut generation_digits);
    CodecUtil::write_index_header(
      out,
      "segments",
      VERSION_CURRENT,
      &StringHelper::random_id(),
      v,
    )?;
    out.write_vint(LATEST.major)?;
    out.write_vint(LATEST.minor)?;
    out.write_vint(LATEST.bug_fix)?;

    out.write_vint(self.index_created_version_major)?;
    CodecUtil::write_be_long(out, self.version)?;
    out.write_vlong(self.counter)?;
    CodecUtil::write_be_int(out, self.segments.len().try_convert()?)?;

    if self.size() > 0 {
      let mut min_segment_version: Option<&Version> = None;
      // We do a separate loop up front so we can write the
      // minSegmentVersion before any SegmentInfo; this makes
      // it cleaner to return IndexFormatTooOldExc at read time:
      for si_per_commit in self.segments.iter() {
        let segment_version = si_per_commit.info.version.as_ref().ok_or_else(|| {
          LuceneError::illegal_state(format!(
            "segment {} does not record a Lucene version",
            si_per_commit.info.name
          ))
        })?;
        if min_segment_version.is_none_or(|min_version| !segment_version.on_or_after(min_version)) {
          min_segment_version = Some(segment_version);
        }
      }

      let min_version = min_segment_version.ok_or_else(|| {
        LuceneError::illegal_state("cannot determine minimum segment Lucene version")
      })?;
      out.write_vint(min_version.major)?;
      out.write_vint(min_version.minor)?;
      out.write_vint(min_version.bug_fix)?;
    }
    for si_per_commit in self.segments.iter() {
      let si = &si_per_commit.info;
      if self.index_created_version_major >= 7 && si.min_version.is_none() {
        return Err(LuceneError::illegal_state(format!(
          "Segments must record minVersion if they have been created on or after Lucene 7: {}",
          si.name
        )));
      }
      out.write_string(&si.name)?;
      let segment_id = si.get_id();
      let segment_id_len = segment_id.len();
      if segment_id_len != StringHelper::ID_LENGTH {
        return Err(LuceneError::illegal_state(format!(
          "Cannot write segment: invalid id segment={} id={:?}",
          si.name, segment_id
        )));
      }
      debug_assert!(segment_id_len <= i32::MAX as usize);
      out.write_bytes_with_len(segment_id, segment_id_len)?;
      out.write_string(si.get_codec()?.get_name())?;

      CodecUtil::write_be_long(out, si_per_commit.get_del_gen())?;
      let del_count = si_per_commit.get_del_count();
      let max_doc = si.max_doc()?;
      if del_count < 0 || del_count > max_doc {
        return Err(LuceneError::illegal_state(format!(
          "Cannot write segment: invalid maxDoc segment={} maxDoc={} delCount={}",
          si.name, max_doc, del_count
        )));
      }
      CodecUtil::write_be_int(out, del_count)?;
      CodecUtil::write_be_long(out, si_per_commit.get_field_infos_gen())?;
      CodecUtil::write_be_long(out, si_per_commit.get_doc_values_gen())?;

      let soft_del_count = si_per_commit.get_soft_del_count();
      if soft_del_count < 0 || soft_del_count > max_doc {
        return Err(LuceneError::illegal_state(format!(
          "Cannot write segment: invalid maxDoc segment={} maxDoc={} softDelCount={}",
          si.name, max_doc, soft_del_count
        )));
      }
      CodecUtil::write_be_int(out, soft_del_count)?;

      if let Some(sci_id) = si_per_commit.get_id() {
        out.write_byte(1)?;
        let sci_id_len = sci_id.len();
        debug_assert_eq!(
          sci_id_len,
          StringHelper::ID_LENGTH,
          "Invalid SegmentCommitInfo#id: {sci_id:?}"
        );
        debug_assert!(sci_id_len <= i32::MAX as usize);
        out.write_bytes_range(sci_id, 0, sci_id_len)?;
      } else {
        out.write_byte(0)?;
      }

      out.write_set_of_strings(si_per_commit.get_field_infos_files())?;

      let dv_updates_files = si_per_commit.get_doc_values_updates_files();
      let dv_updates_files_len = dv_updates_files.len();
      CodecUtil::write_be_int(out, dv_updates_files_len.try_convert()?)?;
      for (key, value) in dv_updates_files {
        CodecUtil::write_be_int(out, *key)?;
        out.write_set_of_strings(value)?;
      }
    }
    out.write_map_of_strings(&self.user_data)?;
    CodecUtil::write_footer(out)?;

    Ok(())
  }

  pub fn try_clone(&self) -> Result<Self> {
    let mut cloned = Self {
      counter: self.counter,
      version: self.version,
      generation: self.generation,
      last_generation: self.last_generation,
      user_data: self.user_data.clone(),
      segments: Vec::with_capacity(self.segments.len()),
      dropped_segment_commit_infos: self.dropped_segment_commit_infos.clone(),
      id: self.id,
      lucene_version: self.lucene_version.clone(),
      min_segment_lucene_version: self.min_segment_lucene_version.clone(),
      index_created_version_major: self.index_created_version_major,
      pending_commit: self.pending_commit,
    };

    for segment_commit_info in self.segments.iter() {
      // debug_assert!(segment_commit_info.info.codec.is_some());
      cloned.add(segment_commit_info.clone())?;
    }
    Ok(cloned)
  }
  /// Returns the version number when this [`SegmentInfos`] was generated.
  pub fn get_version(&self) -> i64 {
    self.version
  }

  /// Returns the current generation.
  pub fn get_generation(&self) -> i64 {
    self.generation
  }

  /// Returns the last successfully read or written generation.
  pub fn get_last_generation(&self) -> i64 {
    self.last_generation
  }
  /// Carry over generation numbers from another [`SegmentInfos`].
  pub fn update_generation<D1>(&mut self, other: &SegmentInfos<D1>) {
    self.last_generation = other.last_generation;
    self.generation = other.generation;
  }

  /// Carry over generation numbers, and version/counter, from another
  /// [`SegmentInfos`].
  pub fn update_generation_version_and_counter<D1>(&mut self, other: &SegmentInfos<D1>) {
    self.update_generation(other);
    self.version = other.version;
    self.counter = other.counter;
  }

  /// Set the generation to be used for the next commit.
  pub fn set_next_write_generation(&mut self, generation: i64) -> Result<()> {
    if generation < self.generation {
      return Err(LuceneError::illegal_state(format!(
        "Cannot decrease generation to {} from current generation {}",
        generation, self.generation
      )));
    }
    self.generation = generation;
    Ok(())
  }

  /// Rollback a pending commit.
  pub fn rollback_commit<D2>(&mut self, directory: &D2)
  where
    D2: Directory,
  {
    if self.pending_commit {
      self.pending_commit = false;

      // We try to clean up our pending_segments_N

      // Must carefully compute fileName from "generation"
      // since lastGeneration isn't incremented:
      if let Some(pending) = IndexFileNames::file_name_from_generation(
        IndexFileNames::PENDING_SEGMENTS,
        "",
        self.generation,
      ) {
        // Suppress, so we keep returning the original error in our
        // caller
        IOUtils::delete_files_ignoring_exceptions(directory, std::iter::once(&pending));
      }
    }
  }
  /// Call this to start a commit. This writes the new segments file, but
  /// writes an invalid checksum at the end, so that it is not visible to
  /// readers. Once this is called, you must call
  /// [`finish_commit`](SegmentInfos::finish_commit) to complete the
  /// commit or [`rollback_commit`](SegmentInfos::rollback_commit) to abort
  /// it.
  ///
  /// Note: [`changed()`](SegmentInfos::changed) should be called prior to
  /// this method if changes have been made to this [`SegmentInfos`] instance.
  pub fn prepare_commit<D2>(&mut self, directory: &D2) -> Result<()>
  where
    D2: Directory,
  {
    #[cfg(test)]
    let _execution_scope =
      ExecutionScope::enter(ExecutionOwner::SegmentInfos, ExecutionMethod::PrepareCommit);
    if self.pending_commit {
      return Err(LuceneError::illegal_state(
        "prepare_commit was already called",
      ));
    }
    directory.sync_metadata()?;
    self.write_with_directory(directory)?;
    Ok(())
  }

  /// Returns all file names referenced by [`SegmentInfo`](crate::core::index::segment_info::SegmentInfo). The returned
  /// collection is recomputed on each invocation.
  pub fn files(&self, include_segments_file: bool) -> Result<HashSet<String>> {
    let size = self.size();
    if size == 1 && !include_segments_file {
      return self
        .info(0)
        .ok_or_else(|| LuceneError::illegal_state("segment was None"))?
        .files();
    }
    let mut files = HashSet::with_capacity(size + usize::from(include_segments_file));
    if include_segments_file && let Some(segment_file_name) = self.get_segments_file_name() {
      files.insert(segment_file_name);
    }
    for i in 0..size {
      let segment_commit_info = self
        .info(i)
        .ok_or_else(|| LuceneError::illegal_state("segment was None"))?;
      segment_commit_info.append_files_to(&mut files)?;
    }
    Ok(files)
  }
  pub(crate) fn files_for_read(
    &self,
    include_segments_file: bool,
  ) -> Result<Cow<'_, HashSet<String>>> {
    if !include_segments_file && let [info] = self.segments.as_slice() {
      info.files_for_read()
    } else {
      self.files(include_segments_file).map(Cow::Owned)
    }
  }

  pub(crate) fn files_to_sync(&self) -> Result<Vec<String>> {
    Ok(match self.files_for_read(false)? {
      Cow::Borrowed(files) => files.iter().cloned().collect(),
      Cow::Owned(files) => files.into_iter().collect(),
    })
  }

  /// Returns the committed `segments_N` filename.
  pub fn finish_commit<D2>(&mut self, directory: &D2) -> Result<String>
  where
    D2: Directory,
  {
    #[cfg(test)]
    let _execution_scope =
      ExecutionScope::enter(ExecutionOwner::SegmentInfos, ExecutionMethod::FinishCommit);
    if !self.pending_commit {
      return Err(LuceneError::illegal_state("prepare_commit was not called"));
    }

    let mut success_rename_and_sync = false;

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<String> {
      let src = IndexFileNames::file_name_from_generation(
        IndexFileNames::PENDING_SEGMENTS,
        "",
        self.generation,
      )
      .ok_or_else(|| LuceneError::illegal_state("Failed to generate source file name."))?;
      let dest =
        IndexFileNames::file_name_from_generation(IndexFileNames::SEGMENTS, "", self.generation)
          .ok_or_else(|| LuceneError::illegal_state("Failed to generate destination file name."))?;
      directory.rename(&src, &dest)?;

      let sync_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> {
        directory.sync_metadata()?;
        success_rename_and_sync = true;
        Ok(())
      }));
      if !success_rename_and_sync {
        // at this point we already created the file but missed to sync directory let's also
        // remove the
        // renamed file
        IOUtils::delete_files_ignoring_exceptions(directory, std::iter::once(&dest));
      }
      unwrap_caught_result!(sync_result)?;
      Ok(dest)
    }));

    if !success_rename_and_sync {
      // deletes pending_segments_N:
      self.rollback_commit(directory);
    }
    let dest = unwrap_caught_result!(result)?;
    self.pending_commit = false;
    self.last_generation = self.generation;
    Ok(dest)
  }
  /// Writes and syncs to the Directory, taking care to remove the segment
  /// file on error.
  ///
  /// Note: [`changed()`](SegmentInfos::changed) should be called prior to
  /// this method if changes have been made to this [`SegmentInfos`] instance.
  pub fn commit<D2>(&mut self, dir: &D2) -> Result<()>
  where
    D2: Directory,
  {
    self.prepare_commit(dir)?;
    self.finish_commit(dir)?;
    Ok(())
  }
  /// Returns `user_data` saved with this commit.
  pub fn get_user_data(&self) -> &HashMap<String, String> {
    &self.user_data
  }

  /// Sets the commit data.
  pub fn set_user_data(
    &mut self,
    data: Option<HashMap<String, String>>,
    do_increment_version: bool,
  ) {
    if let Some(new_data) = data {
      self.user_data = new_data;
    } else {
      self.user_data = HashMap::new();
    }

    if do_increment_version {
      self.changed();
    }
  }

  /// Replaces all segments in this instance, but keeps generation, version,
  /// counter so that future commits remain write-once.
  pub fn replace(&mut self, other: Self) -> Result<()> {
    self.rollback_segment_infos(other.segments)?;
    self.last_generation = other.last_generation;
    self.user_data = other.user_data;
    Ok(())
  }

  /// Returns the sum of all segment's `max_docs`. Note that this does not
  /// include deletions.
  pub fn total_max_doc(&self) -> Result<i32> {
    let mut count = 0i64;
    for segment_commit_info in self.segments.iter() {
      count += i64::from(segment_commit_info.info.max_doc()?);
    }

    // Ensure we don't exceed the actual max document limit.
    debug_assert!(count <= i64::from(get_actual_max_docs()));
    count.try_convert()
  }
  /// Call this before committing if changes have been made to the segments.
  pub fn changed(&mut self) {
    self.version += 1;
  }

  /// Set the version to a new value. The new version must be greater than or
  /// equal to the current version.
  pub fn set_version(&mut self, new_version: i64) -> Result<()> {
    if new_version < self.version {
      return Err(LuceneError::illegal_argument(format!(
        "newVersion (={}) cannot be less than current version (={})",
        new_version, self.version
      )));
    }
    self.version = new_version;
    Ok(())
  }
  /// Applies all changes caused by committing a merge to this [`SegmentInfos`](crate::core::index::segment_infos::SegmentInfos)
  pub(crate) fn apply_merge_changes(
    &mut self,
    source_ids: &[Arc<str>],
    merge_info: &mut Option<SegmentCommitInfo<D>>,
    drop_segment: bool,
  ) -> Result<()> {
    if self.index_created_version_major >= 7
      && merge_info
        .as_ref()
        .and_then(|sci| sci.info.get_min_version())
        .is_none()
    {
      return Err(LuceneError::illegal_argument(
        "All segments must record the minVersion for indices created on or after Lucene 7",
      ));
    }
    let merged_away = (source_ids.len() > 4).then(|| {
      source_ids
        .iter()
        .map(AsRef::as_ref)
        .collect::<HashSet<&str>>()
    });

    let mut kept = 0;
    let mut insertion_index = None;
    let removed = self.segments.extract_if(.., |info| {
      let info_id = info.info.get_id_key();
      let is_source = match &merged_away {
        Some(ids) => ids.contains(info_id),
        None => source_ids.iter().any(|id| id.as_ref() == info_id),
      };
      if is_source {
        insertion_index.get_or_insert(kept);
      } else {
        kept += 1;
      }
      is_source
    });

    let mut output = None;
    for info in removed {
      self
        .dropped_segment_commit_infos
        .insert(Arc::clone(&info.info.id_key), info);
      if !drop_segment && output.is_none() {
        output = merge_info.take();
        if output.is_none() {
          break;
        }
      }
    }

    if !drop_segment {
      let Some(output) = output.or_else(|| merge_info.take()) else {
        self.segments.clear();
        return Err(LuceneError::illegal_state(
          "merge output segment info is missing",
        ));
      };
      self.segments.insert(insertion_index.unwrap_or(0), output);
    }

    Ok(())
  }

  pub fn create_backup_segment_infos(&self) -> Result<Vec<SegmentCommitInfo<D>>> {
    let mut list = Vec::with_capacity(self.segments.len());
    for segment_commit_info in self.segments.iter() {
      list.push(segment_commit_info.clone());
    }
    Ok(list)
  }

  pub fn rollback_segment_infos(&mut self, mut infos: Vec<SegmentCommitInfo<D>>) -> Result<()> {
    self.clear();
    if self.index_created_version_major >= 7
      && let Some(index) = infos
        .iter()
        .position(|info| info.info.min_version.is_none())
    {
      let error = Self::missing_min_version(&infos[index]);
      infos.truncate(index);
      self.segments = infos;
      return Err(error);
    }
    self.segments = infos;
    Ok(())
  }
  pub fn iter_mut(&mut self) -> &mut [SegmentCommitInfo<D>] {
    self.segments.as_mut_slice()
  }
  /// Returns all contained segments as a non-mutable reference to the
  /// internal vector.
  pub fn iter(&self) -> &[SegmentCommitInfo<D>] {
    self.segments.as_slice()
  }

  /// Returns the number of [`SegmentCommitInfo`]s.
  pub fn size(&self) -> usize {
    self.segments.len()
  }

  /// Appends the provided [`SegmentCommitInfo`] to the `segments` list.
  pub fn add(&mut self, si: SegmentCommitInfo<D>) -> Result<()> {
    if self.index_created_version_major >= 7 && si.info.min_version.is_none() {
      return Err(Self::missing_min_version(&si));
    }
    let _id = si.info.get_id_key();
    self.segments.push(si);
    Ok(())
  }

  fn missing_min_version(info: &SegmentCommitInfo<D>) -> LuceneError {
    LuceneError::illegal_argument(format!(
      "All segments must record the minVersion for indices created on or after Lucene 7, but minVersion is missing for segment: {info}"
    ))
  }

  /// Appends the provided [`SegmentCommitInfo`]s.
  pub fn add_all<I>(&mut self, sis: I) -> Result<()>
  where
    I: IntoIterator<Item = SegmentCommitInfo<D>>,
  {
    let sis = sis.into_iter();
    self.segments.reserve(sis.size_hint().0);
    for si in sis {
      self.add(si)?;
    }
    Ok(())
  }

  /// Clears all [`SegmentCommitInfo`]s.
  pub fn clear(&mut self) {
    self
      .dropped_segment_commit_infos
      .reserve(self.segments.len());
    for info in self.segments.drain(..) {
      self
        .dropped_segment_commit_infos
        .insert(Arc::clone(&info.info.id_key), info);
    }
  }

  /// Removes the provided [`SegmentCommitInfo`].
  ///
  /// Returns `true` if the segment was present and removed.
  pub fn remove_with_id(&mut self, si_id: &str) -> bool {
    let Some(idx) = self
      .segments
      .iter()
      .position(|sci| sci.info.get_id_key() == si_id)
    else {
      return false;
    };
    let info = self.segments.remove(idx);
    self
      .dropped_segment_commit_infos
      .insert(Arc::clone(&info.info.id_key), info);
    true
  }

  /// Removes the [`SegmentCommitInfo`] at the provided index.
  pub fn remove(&mut self, index: usize) {
    if index >= self.segments.len() {
      return;
    }
    let info = self.segments.remove(index);
    self
      .dropped_segment_commit_infos
      .insert(Arc::clone(&info.info.id_key), info);
  }

  pub(crate) fn remove_dropped_segment_commit_info(
    &mut self,
    si_id: &str,
  ) -> Option<SegmentCommitInfo<D>> {
    self.dropped_segment_commit_infos.remove(si_id)
  }

  /// Returns true if the provided [`SegmentCommitInfo`] is contained.
  pub fn contains(&self, si_id: &str) -> bool {
    self.index_of_live(si_id).is_some()
  }

  /// Returns the [`Version`] of the Lucene commit.
  pub fn get_commit_lucene_version(&self) -> Option<&Version> {
    self.lucene_version.as_ref()
  }

  /// Returns the [`Version`] of the oldest segment, or `None` if there are no
  /// segments.
  pub fn get_min_segment_lucene_version(&self) -> Option<&Version> {
    self.min_segment_lucene_version.as_ref()
  }

  /// Returns the version major that was used to initially create the index.
  /// This version is set when the index is first created and then never
  /// changes. Older indices report 6 as the creation version.
  pub fn get_index_created_version_major(&self) -> i32 {
    self.index_created_version_major
  }

  pub fn seg_ids(&self) -> Vec<String> {
    self
      .segments
      .iter()
      .map(|s| s.info.get_id_key().to_string())
      .collect()
  }
}

impl<D> fmt::Display for SegmentInfos<D> {
  /// Returns a readable description of this segment.
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
      "{}: ",
      self
        .get_segments_file_name()
        .unwrap_or_else(|| "null".to_string())
    )?;
    for (i, segment_commit_info) in self.segments.iter().enumerate() {
      if i > 0 {
        write!(f, " ")?;
      }
      write!(f, "{segment_commit_info}")?
    }
    Ok(())
  }
}

pub trait FindSegmentsFile {
  type V;
  type D: Directory;
  fn get_directory_point(&self) -> Arc<Self::D>;
  /// Run doBody on the provided commit.
  fn run_with_commit<T>(&mut self, commit: &T) -> Result<Self::V>
  where
    T: IndexCommit<Directory = Arc<Self::D>>,
  {
    if !self
      .get_directory_point()
      .is_same_identity(&*commit.get_directory())
    {
      return Err(LuceneError::io(Error::other(
        "the specified commit does not match the specified Directory",
      )));
    }
    self.do_body(commit.get_segments_file_name())
  }
  /// Locate the most recent segments file and run doBody on it.
  fn run(&mut self) -> Result<Self::V> {
    let mut last_gen: i64;
    let mut gen_: i64 = -1;
    let mut exc: Option<LuceneError> = None;
    // Loop until we succeed in calling doBody() without
    // hitting an I/O error. An I/O error most likely
    // means an IW deleted our commit while opening
    // the time it took us to load the now-old infos files
    // (and segments files).  It's also possible it's a
    // true error (corrupt index).  To distinguish these,
    // on each retry we must see "forward progress" on
    // which generation we are trying to load.  If we
    // don't, then the original error is real and we return
    // it.
    let directory = self.get_directory_point();
    loop {
      last_gen = gen_;
      let mut files = directory.list_all()?;
      let mut files2 = directory.list_all()?;
      files.sort_unstable();
      files2.sort_unstable();
      if files != files2 {
        continue;
      }
      gen_ = get_last_commit_generation(&files)?;
      if get_info_stream().is_some() {
        message(&format!("directory listing gen={gen_}"))?;
      }
      if gen_ == -1 {
        return Err(LuceneError::index_not_found(format!(
          "No segments* file found in the {}: files: {:?}",
          directory, files
        )));
      } else if gen_ > last_gen {
        let segment_file_name =
          IndexFileNames::file_name_from_generation(IndexFileNames::SEGMENTS, "", gen_)
            .ok_or_else(|| LuceneError::illegal_state("Failed to generate segment file name."))?;
        match self.do_body(&segment_file_name) {
          Ok(result) => {
            if get_info_stream().is_some() {
              message(&format!("success on {segment_file_name}"))?;
            }
            return Ok(result);
          },
          Err(err) if err.is_io_error() => {
            let error_message = err.to_string();
            if exc.is_none() {
              exc = Some(err);
            }

            if get_info_stream().is_some() {
              message(&format!(
                "primary error on '{}': {}; will retry: gen = {}",
                segment_file_name, error_message, gen_
              ))?;
            }
          },
          Err(err) => return Err(err),
        }
      } else {
        return Err(exc.unwrap_or_else(|| {
          LuceneError::illegal_state("Unexpected error during FindSegmentsFile::run")
        }));
      }
    }
  }
  /// Sub struct must implement this.
  /// The assumption is an error will be returned if something goes wrong during the processing that could have been caused by a writer committing.
  fn do_body(&mut self, segment_file_name: &str) -> Result<Self::V>;
}

pub struct FindSegmentsFileImpl<D> {
  pub(crate) dir: Arc<D>,
  pub(crate) min_supported_major_version: i32,
}
impl<D> FindSegmentsFile for FindSegmentsFileImpl<D>
where
  D: Directory,
{
  type V = SegmentInfos<D>;
  type D = D;

  fn get_directory_point(&self) -> Arc<Self::D> {
    self.dir.clone()
  }

  fn do_body(&mut self, segment_file_name: &str) -> Result<Self::V> {
    SegmentInfos::read_commit_with_file_min_version(
      self.dir.clone(),
      segment_file_name,
      self.min_supported_major_version,
    )
  }
}

/// The version at the time when 8.0 was released.
pub const VERSION_74: i32 = 9;
/// The version that recorded SegmentCommitInfo IDs.
pub const VERSION_86: i32 = 10;
/// Current version of SegmentInfos.
pub(crate) const VERSION_CURRENT: i32 = VERSION_86;
/// Name of the generation reference file name.
pub(crate) const OLD_SEGMENTS_GEN: &str = "segments.gen";
/// Sets the global INFO_STREAM to the given optional [`OutputEnum`].
pub fn set_info_stream<T>(output: T) -> Result<()>
where
  T: Into<Option<OutputEnum>>,
{
  let mut info_stream = INFO_STREAM.lock();
  *info_stream = output.into();
  Ok(())
}

/// Returns the current global INFO_STREAM under its synchronization guard.
pub fn get_info_stream() -> parking_lot::MutexGuard<'static, Option<OutputEnum>> {
  INFO_STREAM.lock()
}

/// Prints a message to the INFO_STREAM if it is set.
/// This function assumes the caller has checked whether INFO_STREAM is `Some`.
pub fn message(msg: &str) -> Result<()> {
  let mut info_stream = INFO_STREAM.lock();

  if let Some(stream) = info_stream.as_mut() {
    let current_thread = std::thread::current();
    let thread_name = current_thread.name().unwrap_or("unnamed");
    let _ = writeln!(stream, "SIS [{thread_name}]: {msg}");
  }

  Ok(())
}
/// Get the generation of the most recent commit to the list of index files (N
/// in the segments_N file).
///
/// # Arguments
/// - `files`: A slice of file names to check.
pub fn get_last_commit_generation(files: &[String]) -> Result<i64> {
  let mut max = -1;
  for file in files {
    if file.starts_with(IndexFileNames::SEGMENTS)
                // skipping this file here helps deliver the right error when opening an old index
                && !file.starts_with(OLD_SEGMENTS_GEN)
    {
      let gen_ = generation_from_segments_file_name(file)?;
      if gen_ > max {
        max = gen_;
      }
    }
  }
  Ok(max)
}

/// Get the generation of the most recent commit to the index in this directory.
pub fn get_last_commit_generation_from_directory<D>(directory: &D) -> Result<i64>
where
  D: Directory,
{
  let files = directory.list_all()?;
  get_last_commit_generation(&files)
}

/// Get the filename of the segments_N file for the most recent commit in the
/// list of index files.
pub fn get_last_commit_segments_file_name(files: &[String]) -> Result<Option<String>> {
  let last_gen = get_last_commit_generation(files)?;
  Ok(IndexFileNames::file_name_from_generation(
    IndexFileNames::SEGMENTS,
    "",
    last_gen,
  ))
}

/// Get the filename of the segments_N file for the most recent commit to the
/// index in this Directory.
pub fn get_last_commit_segments_file_name_from_directory<D>(directory: &D) -> Result<Option<String>>
where
  D: Directory,
{
  let last_gen = get_last_commit_generation_from_directory(directory)?;
  Ok(IndexFileNames::file_name_from_generation(
    IndexFileNames::SEGMENTS,
    "",
    last_gen,
  ))
}
/// Parse the generation off the segment file name and return it.
pub fn generation_from_segments_file_name(file_name: &str) -> Result<i64> {
  if file_name == OLD_SEGMENTS_GEN {
    Err(LuceneError::illegal_argument(format!(
      "\"{}\" is not a valid segment file name since 4.0",
      OLD_SEGMENTS_GEN
    )))
  } else if file_name == IndexFileNames::SEGMENTS {
    Ok(0)
  } else if file_name.starts_with(IndexFileNames::SEGMENTS) {
    let generation_str = &file_name[IndexFileNames::SEGMENTS.len() + 1..];
    match i64::from_str_radix(generation_str, 36) {
      Ok(generation) => Ok(generation),
      Err(_) => Err(LuceneError::number_format(format!(
        "Failed to parse generation from file name: \"{file_name}\""
      ))),
    }
  } else {
    Err(LuceneError::illegal_argument(format!(
      "fileName \"{file_name}\" is not a segments file"
    )))
  }
}