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
/*
 * 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::sync::{Arc, LazyLock};

use crate::core::index::{BytesRef, BytesRefBuilder};
use crate::core::util::access::ByteSource;
use crate::core::util::accountable::Accountable;
use crate::core::util::array_util::ArrayUtil;
use crate::core::util::bit_util::BitUtil;
use crate::core::util::bytes_ref_block_pool::{BytesRefBlockPool, BytesRefBlockPoolPosition};
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::most_significant_bit_radix_sort::LENGTH_THRESHOLD;
use crate::core::util::ram_usage_estimator::size_of_vec;
use crate::core::util::{
  AtomicCounter, ByteBlockPool, BytesRefComparator, Counter, GOOD_FAST_HASH_SEED, HISTOGRAM_SIZE,
  LEVEL_THRESHOLD, MSBRadixSorter, MSBRadixSorterBase, Natural, SharedCounter, Sorter,
  StringHelper, StringSorter, StringSorterBase,
};

/// [`BytesRefHash`] is a special purpose hash-map like data structure optimized
/// for [`BytesRef`] instances. [`BytesRefHash`] maintains mappings of byte arrays
/// to `i32` IDs, storing the hashed bytes efficiently in
/// continuous storage. The mapping to the ID is encapsulated inside
/// [`BytesRefHash`] and is guaranteed to be increased for each added [`BytesRef`].
///
/// # Note
/// - The maximum capacity [`BytesRef`] instance passed to
///   [`add`](BytesRefHash::add) must not be longer than
///   [`BYTE_BLOCK_SIZE`](crate::core::util::byte_block_pool::BYTE_BLOCK_SIZE) - 2.
/// - The internal storage is limited to 2GB total byte storage.
///
pub struct BytesRefHash<BSA> {
  pool: BytesRefBlockPool,
  hash_mask: usize,
  pub(crate) count: usize,
  pub ids: Vec<i32>,
  pub(crate) bytes_start_array: BSA,
  bytes_used: SharedCounter,
}
impl BytesRefHash<DirectBytesStartArray> {
  pub fn new() -> Result<Self> {
    let bytes_start_array = DirectBytesStartArray::new(DEFAULT_CAPACITY);
    BytesRefHash::from_bytes_start_array(16, bytes_start_array)
  }
}
// The process-wide hash seed never changes. Cache the same MurmurHash values
// for every possible one-byte key without adding state to individual hashes.
static SINGLE_BYTE_HASHES: LazyLock<[i32; 256]> = LazyLock::new(|| {
  let seed = *GOOD_FAST_HASH_SEED;
  std::array::from_fn(|byte| StringHelper::murmurhash3_x86_32_with_byte(&[byte as u8], 0, 1, seed))
});

pub fn do_hash(bytes: &[u8], offset: usize, length: usize) -> i32 {
  if length == 1 {
    SINGLE_BYTE_HASHES[bytes[offset] as usize]
  } else {
    StringHelper::murmurhash3_x86_32_with_byte(bytes, offset, length, *GOOD_FAST_HASH_SEED)
  }
}
impl<BSA> BytesRefHash<BSA>
where
  BSA: BytesStartArray,
{
  pub fn from_bytes_start_array(capacity: usize, mut bytes_start_array: BSA) -> Result<Self> {
    bytes_start_array.init()?;
    let mut hash = Self::without_storage(capacity, bytes_start_array);
    hash.ids = vec![-1; capacity];
    hash.bytes_used.add_and_get(size_of_vec(&hash.ids));
    Ok(hash)
  }

  pub(crate) fn without_storage(capacity: usize, mut bytes_start_array: BSA) -> Self {
    let bytes_used = bytes_start_array.bytes_used();
    Self {
      pool: BytesRefBlockPool::new(),
      hash_mask: capacity - 1,
      count: 0,
      ids: Vec::new(),
      bytes_start_array,
      bytes_used,
    }
  }
  /// Returns the number of [`BytesRef`] values in this [`BytesRefHash`].
  ///
  /// # Returns
  /// The number of [`BytesRef`] values in this [`BytesRefHash`].
  pub fn size(&self) -> usize {
    self.count
  }
  /// Returns the pool position of the bytes for the given `bytes_id` without
  /// copying them.
  ///
  /// # Note
  /// The given `bytes_id` must be a non-negative integer less than the current
  /// size (`size()`).
  ///
  /// # Arguments
  /// - `bytes_id`: The ID.
  /// - `pool`: The same byte pool used to add the value.
  ///
  /// # Returns
  /// A position in `pool`. Borrow its bytes while reading, or copy them when
  /// independent ownership is needed. The position does not keep the pool alive
  /// and must not be reused after its contents are reset or changed.
  pub fn get(&self, bytes_id: i32, pool: &ByteBlockPool) -> Result<BytesRefBlockPoolPosition> {
    debug_assert!(
      !self.bytes_start_array.need_init(),
      "bytes_start is null - not initialized"
    );
    let bytes_start_len = self.bytes_start_array.len()?;
    let bytes_id = bytes_id as usize;
    debug_assert!(
      bytes_id < bytes_start_len,
      "bytesID exceeds bytes_start len"
    );
    let value = self.bytes_start_array.get_value(bytes_id)?;
    Ok(self.pool.fill_bytes_ref(value, pool))
  }

  /// Returns the id array in arbitrary order. Valid ids start at offset 0 and
  /// end at a limit of `size()` - 1.
  ///
  /// # Note
  /// This is a destructive operation. `Clear()` must be called to reuse this
  /// [`BytesRefHash`] instance.
  pub fn compact(&mut self) -> Result<&Vec<i32>> {
    debug_assert!(
      !self.bytes_start_array.need_init(),
      "bytes_start is null - not initialized"
    );

    let hash_size = self.hash_mask.wrapping_add(1);
    let mut upto = 0;
    if let Some(ids) = self.ids.get_mut(..hash_size) {
      for i in 0..ids.len() {
        if ids[i] != -1 {
          if upto < i {
            ids[upto] = ids[i];
            ids[i] = -1;
          }
          upto += 1;
        }
      }
    } else {
      for i in 0..hash_size {
        if self.ids[i] != -1 {
          if upto < i {
            self.ids[upto] = self.ids[i];
            self.ids[i] = -1;
          }
          upto += 1;
        }
      }
    }
    debug_assert!(upto == self.count);

    Ok(&self.ids)
  }
  /// Returns the values array sorted by the referenced byte values.
  pub fn sort(&mut self, byte_block_pool: &ByteBlockPool) -> Result<()> {
    let compact = self.compact()?;
    let mut length = compact.len();
    debug_assert!(
      self.count * 2 <= length,
      "We need load factor <= 0.5f to speed up this sort"
    );
    let tmp_offset = self.count;
    let sub_sorter = StringSorterImpl::new(
      tmp_offset,
      &mut self.ids,
      &mut self.pool,
      byte_block_pool,
      &self.bytes_start_array,
    );
    let mut sorter = StringSorter::new(sub_sorter, Natural::default());
    sorter.sort(0, tmp_offset)?;

    length = self.ids.len();
    if let Some(ids) = self.ids.get_mut(tmp_offset..length) {
      ids.fill(-1);
    }
    Ok(())
  }
  fn shrink(&mut self, target_size: usize) -> bool {
    // Cannot use ArrayUtil.shrink because we require power of 2:
    let old_hash_size = self.hash_mask.wrapping_add(1);
    let mut new_size = old_hash_size;

    while new_size >= 8 && new_size / 4 > target_size {
      new_size /= 2;
    }

    if new_size != old_hash_size {
      let old_size = size_of_vec(&self.ids);
      self.ids = vec![-1; new_size];
      self
        .bytes_used
        .add_and_get(size_of_vec(&self.ids).saturating_sub(old_size));
      self.hash_mask = new_size - 1;
      true
    } else {
      false
    }
  }
  /// Clears the [`BytesRef`] which maps to the given [`BytesRef`].
  pub fn clear_with_reset_pool(&mut self, reset_pool: bool, byte_block_pool: &mut ByteBlockPool) {
    let last_count = self.count;
    self.count = 0;

    if reset_pool {
      self.pool.reset(byte_block_pool);
    }

    self.bytes_start_array.clear();

    if self.shrink(last_count) {
      // shrink clears the hash entries
      return;
    }
    self.ids.fill(-1);
  }
  pub fn clear(&mut self, byte_block_pool: &mut ByteBlockPool) {
    self.clear_with_reset_pool(true, byte_block_pool)
  }

  /// Closes the [`BytesRefHash`] and releases all internally used memory.
  pub fn close(&mut self, byte_block_pool: &mut ByteBlockPool) {
    self.clear_with_reset_pool(true, byte_block_pool);
    self.bytes_used.add_and_get(-size_of_vec(&self.ids));
    self.ids = vec![];
  }
  /// Adds a new [`BytesRef`].
  ///
  /// # Arguments
  /// - `bytes`: The bytes to hash.
  ///
  /// # Returns
  /// The id the given bytes are hashed to if there was no mapping for the
  /// given bytes, otherwise `(-(id) - 1)`. This guarantees that the
  /// return value will always be >= 0 if the given bytes haven't been
  /// hashed before.
  ///
  /// # Errors
  /// Returns
  /// [`LuceneErrorKind::MaxBytesLengthExceeded`](crate::core::util::error::lucene_error::LuceneErrorKind::MaxBytesLengthExceeded)
  /// if the given bytes are greater than 2 +
  /// [`BYTE_BLOCK_SIZE`](crate::core::util::byte_block_pool::BYTE_BLOCK_SIZE).
  pub fn add<BS>(
    &mut self,
    bytes: &BytesRef<BS>,
    byte_block_pool: &mut ByteBlockPool,
  ) -> Result<i32>
  where
    BS: ByteSource,
  {
    debug_assert!(
      !self.bytes_start_array.need_init(),
      "Bytesstart is null - not initialized"
    );

    // final position
    let hash_pos = self.find_hash(bytes, byte_block_pool)?;
    let mut e = self.ids[hash_pos];
    if e == -1 {
      {
        let length = self.bytes_start_array.len()?;
        let index = self.count;
        // new entry
        if index >= length {
          self.bytes_start_array.grow()?;
          let grown_length = self.bytes_start_array.len()?;
          debug_assert!(
            index < grown_length + 1,
            "count: {} len: {}",
            self.count,
            grown_length
          );
        }

        let v = self.pool.add_bytes_ref(bytes, byte_block_pool)?;
        self.bytes_start_array.set_value(index, v)?;
        e = self.count as i32;
        self.count += 1;
        debug_assert_eq!(self.ids[hash_pos], -1);
        self.ids[hash_pos] = e;
      }

      let hash_size = self.hash_mask.wrapping_add(1);
      if self.count == hash_size >> 1 {
        self.rehash(2 * hash_size, true, byte_block_pool)?;
      }

      return Ok(e);
    }
    Ok(-(e + 1))
  }
  /// Returns the id of the given [`BytesRef`].
  ///
  /// # Arguments
  /// - `bytes`: The [`BytesRef`] to look for.
  ///
  /// # Returns
  /// The id of the given bytes, or `-1` if there is no mapping for the given
  /// bytes.
  pub fn find(&self, bytes: &BytesRef<Vec<u8>>, byte_block_pool: &ByteBlockPool) -> Result<i32> {
    Ok(self.ids[self.find_hash(bytes, byte_block_pool)?])
  }
  fn find_hash<BS>(&self, bytes: &BytesRef<BS>, byte_block_pool: &ByteBlockPool) -> Result<usize>
  where
    BS: ByteSource,
  {
    debug_assert!(
      !self.bytes_start_array.need_init(),
      "bytesStart is null - not initialized"
    );

    let bytes_slice = bytes.as_byte_slice();
    let mut code = do_hash(bytes_slice, 0, bytes_slice.len());

    loop {
      let hash_pos = (code as usize) & self.hash_mask;
      let e = self.ids[hash_pos];
      if e == -1
        || self.pool.equals(
          self.bytes_start_array.get_value(e as usize)?,
          bytes,
          byte_block_pool,
        )
      {
        return Ok(hash_pos);
      }
      code = code.wrapping_add(1);
    }
  }
  /// Adds an "arbitrary" integer offset instead of a [`BytesRef`] term.
  ///
  /// This is used in the indexer to hold the hash for term vectors, because
  /// they do not redundantly store the term bytes directly and instead
  /// reference the term bytes already stored by the postings
  /// [`BytesRefHash`].
  pub fn add_by_pool_offset(
    &mut self,
    offset: i32,
    byte_block_pool: &mut ByteBlockPool,
  ) -> Result<i32> {
    debug_assert!(
      !self.bytes_start_array.need_init(),
      "Bytesstart is null - not initialized"
    );

    // Final position
    let mut code = offset;
    let mut hash_pos = (offset as usize) & self.hash_mask;
    let mut e = self.ids[hash_pos];
    let length = self.bytes_start_array.len()?;
    // Resolve hash conflicts
    while e != -1 && self.bytes_start_array.get_value(e as usize)? != offset {
      code = code.wrapping_add(1);
      hash_pos = (code as usize) & self.hash_mask;
      e = self.ids[hash_pos];
    }

    if e == -1 {
      // New entry
      let index = self.count;
      if index >= length {
        self.bytes_start_array.grow()?;
        let grown_length = self.bytes_start_array.len()?;
        debug_assert!(
          self.count < grown_length + 1,
          "count: {}, len: {}",
          self.count,
          grown_length
        );
      }

      e = self.count as i32;
      self.count += 1;
      self.bytes_start_array.set_value(index, offset)?;

      debug_assert_eq!(self.ids[hash_pos], -1);
      self.ids[hash_pos] = e;

      let hash_size = self.hash_mask.wrapping_add(1);
      if self.count == hash_size >> 1 {
        self.rehash(2 * hash_size, false, byte_block_pool)?;
      }

      return Ok(e);
    }

    Ok(-(e + 1))
  }
  /// Called when hash is too small (> 50% occupied) or too large (< 20%
  /// occupied).
  fn rehash(
    &mut self,
    new_size: usize,
    hash_on_data: bool,
    byte_block_pool: &mut ByteBlockPool,
  ) -> Result<()> {
    let new_mask = new_size - 1;
    let old_size = size_of_vec(&self.ids);
    let mut new_hash = vec![-1; new_size];
    let old_hash_size = self.hash_mask.wrapping_add(1);
    for i in 0..old_hash_size {
      let e0 = self.ids[i];
      if e0 != -1 {
        let mut code = if hash_on_data {
          self.pool.hash(
            self.bytes_start_array.get_value(e0 as usize)?,
            byte_block_pool,
          )
        } else {
          self.bytes_start_array.get_value(e0 as usize)?
        };

        let mut hash_pos = (code as usize) & new_mask;
        if new_hash[hash_pos] != -1 {
          loop {
            code = code.wrapping_add(1);
            hash_pos = (code as usize) & new_mask;
            if new_hash[hash_pos] == -1 {
              break;
            }
          }
        }
        new_hash[hash_pos] = e0;
      }
    }
    self.hash_mask = new_mask;
    self
      .bytes_used
      .add_and_get(size_of_vec(&new_hash).saturating_sub(old_size));
    self.ids = new_hash;
    Ok(())
  }

  /// Reinitializes the [`BytesRefHash`] after a previous `clear()` call.
  /// If `clear()` has not been called previously, this method has no effect.
  pub fn reinit(&mut self) -> Result<()> {
    if self.bytes_start_array.need_init() {
      self.bytes_start_array.init()?;
    }

    if self.ids.is_empty() {
      self.ids = vec![-1; self.hash_mask.wrapping_add(1)];
      self.bytes_used.add_and_get(size_of_vec(&self.ids));
    }
    Ok(())
  }
  /// Returns the `bytesStart` offset into the internally used
  /// `SingleThreadedByteBlockPool` for the given `bytes_id`.
  ///
  /// # Arguments
  /// * `bytes_id` - The ID to look up.
  ///
  /// # Returns
  /// The `bytesStart` offset into the internally used
  /// `SingleThreadedByteBlockPool` for the given ID.
  pub fn byte_start(&self, bytes_id: i32) -> Result<i32> {
    debug_assert!(
      !self.bytes_start_array.need_init(),
      "bytes_start is null - not initialized"
    );
    let bytes_index = bytes_id as usize;
    debug_assert!(bytes_id >= 0 && bytes_index < self.count);
    self.bytes_start_array.get_value(bytes_index)
  }

  /// Returns the retained heap used by this hash and the byte pool that stores
  /// its terms.
  ///
  /// The [`ByteBlockPool`] is passed separately because the Rust port keeps it
  /// outside [`BytesRefHash`]. Callers should only use this when this hash is the
  /// accounting owner of `byte_block_pool`.
  pub fn ram_bytes_used_with_pool(&self, byte_block_pool: &ByteBlockPool) -> Result<i64> {
    Ok(
      self
        .ram_bytes_used()?
        .saturating_add(byte_block_pool.ram_bytes_used()?),
    )
  }
}
impl<BSA> Accountable for BytesRefHash<BSA>
where
  BSA: BytesStartArray,
{
  fn ram_bytes_used(&self) -> Result<i64> {
    Ok(
      self
        .pool
        .ram_bytes_used()?
        .saturating_add(size_of_vec(&self.ids))
        .saturating_add(self.bytes_start_array.ram_bytes_used()?),
    )
  }
}

pub(crate) struct StringSorterImpl<'a, BSA> {
  tmp_offset: usize,
  compact: &'a mut Vec<i32>,
  pool: &'a mut BytesRefBlockPool,
  byte_block_pool: &'a ByteBlockPool,
  bytes_start_array: &'a BSA,
  k: usize,
  cmp: Natural,
  scratch_bytes: BytesRef<&'a [u8]>,
}
impl<'a, BSA> StringSorterImpl<'a, BSA>
where
  BSA: BytesStartArray,
{
  pub fn new(
    tmp_offset: usize,
    compact: &'a mut Vec<i32>,
    pool: &'a mut BytesRefBlockPool,
    byte_block_pool: &'a ByteBlockPool,
    bytes_start_array: &'a BSA,
  ) -> Self {
    StringSorterImpl {
      tmp_offset,
      compact,
      pool,
      byte_block_pool,
      bytes_start_array,
      k: 0,
      cmp: Natural::default(),
      scratch_bytes: BytesRef::default(),
    }
  }
  fn swap_bucket_cache(&mut self, i: usize, j: usize) -> Result<()> {
    self.swap(i, j)?;
    self.compact.swap(self.tmp_offset + i, self.tmp_offset + j);
    Ok(())
  }
}
impl<BSA> MSBRadixSorterBase for StringSorterImpl<'_, BSA>
where
  BSA: BytesStartArray,
{
  fn byte_at(&mut self, i: usize, k: usize) -> Result<i32> {
    let start = self.bytes_start_array.get_value(self.compact[i] as usize)?;
    self.scratch_bytes = self.pool.borrow_bytes_ref(start, self.byte_block_pool);
    self.cmp.byte_at(&self.scratch_bytes, k)
  }

  fn reorder(
    &mut self,
    from: usize,
    _to: usize,
    start_offsets: &mut [usize],
    end_offsets: &mut [usize],
    k: usize,
  ) -> Result<()> {
    debug_assert_eq!(self.k, k);
    for i in 0..HISTOGRAM_SIZE {
      let limit = end_offsets[i];
      loop {
        let h1 = start_offsets[i];
        if h1 >= limit {
          break;
        }

        let idx = self.tmp_offset + from + h1;
        let b = self.compact[idx] as usize;

        let h2 = start_offsets[b];
        start_offsets[b] += 1;

        self.swap_bucket_cache(from + h1, from + h2)?;
      }
    }
    Ok(())
  }

  fn build_histogram(
    &mut self,
    prefix_common_bucket: usize,
    prefix_common_len: usize,
    from: usize,
    to: usize,
    k: usize,
    histogram: &mut [usize],
  ) -> Result<()> {
    self.k = k;
    histogram[prefix_common_bucket] = prefix_common_len;
    self.compact[(self.tmp_offset + from - prefix_common_len)..(self.tmp_offset + from)]
      .fill(prefix_common_bucket as i32);
    for i in from..to {
      let b = self.get_bucket(i, k)?;
      self.compact[self.tmp_offset + i] = b as i32;
      histogram[b] += 1;
    }
    Ok(())
  }

  fn should_fallback(&self, from: usize, to: usize, l: usize) -> bool {
    // We lower the fallback threshold because the bucket cache speeds up
    // the reorder
    to - from <= (LENGTH_THRESHOLD / 2) || l >= LEVEL_THRESHOLD
  }
}
impl<BSA> Sorter for StringSorterImpl<'_, BSA>
where
  BSA: BytesStartArray,
{
  fn swap(&mut self, i: usize, j: usize) -> Result<()> {
    self.compact.swap(i, j);
    Ok(())
  }
}
impl<'a, BSA> StringSorterBase for StringSorterImpl<'a, BSA>
where
  BSA: BytesStartArray,
{
  type Bytes = &'a [u8];

  fn get(
    &mut self,
    _builder: &mut BytesRefBuilder<Vec<u8>>,
    result: &mut BytesRef<Self::Bytes>,
    i: usize,
  ) -> Result<()> {
    let start = self.bytes_start_array.get_value(self.compact[i] as usize)?;
    *result = self.pool.borrow_bytes_ref(start, self.byte_block_pool);
    Ok(())
  }

  fn radix_sorter<'b, C1>(&'b mut self, cmp: &'b mut C1) -> impl Sorter + 'b
  where
    C1: BytesRefComparator<Self::Bytes>,
    Self: Sorter + Sized,
  {
    let length = cmp.compared_bytes_count();
    let delegate = MSBStringHashRadixSorter::new(cmp, self);
    MSBRadixSorter::new(length, delegate)
  }
}

/// Manages allocation of the per-term addresses.
#[allow(clippy::len_without_is_empty)]
pub trait BytesStartArray {
  /// Initializes the BytesStartArray. This call will allocate memory.
  ///
  /// # Returns
  /// The initialized bytes start array.
  fn init(&mut self) -> Result<()>;

  /// Grows the [`BytesStartArray`].
  ///
  /// # Returns
  /// The grown array.
  fn grow(&mut self) -> Result<()>;

  /// Clears the [`BytesStartArray`] and returns the cleared instance.
  ///
  /// # Returns
  /// The cleared instance, this might be `None`.
  fn clear(&mut self);

  /// A reference holding the number of bytes used by this [`BytesStartArray`].
  /// The [`BytesRefHash`] uses this reference to track its memory usage.
  ///
  /// # Returns
  /// A reference holding the number of bytes used by this [`BytesStartArray`].
  fn bytes_used(&mut self) -> SharedCounter;
  fn get_value(&self, index: usize) -> Result<i32>;
  fn set_value(&mut self, index: usize, value: i32) -> Result<()>;
  fn len(&self) -> Result<usize>;
  fn need_init(&self) -> bool;
  fn ram_bytes_used(&self) -> Result<i64>;
}
/// A simple [`BytesStartArray`] that tracks memory allocation using a private
/// [`Counter`] instance.
pub struct DirectBytesStartArray {
  init_size: usize,
  pub(crate) bytes_start: Vec<i32>,
  bytes_used: SharedCounter,
  init: bool,
}
impl DirectBytesStartArray {
  pub fn new(init_size: usize) -> Self {
    DirectBytesStartArray::with_counter(init_size, Arc::new(AtomicCounter::new()))
  }
  pub fn with_counter(init_size: usize, counter: SharedCounter) -> Self {
    DirectBytesStartArray {
      init_size,
      bytes_start: vec![],
      bytes_used: counter,
      init: false,
    }
  }
}

impl BytesStartArray for DirectBytesStartArray {
  fn init(&mut self) -> Result<()> {
    self.bytes_start = vec![0; ArrayUtil::oversize(self.init_size, BitUtil::INT_BYTES)?];
    self.init = true;
    Ok(())
  }

  fn grow(&mut self) -> Result<()> {
    debug_assert!(self.init);
    let length = self.bytes_start.len();
    ArrayUtil::grow_with(&mut self.bytes_start, length + 1, || 0)?;
    Ok(())
  }

  fn clear(&mut self) {
    self.init = false;
    self.bytes_start = vec![];
  }

  fn bytes_used(&mut self) -> SharedCounter {
    self.bytes_used.clone()
  }

  fn get_value(&self, index: usize) -> Result<i32> {
    self.bytes_start.get(index).copied().ok_or_else(|| {
      LuceneError::illegal_argument(format!("bytes start index {index} is out of bounds"))
    })
  }

  fn set_value(&mut self, index: usize, value: i32) -> Result<()> {
    let slot = self.bytes_start.get_mut(index).ok_or_else(|| {
      LuceneError::illegal_argument(format!("bytes start index {index} is out of bounds"))
    })?;
    *slot = value;
    Ok(())
  }

  fn len(&self) -> Result<usize> {
    Ok(self.bytes_start.len())
  }

  fn need_init(&self) -> bool {
    !self.init
  }

  fn ram_bytes_used(&self) -> Result<i64> {
    Ok(size_of_vec(&self.bytes_start))
  }
}

pub struct MSBStringHashRadixSorter<'a, T: StringSorterBase, C> {
  scratch1: BytesRefBuilder<Vec<u8>>,
  scratch2: BytesRefBuilder<Vec<u8>>,
  pivot_builder: BytesRefBuilder<Vec<u8>>,
  scratch_bytes1: BytesRef<T::Bytes>,
  scratch_bytes2: BytesRef<T::Bytes>,
  pivot: BytesRef<T::Bytes>,
  cmp: &'a mut C,
  delegate: &'a mut T,
}
impl<'a, T, C> MSBStringHashRadixSorter<'a, T, C>
where
  T: StringSorterBase,
  C: BytesRefComparator<T::Bytes>,
{
  pub fn new(cmp: &'a mut C, delegate: &'a mut T) -> MSBStringHashRadixSorter<'a, T, C> {
    MSBStringHashRadixSorter {
      scratch1: BytesRefBuilder::default(),
      scratch2: BytesRefBuilder::default(),
      pivot_builder: BytesRefBuilder::default(),
      scratch_bytes1: BytesRef::default(),
      scratch_bytes2: BytesRef::default(),
      pivot: BytesRef::default(),
      cmp,
      delegate,
    }
  }
}

impl<T, C> Sorter for MSBStringHashRadixSorter<'_, T, C>
where
  T: StringSorterBase + MSBRadixSorterBase,
  C: BytesRefComparator<T::Bytes>,
{
  fn swap(&mut self, i: usize, j: usize) -> Result<()> {
    self.delegate.swap(i, j)
  }
}

impl<T, C> MSBRadixSorterBase for MSBStringHashRadixSorter<'_, T, C>
where
  T: StringSorterBase + MSBRadixSorterBase,
  C: BytesRefComparator<T::Bytes>,
{
  fn byte_at(&mut self, i: usize, k: usize) -> Result<i32> {
    self.delegate.byte_at(i, k)
  }

  fn get_fallback_sorter(&mut self, k: usize, _length: usize) -> impl Sorter {
    self.delegate.fall_back_sorter(
      self.cmp,
      Some(k),
      &mut self.scratch1,
      &mut self.scratch2,
      &mut self.pivot_builder,
      &mut self.scratch_bytes1,
      &mut self.scratch_bytes2,
      &mut self.pivot,
    )
  }

  fn reorder(
    &mut self,
    from: usize,
    to: usize,
    start_offsets: &mut [usize],
    end_offsets: &mut [usize],
    k: usize,
  ) -> Result<()> {
    self
      .delegate
      .reorder(from, to, start_offsets, end_offsets, k)
  }

  fn build_histogram(
    &mut self,
    prefix_common_bucket: usize,
    prefix_common_len: usize,
    from: usize,
    to: usize,
    k: usize,
    histogram: &mut [usize],
  ) -> Result<()> {
    self.delegate.build_histogram(
      prefix_common_bucket,
      prefix_common_len,
      from,
      to,
      k,
      histogram,
    )
  }

  fn should_fallback(&self, from: usize, to: usize, l: usize) -> bool {
    self.delegate.should_fallback(from, to, l)
  }
}

pub const DEFAULT_CAPACITY: usize = 16;
pub(crate) type DirectBytesRefHash = BytesRefHash<DirectBytesStartArray>;