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
/*
 * 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::hash::Hash;

use crate::core::util::accountable::Accountable;
use crate::core::util::array_util::ArrayUtil;
use crate::core::util::error::lucene_error::{LuceneError, Result};
/// BitSet of fixed length (`num_bits`), backed by an accessible
/// ([`get_bits`](LongBitSet::get_bits)) `&[i64]`, accessed with a `usize` index.
/// Use it only if you intend to store more than 2.1B bits, otherwise you should
/// use [`FixedBitSet`](crate::core::util::fixed_bit_set::FixedBitSet).
#[derive(Debug)]
pub struct LongBitSet {
  bits: Vec<i64>,  // `i64` words holding the bits.
  num_bits: usize, // The number of bits in use
  // The exact number of words needed to hold `num_bits` (`<= bits.len()`).
  num_words: usize,
}
impl LongBitSet {
  pub const MAX_NUM_BITS: usize = 64 * ArrayUtil::MAX_ARRAY_LENGTH;
  /// If the given [`LongBitSet`] is large enough to hold `num_bits + 1`,
  /// returns the given bitset, otherwise returns a new [`LongBitSet`]
  /// which can hold the requested number of bits.
  ///
  /// **NOTE:** the returned bitset reuses the underlying `Vec<i64>` of the
  /// given `bits` if possible. Also, calling
  /// [`length()`](LongBitSet::length) on the returned bitset may return a
  /// value greater than `num_bits`.
  pub fn ensure_capacity(bits: &mut LongBitSet, num_bits: usize) -> Result<()> {
    if num_bits < bits.num_bits {
    } else {
      let num_words = Self::bits2words(num_bits)?;
      let length = bits.bits.len();
      if num_words >= length {
        ArrayUtil::grow_with(&mut bits.bits, num_words + 1, || 0)?;
      }
      debug_assert!(bits.bits.len() <= i32::MAX as usize);
      bits.num_bits = (bits.bits.len()) << 6;
      bits.num_words = Self::bits2words(bits.num_bits)?;
    }
    Ok(())
  }
  /// Returns the number of 64-bit words needed to hold `num_bits`.
  pub fn bits2words(num_bits: usize) -> Result<usize> {
    if !(0..=Self::MAX_NUM_BITS).contains(&num_bits) {
      return Err(LuceneError::illegal_argument(format!(
        "num_bits must be 0..{}; got {}",
        Self::MAX_NUM_BITS,
        num_bits
      )));
    }
    if num_bits == 0 {
      Ok(0)
    } else {
      Ok(((num_bits - 1) >> 6) + 1)
    }
  }
  /// Creates a new [`LongBitSet`]. The internally allocated `[i64]` will be
  /// exactly the size needed to accommodate the `numBits` specified.
  ///
  /// # Arguments
  /// * `num_bits` - the number of bits needed
  pub fn new(num_bits: usize) -> Result<Self> {
    let num_words = Self::bits2words(num_bits)?;
    let bits = vec![0i64; num_words];
    Ok(Self::from_validated_parts(bits, num_bits, num_words))
  }
  /// Creates a new [`LongBitSet`] using the provided `Vec<i64>` as
  /// backing storage. `stored_bits` must be large enough to
  /// accommodate the `num_bits` specified, but may be larger. In that
  /// case the 'extra' or 'ghost' bits must be clear (or they may provoke
  /// spurious side-effects).
  ///
  /// # Arguments
  /// * `stored_bits` - The vector to use as backing storage.
  /// * `num_bits` - the number of bits actually needed
  pub fn from_bits<B>(stored_bits: B, num_bits: usize) -> Result<Self>
  where
    B: Into<Vec<i64>>,
  {
    let stored_bits = stored_bits.into();
    let num_words = Self::bits2words(num_bits)?;
    if num_words > stored_bits.len() {
      return Err(LuceneError::illegal_argument(format!(
        "The given long array is too small to hold {num_bits} bits"
      )));
    }

    Ok(Self::from_validated_parts(stored_bits, num_bits, num_words))
  }

  fn from_validated_parts(bits: Vec<i64>, num_bits: usize, num_words: usize) -> Self {
    debug_assert!(matches!(
      Self::bits2words(num_bits),
      Ok(expected_num_words) if expected_num_words == num_words
    ));
    debug_assert!(num_words <= bits.len());
    let bit_set = Self {
      bits,
      num_bits,
      num_words,
    };
    debug_assert!(bit_set.verify_ghost_bits_clear());
    bit_set
  }
  /**
   * Checks if the bits past numBits are clear. Some methods rely on this
   * implicit assumption: search for "Depends on the ghost bits being
   * clear!"
   *
   * return true if the bits past numBits are clear.
   */
  fn verify_ghost_bits_clear(&self) -> bool {
    for i in self.num_words..self.bits.len() {
      if self.bits[i] != 0 {
        return false;
      }
    }

    if (self.num_bits & 0x3f) == 0 {
      return true;
    }

    let mask = (!0i64).wrapping_shl(self.num_bits as u32);
    (self.bits[self.num_words - 1] & mask) == 0
  }
  /// Returns the number of bits stored in this bitset.
  pub fn length(&self) -> usize {
    self.num_bits
  }

  /// Expert.
  pub fn get_bits(&self) -> &[i64] {
    &self.bits
  }

  /// Returns number of set bits.
  ///
  /// NOTE: this visits every long in the backing bits array,
  /// and the result is not internally cached!
  ///
  /// This relies on ghost bits being clear.
  pub fn cardinality(&self) -> usize {
    // Depends on the ghost bits being clear!
    let words = &self.bits[..self.num_words];
    if words.len() >= 8 {
      words.iter().map(|v| v.count_ones() as usize).sum()
    } else {
      match words.len() {
        0 => 0,
        1 => words[0].count_ones() as usize,
        _ => {
          // Count two disjoint 64-bit halves together without sign extension.
          let (pairs, tail) = words.as_chunks::<2>();
          pairs
            .iter()
            .map(|&[a, b]| ((a as u64 as u128) | ((b as u64 as u128) << 64)).count_ones() as usize)
            .sum::<usize>()
            + tail.iter().map(|v| v.count_ones() as usize).sum::<usize>()
        },
      }
    }
  }

  pub fn get(&self, index: usize) -> bool {
    debug_assert!(
      index < self.num_bits,
      "index = {}, num_bits = {}",
      index,
      self.num_bits
    );
    let i = index >> 6;
    // signed shift will keep a negative index and force an
    // array-index-out-of-bounds-error, removing the need for an
    // explicit check.
    let bitmask = 1i64.wrapping_shl(index as u32);
    (self.bits[i] & bitmask) != 0
  }

  pub fn set(&mut self, index: usize) {
    debug_assert!(
      index < self.num_bits,
      "index = {}, num_bits = {}",
      index,
      self.num_bits
    );
    let word_num = index >> 6;
    let bitmask = 1i64.wrapping_shl(index as u32);
    self.bits[word_num] |= bitmask;
  }

  /// Returns the previous value of the bit at `index`, and sets it.
  pub fn get_and_set(&mut self, index: usize) -> bool {
    debug_assert!(
      index < self.num_bits,
      "index = {}, num_bits = {}",
      index,
      self.num_bits
    );
    let word_num = index >> 6;
    let bitmask = 1i64.wrapping_shl(index as u32);
    let val = (self.bits[word_num] & bitmask) != 0;
    self.bits[word_num] |= bitmask;
    val
  }
  pub fn clear(&mut self, index: usize) {
    debug_assert!(
      index < self.num_bits,
      "index = {}, num_bits = {}",
      index,
      self.num_bits
    );
    let word_num = index >> 6;
    let bitmask = 1i64.wrapping_shl(index as u32);
    self.bits[word_num] &= !bitmask;
  }

  /// Returns the previous value of the bit at `index`, and clears it.
  pub fn get_and_clear(&mut self, index: usize) -> bool {
    debug_assert!(
      index < self.num_bits,
      "index = {}, num_bits = {}",
      index,
      self.num_bits
    );
    let word_num = index >> 6;
    let bitmask = 1i64.wrapping_shl(index as u32);
    let val = (self.bits[word_num] & bitmask) != 0;
    self.bits[word_num] &= !bitmask;
    val
  }

  /// Returns the index of the first set bit starting at the given `index`.
  /// Returns -1 if no such bit is found.
  ///
  /// Depends on ghost bits being clear!
  pub fn next_set_bit(&self, index: usize) -> Option<usize> {
    debug_assert!(
      index < self.num_bits,
      "index = {}, num_bits = {}",
      index,
      self.num_bits
    );

    let mut i = index >> 6;
    let sub_index = index & 63;
    let mut word = self.bits[i] >> sub_index;

    if word != 0 {
      return Some(index + word.trailing_zeros() as usize);
    }

    i += 1;
    while i < self.num_words {
      word = self.bits[i];
      if word != 0 {
        return Some(i << 6 | word.trailing_zeros() as usize);
      }
      i += 1;
    }
    None
  }
  /// Returns the index of the last set bit before or on the given `index`.
  /// Returns -1 if there are no more set bits.
  pub fn prev_set_bit(&self, index: usize) -> Option<usize> {
    debug_assert!(
      index < self.num_bits,
      "index = {}, num_bits = {}",
      index,
      self.num_bits
    );

    let i = index >> 6;
    let sub_index = index & 0x3f;
    let word = self.bits[i] << (63 - sub_index);

    if word != 0 {
      return Some((i << 6) + sub_index - word.leading_zeros() as usize);
    }

    let mut v = i.checked_sub(1);

    while let Some(i) = v {
      let word = self.bits[i];
      if word != 0 {
        return Some((i << 6) + 63 - word.leading_zeros() as usize);
      }
      v = i.checked_sub(1);
    }
    None
  }

  /// Performs bitwise OR: this = this OR other
  pub fn or(&mut self, other: &LongBitSet) {
    debug_assert!(
      other.num_words <= self.num_words,
      "num_words = {}, other.num_words = {}",
      self.num_words,
      other.num_words
    );

    let pos = std::cmp::min(self.num_words, other.num_words);
    for i in 0..pos {
      self.bits[i] |= other.bits[i];
    }
  }
  /// Performs bitwise XOR: this = this XOR other
  pub fn xor(&mut self, other: &LongBitSet) {
    debug_assert!(
      other.num_words <= self.num_words,
      "num_words = {}, other.num_words = {}",
      self.num_words,
      other.num_words
    );

    let pos = std::cmp::min(self.num_words, other.num_words);
    for i in 0..pos {
      self.bits[i] ^= other.bits[i];
    }
  }

  /// Returns true if the sets have any elements in common.
  ///
  /// Depends on the ghost bits being clear!
  pub fn intersects(&self, other: &LongBitSet) -> bool {
    let pos = std::cmp::min(self.num_words, other.num_words);
    if pos == 0 {
      return false;
    }
    // Probe both ends while retaining the fast first-word path.
    if (self.bits[0] & other.bits[0]) != 0 {
      return true;
    }
    if pos == 1 {
      return false;
    }
    if (self.bits[pos - 1] & other.bits[pos - 1]) != 0 {
      return true;
    }
    for i in 1..pos - 1 {
      if (self.bits[i] & other.bits[i]) != 0 {
        return true;
      }
    }
    false
  }

  /// Performs bitwise AND: this = this AND other
  pub fn and(&mut self, other: &LongBitSet) {
    let pos = std::cmp::min(self.num_words, other.num_words);
    for i in 0..pos {
      self.bits[i] &= other.bits[i];
    }
    if self.num_words > other.num_words {
      for i in other.num_words..self.num_words {
        self.bits[i] = 0;
      }
    }
  }

  /// Performs bitwise AND NOT: this = this AND NOT other
  pub fn and_not(&mut self, other: &LongBitSet) {
    let pos = std::cmp::min(self.num_words, other.num_words);
    for i in 0..pos {
      self.bits[i] &= !other.bits[i];
    }
  }
  /// Scans the backing store to check if all bits are clear.
  ///
  /// The method is deliberately not called "is_empty" to emphasize it is not
  /// low cost.
  ///
  /// This depends on the ghost bits being clear!
  pub fn scan_is_empty(&self) -> bool {
    // Constructors validate num_words <= bits.len(); keep the bound explicit
    // so the grouped loads do not need individual bounds checks.
    let mut num_words = self.num_words;
    if num_words > self.bits.len() {
      num_words = self.bits.len();
    }
    let mut i = 0;
    while i < num_words {
      if self.bits[i] != 0 {
        return false;
      }
      i += 1;
      // One scalar probe followed by five words keeps first hits cheap.
      if i + 5 <= num_words {
        if (self.bits[i]
          | self.bits[i + 1]
          | self.bits[i + 2]
          | self.bits[i + 3]
          | self.bits[i + 4])
          != 0
        {
          return false;
        }
        i += 5;
      }
    }
    true
  }

  /// Flips a range of bits in [start_index, end_index)
  ///
  /// - `start_index`: lower bound (inclusive)
  /// - `end_index`: upper bound (exclusive)
  pub fn flip(&mut self, start_index: usize, end_index: usize) {
    debug_assert!(
      start_index < self.num_bits,
      "start_index = {}, num_bits = {}",
      start_index,
      self.num_bits
    );
    debug_assert!(
      end_index <= self.num_bits,
      "end_index = {}, num_bits = {}",
      end_index,
      self.num_bits
    );

    if end_index <= start_index {
      return;
    }

    let start_word = start_index >> 6;
    let end_word = (end_index - 1) >> 6;

    let start_mask = -1_i64 << (start_index % 64);
    let shift = 0usize.wrapping_sub(end_index) & 63;
    let end_mask = (u64::MAX >> shift) as i64;

    if start_word == end_word {
      self.bits[start_word] ^= start_mask & end_mask;
      return;
    }

    self.bits[start_word] ^= start_mask;

    for i in (start_word + 1)..end_word {
      self.bits[i] = !self.bits[i];
    }

    self.bits[end_word] ^= end_mask;
  }
  /// Flip the bit at the provided index.
  pub fn flip_one(&mut self, index: usize) {
    debug_assert!(
      index < self.num_bits,
      "index = {}, num_bits = {}",
      index,
      self.num_bits
    );
    let word_num = index >> 6;
    let bitmask = 1i64.wrapping_shl(index as u32); // mod 64 is implicit
    self.bits[word_num] ^= bitmask;
  }

  /// Sets a range of bits in [start_index, end_index)
  ///
  /// - `start_index`: lower index (inclusive)
  /// - `end_index`: one-past the last bit to set
  pub fn set_range(&mut self, start_index: usize, end_index: usize) {
    debug_assert!(
      start_index < self.num_bits,
      "start_index = {}, num_bits = {}",
      start_index,
      self.num_bits
    );
    debug_assert!(
      end_index <= self.num_bits,
      "end_index = {}, num_bits = {}",
      end_index,
      self.num_bits
    );

    if end_index <= start_index {
      return;
    }

    let start_word = start_index >> 6;
    let end_word = (end_index - 1) >> 6;

    let start_mask = -1_i64 << (start_index % 64);
    let shift = 0usize.wrapping_sub(end_index) & 63;
    let end_mask = (u64::MAX >> shift) as i64;

    if start_word == end_word {
      self.bits[start_word] |= start_mask & end_mask;
      return;
    }

    self.bits[start_word] |= start_mask;
    for i in (start_word + 1)..end_word {
      self.bits[i] = -1;
    }
    self.bits[end_word] |= end_mask;
  }
  /// Clears a range of bits in [start_index, end_index)
  ///
  /// - `start_index`: lower index (inclusive)
  /// - `end_index`: one-past the last bit to clear
  pub fn clear_range(&mut self, start_index: usize, end_index: usize) {
    debug_assert!(
      start_index < self.num_bits,
      "start_index = {}, num_bits = {}",
      start_index,
      self.num_bits
    );
    debug_assert!(
      end_index <= self.num_bits,
      "end_index = {}, num_bits = {}",
      end_index,
      self.num_bits
    );

    if end_index <= start_index {
      return;
    }

    let start_word = start_index >> 6;
    let end_word = (end_index - 1) >> 6;

    let mut start_mask = -1_i64 << (start_index % 64);
    let shift = 0usize.wrapping_sub(end_index) & 63;
    let mut end_mask = (u64::MAX >> shift) as i64;

    // Invert masks since we are clearing
    start_mask = !start_mask;
    end_mask = !end_mask;

    if start_word == end_word {
      self.bits[start_word] &= start_mask | end_mask;
      return;
    }

    self.bits[start_word] &= start_mask;
    for i in (start_word + 1)..end_word {
      self.bits[i] = 0;
    }
    self.bits[end_word] &= end_mask;
  }
}
impl Accountable for LongBitSet {
  fn ram_bytes_used(&self) -> Result<i64> {
    Ok(crate::core::util::ram_usage_estimator::size_of_vec(
      &self.bits,
    ))
  }
}
impl Clone for LongBitSet {
  fn clone(&self) -> Self {
    Self::from_validated_parts(self.bits.clone(), self.num_bits, self.num_words)
  }
}
impl PartialEq for LongBitSet {
  fn eq(&self, other: &Self) -> bool {
    if self.num_bits != other.num_bits {
      return false;
    }
    self.bits == other.bits
  }
}
impl Eq for LongBitSet {}
impl Hash for LongBitSet {
  fn hash<H>(&self, state: &mut H)
  where
    H: std::hash::Hasher,
  {
    self.bits.hash(state);
    self.num_bits.hash(state);
  }
}