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
/*
 * 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::{Borrow, Cow};

use crate::core::index::{BytesRef, BytesRefBuilder, BytesRefValueEnum};
use crate::core::util::access::ByteSource;
use crate::core::util::accountable::Accountable;
use crate::core::util::allocator_byte::DirectTrackingAllocatorByte;
use crate::core::util::array_util::ArrayUtil;
use crate::core::util::byte_block_pool::{BYTE_BLOCK_MASK, BYTE_BLOCK_SHIFT, BYTE_BLOCK_SIZE};
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::ram_usage_estimator::size_of_array_capacity;
use crate::core::util::sortable_bytes_ref_array::SortableBytesRefArray;
use crate::core::util::{
  ByteBlockPool, BytesRefComparator, Counter, MSBRadixSorterBase, SharedCounter, SliceCopyOps,
  Sorter, StableStringSorter, StableStringSorterBase, StringSorter, StringSorterBase, TryIntoInt,
};

/// A simple append-only random-access array that stores full copies of the
/// appended bytes in a [`ByteBlockPool`].
///
/// # Note
/// This struct is **not thread-safe!**
///
/// # Internal
/// This is an internal and experimental component.
#[derive(Debug)]
pub struct BytesRefArray {
  storage: ByteStorage,
  offsets: smallvec::SmallVec<[usize; 1]>,
  last_element: usize,
  current_offset: usize,
  byte_used: SharedCounter,
}

#[derive(Debug)]
enum ByteStorage {
  Blocks(Box<ByteBlockPool>),
  Compact(Vec<u8>),
}

impl BytesRefArray {
  pub fn new(byte_used: SharedCounter) -> Result<BytesRefArray> {
    let allocator = DirectTrackingAllocatorByte::new(byte_used.clone());
    byte_used.add_and_get(size_of::<ByteBlockPool>() as i64);
    let storage = ByteStorage::Blocks(Box::new(ByteBlockPool::new(allocator)));
    Ok(Self::with_storage(byte_used, storage))
  }

  pub(crate) fn new_compact(byte_used: SharedCounter) -> Self {
    Self::with_storage(byte_used, ByteStorage::Compact(Vec::new()))
  }

  fn with_storage(byte_used: SharedCounter, storage: ByteStorage) -> Self {
    let offsets = smallvec::SmallVec::with_capacity(1);
    byte_used.add_and_get(size_of_array_capacity::<usize>(offsets.capacity()));
    Self {
      storage,
      offsets,
      last_element: 0,
      current_offset: 0,
      byte_used,
    }
  }
  /// Returns the nth element of this [`BytesRefArray`].
  ///
  /// The returned bytes borrow the pool when the value is contained in one
  /// block. Values spanning blocks own a copy.
  ///
  /// # Parameters
  /// - `index`: The index of the element to retrieve.
  ///
  /// # Returns
  /// The nth element of this [`BytesRefArray`] as a [`BytesRefValueEnum`].
  ///
  /// # Errors
  /// Returns [`LuceneError::array_index_out_of_bounds`] if the index is
  /// invalid.
  pub fn get(&self, index: usize) -> Result<BytesRefValueEnum<'_>> {
    if index >= self.last_element {
      return Err(LuceneError::array_index_out_of_bounds(format!(
        "index: {}, last_element: {}",
        index, self.last_element
      )));
    }

    let offset = self.offsets[index];
    let length = if index == self.last_element - 1 {
      self.current_offset - offset
    } else {
      self.offsets[index + 1] - offset
    };

    if length == 0 {
      return Ok(BytesRefValueEnum::Slice(BytesRef {
        bytes: &[],
        offset: 0,
        length: 0,
      }));
    }
    let pool = match &self.storage {
      ByteStorage::Compact(bytes) => {
        return Ok(BytesRefValueEnum::Slice(BytesRef {
          bytes: &bytes[offset..offset + length],
          offset: 0,
          length,
        }));
      },
      ByteStorage::Blocks(pool) => pool,
    };
    let block_index = offset >> BYTE_BLOCK_SHIFT;
    let block_offset = offset & BYTE_BLOCK_MASK as usize;
    if length <= BYTE_BLOCK_SIZE as usize - block_offset {
      return Ok(BytesRefValueEnum::Slice(BytesRef {
        bytes: &pool.get_buffer(block_index)[block_offset..block_offset + length],
        offset: 0,
        length,
      }));
    }
    // Keep Lucene's length validation, but this owned snapshot will not grow.
    ArrayUtil::oversize(length, size_of::<u8>())?;
    let mut bytes = Vec::with_capacity(length);
    let buffer_index: i32 = ((offset as i64) >> BYTE_BLOCK_SHIFT).try_convert()?;
    let mut buffer_index = buffer_index as usize;
    let mut pos = (offset as i64 & BYTE_BLOCK_MASK as i64) as usize;
    let mut remaining = length;
    while remaining > 0 {
      let chunk = std::cmp::min(BYTE_BLOCK_SIZE as usize - pos, remaining);
      bytes.extend_from_slice(&pool.get_buffer(buffer_index)[pos..pos + chunk]);
      remaining -= chunk;
      buffer_index += 1;
      pos = 0;
    }
    Ok(BytesRefValueEnum::Buffer(Cow::Owned(BytesRef {
      bytes,
      offset: 0,
      length,
    })))
  }

  /// Used only by the sorting function below to set a [`BytesRef`] with the
  /// specified slice, avoiding copying bytes in the common case when the
  /// slice is contained in a single block in the byte block pool.
  #[allow(
    clippy::owned_cow,
    reason = "Matches ByteBlockPool's Vec carrier, which preserves reusable cross-block capacity"
  )]
  fn set_bytes_ref<'a>(
    &'a self,
    spare: &mut BytesRefBuilder<Vec<u8>>,
    result: &mut BytesRef<Cow<'a, Vec<u8>>>,
    index: usize,
  ) -> Result<()> {
    if index >= self.last_element {
      return Err(LuceneError::array_index_out_of_bounds(format!(
        "index: {}, last_element: {}",
        index, self.last_element
      )));
    }

    let offset = self.offsets[index];
    let length = if index == self.last_element - 1 {
      self.current_offset - offset
    } else {
      self.offsets[index + 1] - offset
    };

    match &self.storage {
      ByteStorage::Compact(bytes) => {
        result.bytes = Cow::Borrowed(bytes);
        result.offset = offset;
        result.length = length;
      },
      ByteStorage::Blocks(pool) => pool.set_bytes_ref(spare, result, offset as i64, length)?,
    }
    Ok(())
  }

  /// Returns a [`SortState`] representing the order of elements in this
  /// array. This is a non-destructive operation.
  ///
  /// # Parameters
  /// - `comp`: The comparator to compare [`BytesRef`]s. A radix sort
  ///   optimization is available if the comparator implements
  ///   [`BytesRefComparator`].
  /// - `stable`: Indicates if the sort needs to be stable.
  ///
  /// # Returns
  /// A [`SortState`] that can be used in
  /// [`BytesRefArray::iterator_with_state`] with the given sort state.
  pub fn sort<'a, C>(&'a self, comp: C, stable: bool) -> Result<SortState>
  where
    C: BytesRefComparator<Cow<'a, Vec<u8>>>,
  {
    let size = self.size();
    let mut indices = (size > 1).then(|| (0..size).collect::<smallvec::SmallVec<_>>());
    let mut identity = [0];
    let ordered_entries = indices
      .as_deref_mut()
      .unwrap_or(&mut identity[..size.min(1)]);
    if stable {
      let delegate = StableStringSorterImpl {
        tmp: Vec::new(),
        ordered_entries,
        bytes_ref_array: self,
      };
      let stable_string_sorter = StableStringSorter::new(delegate);
      let mut string_sorter = StringSorter::new(stable_string_sorter, comp);
      string_sorter.sort(0, size)?;
    } else {
      let delegate = StringSorterImpl {
        ordered_entries,
        bytes_ref_array: self,
      };
      let mut string_sorter = StringSorter::new(delegate, comp);
      string_sorter.sort(0, size)?;
    }
    Ok(SortState::new(indices))
  }
  pub fn iterator(&'_ self) -> IndexedBytesRefIteratorImpl<'_> {
    IndexedBytesRefIteratorImpl::new(None, self)
  }
  /// Returns an [`IndexedBytesRefIteratorImpl`] with point-in-time semantics.
  /// The iterator provides access to all [`BytesRef`] instances appended so
  /// far.
  ///
  /// # Parameters
  /// - `sort_state`:  the iterator will iterate the byte values in the order
  ///   defined by the `sort_state`.
  ///
  /// # Note
  /// - This is a non-destructive operation.
  /// # See Also
  /// [`IndexedBytesRefIterator`]
  ///
  /// [`BytesRef`]
  pub fn iterator_with_state<S: Borrow<SortState>>(
    &self,
    sort_state: S,
  ) -> IndexedBytesRefIteratorImpl<'_, S> {
    IndexedBytesRefIteratorImpl::new(Some(sort_state), self)
  }
}
/// Appends a copy of the given [`BytesRef`] to this [`BytesRefArray`].
///
/// # Parameters
/// - `bytes`: The [`BytesRef`] to append.
///
/// # Returns
/// The index of the appended bytes.
///
/// [`BytesRef`]
///
/// [`BytesRefArray`]
impl<'a> SortableBytesRefArray<'a> for BytesRefArray {
  fn append<AV: ByteSource>(&mut self, bytes: &BytesRef<AV>) -> Result<usize> {
    let view = bytes.as_byte_slice();
    if self.offsets.len() == self.offsets.capacity() {
      let old_size = size_of_array_capacity::<usize>(self.offsets.capacity());
      let min_size = self.offsets.len() + 1;
      ArrayUtil::oversize(min_size, size_of::<usize>())?;
      // Match Vec's minimum nonzero growth capacity for word-sized elements.
      let capacity = min_size.max(self.offsets.capacity() * 2).max(4);
      self.offsets.reserve_exact(capacity - self.offsets.len());
      self
        .byte_used
        .add_and_get(size_of_array_capacity::<usize>(self.offsets.capacity()) - old_size);
    }
    match &mut self.storage {
      ByteStorage::Compact(bytes) => {
        // Keep the same representable end offsets as the block pool.
        let end = bytes
          .len()
          .checked_add(view.len())
          .filter(|&end| i32::try_from(end).is_ok());
        if end.is_none() {
          return Err(LuceneError::number_overflow(
            "Overflow when calculating byte offset.",
          ));
        }
        let old_capacity = bytes.capacity();
        bytes.extend_from_slice(view);
        if bytes.capacity() != old_capacity {
          self.byte_used.add_and_get(
            size_of_array_capacity::<u8>(bytes.capacity())
              - if old_capacity == 0 {
                0
              } else {
                size_of_array_capacity::<u8>(old_capacity)
              },
          );
        }
      },
      ByteStorage::Blocks(pool) => {
        if pool.buffer_upto.is_none() {
          pool.next_buffer()?;
        }
        pool.append(view)?;
      },
    }
    self.offsets.push(self.current_offset);
    self.last_element += 1;
    self.current_offset += view.len();
    Ok(self.last_element - 1)
  }

  fn clear(&mut self) {
    self.last_element = 0;
    self.current_offset = 0;
    self.offsets.clear();
    match &mut self.storage {
      ByteStorage::Compact(bytes) => bytes.clear(),
      ByteStorage::Blocks(pool) => pool.reset(false, true),
    }
  }

  fn size(&self) -> usize {
    self.last_element
  }

  /// Returns an [`IndexedBytesRefIterator`] with point-in-time semantics. The
  /// iterator provides access to all [`BytesRef`] instances appended so
  /// far.
  ///
  /// # Parameters
  /// - `comp`: An optional [`Comparator`](crate::core::util::comparator::Comparator) to specify the order of iteration.
  ///   the iterator will iterate the byte values in the order specified by
  ///   the comparator.
  ///
  /// # Note
  /// - This is a non-destructive operation.
  type Iter = IndexedBytesRefIteratorImpl<'a>;

  fn iterator<C>(&'a self, comp: C) -> Result<Self::Iter>
  where
    C: BytesRefComparator<Cow<'a, Vec<u8>>>,
  {
    let ords = self.sort(comp, false)?;
    Ok(self.iterator_with_state(ords))
  }
}

#[derive(Clone, Debug)]
pub struct SortState {
  pub(crate) indices: Option<smallvec::SmallVec<[usize; 4]>>,
}
impl SortState {
  fn new(indices: Option<smallvec::SmallVec<[usize; 4]>>) -> SortState {
    SortState { indices }
  }
}
impl Accountable for SortState {
  fn ram_bytes_used(&self) -> Result<i64> {
    Ok(
      self
        .indices
        .as_ref()
        .filter(|indices| indices.spilled())
        .map_or(0, |indices| {
          size_of_array_capacity::<usize>(indices.capacity())
        }),
    )
  }
}

pub struct IndexedBytesRefIteratorImpl<'a, S = SortState> {
  pos: usize,
  pub(crate) ord: usize,
  sort_state: Option<S>,
  size: usize,
  bytes_ref_array: &'a BytesRefArray,
  result: BytesRef<Vec<u8>>,
}
impl<'a, S: Borrow<SortState>> IndexedBytesRefIteratorImpl<'a, S> {
  pub(crate) fn new(
    sort_state: Option<S>,
    bytes_ref_array: &'a BytesRefArray,
  ) -> IndexedBytesRefIteratorImpl<'a, S> {
    if let Some(indices) = sort_state
      .as_ref()
      .and_then(|state| state.borrow().indices.as_ref())
    {
      debug_assert_eq!(indices.len(), bytes_ref_array.size());
    }
    Self {
      pos: 0,
      ord: 0,
      sort_state,
      size: bytes_ref_array.size(),
      bytes_ref_array,
      result: BytesRef::new(),
    }
  }
}
impl<S: Borrow<SortState>> IndexedBytesRefIterator for IndexedBytesRefIteratorImpl<'_, S> {
  fn next(&mut self) -> Result<Option<(usize, BytesRefValueEnum<'_>)>> {
    if self.pos < self.size {
      self.ord = match self
        .sort_state
        .as_ref()
        .and_then(|state| state.borrow().indices.as_ref())
      {
        None => self.pos,
        Some(indices) => indices[self.pos],
      };

      let array = self.bytes_ref_array;
      if self.ord >= array.last_element {
        return Err(LuceneError::array_index_out_of_bounds(format!(
          "index: {}, last_element: {}",
          self.ord, array.last_element
        )));
      }
      let offset = array.offsets[self.ord];
      let length = if self.ord == array.last_element - 1 {
        array.current_offset - offset
      } else {
        array.offsets[self.ord + 1] - offset
      };
      // Retain the growth error before updating the result or converting
      // the offset, even when a contiguous value no longer needs a copy.
      if self.result.bytes.len() < length {
        ArrayUtil::oversize(length, size_of::<u8>())?;
      }
      let pool = match &array.storage {
        ByteStorage::Compact(bytes) => {
          self.pos += 1;
          let value = BytesRef {
            bytes: &bytes[offset..offset + length],
            offset: 0,
            length,
          };
          return Ok(Some((self.ord, BytesRefValueEnum::Slice(value))));
        },
        ByteStorage::Blocks(pool) => pool,
      };
      let offset = offset as i64;
      let pos = (offset & BYTE_BLOCK_MASK as i64) as usize;
      if pos + length > BYTE_BLOCK_SIZE as usize {
        ArrayUtil::grow_no_copy(&mut self.result.bytes, length, || 0)?;
      }
      self.result.length = length;
      let buffer_index: i32 = (offset >> BYTE_BLOCK_SHIFT).try_convert()?;
      let value = if pos + length <= BYTE_BLOCK_SIZE as usize {
        let bytes = &pool.get_buffer(buffer_index as usize)[pos..pos + length];
        self.result.offset = 0;
        BytesRefValueEnum::Slice(BytesRef {
          bytes,
          offset: 0,
          length,
        })
      } else {
        self.result.offset = 0;
        pool.read_bytes(offset, &mut self.result.bytes, 0, length)?;
        BytesRefValueEnum::Buffer(Cow::Borrowed(&self.result))
      };
      self.pos += 1;
      Ok(Some((self.ord, value)))
    } else {
      Ok(None)
    }
  }
  fn ord(&self) -> usize {
    self.ord
  }
}

pub trait IndexedBytesRefIterator {
  /// Returns the next ordinal and value, borrowing a pool block when contiguous.
  fn next(&mut self) -> Result<Option<(usize, BytesRefValueEnum<'_>)>>;

  /// Returns the ordinal position of the element that was returned in the
  /// latest call to [`next`](Self::next).
  ///
  /// # Warning
  /// This method must not be called if [`next`](Self::next) has
  /// not been called yet, or if the last call to
  /// [`next`](Self::next) returned `None`.
  fn ord(&self) -> usize;
}

struct StableStringSorterImpl<'a, 'o> {
  tmp: Vec<usize>,
  ordered_entries: &'o mut [usize],
  bytes_ref_array: &'a BytesRefArray,
}
impl Sorter for StableStringSorterImpl<'_, '_> {
  fn swap(&mut self, i: usize, j: usize) -> Result<()> {
    self.ordered_entries.swap(i, j);
    Ok(())
  }
}

impl<'a> StringSorterBase for StableStringSorterImpl<'a, '_> {
  type Bytes = Cow<'a, Vec<u8>>;

  fn get(
    &mut self,
    builder: &mut BytesRefBuilder<Vec<u8>>,
    result: &mut BytesRef<Cow<'a, Vec<u8>>>,
    i: usize,
  ) -> Result<()> {
    self
      .bytes_ref_array
      .set_bytes_ref(builder, result, self.ordered_entries[i])
  }
}

impl StableStringSorterBase for StableStringSorterImpl<'_, '_> {
  fn save(&mut self, i: usize, j: usize) {
    let value = self.ordered_entries[i];
    if self.tmp.is_empty() {
      self.tmp = vec![0; self.ordered_entries.len()];
    }
    self.tmp[j] = value;
  }
  fn restore(&mut self, i: usize, j: usize) {
    self.ordered_entries.copy_from(&self.tmp[i..j], i);
  }
}
impl MSBRadixSorterBase for StableStringSorterImpl<'_, '_> {}

struct StringSorterImpl<'a, 'o> {
  ordered_entries: &'o mut [usize],
  bytes_ref_array: &'a BytesRefArray,
}
impl Sorter for StringSorterImpl<'_, '_> {
  fn swap(&mut self, i: usize, j: usize) -> Result<()> {
    self.ordered_entries.swap(i, j);
    Ok(())
  }
}
impl<'a> StringSorterBase for StringSorterImpl<'a, '_> {
  type Bytes = Cow<'a, Vec<u8>>;

  fn get(
    &mut self,
    builder: &mut BytesRefBuilder<Vec<u8>>,
    result: &mut BytesRef<Cow<'a, Vec<u8>>>,
    i: usize,
  ) -> Result<()> {
    self
      .bytes_ref_array
      .set_bytes_ref(builder, result, self.ordered_entries[i])
  }
}