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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::fmt;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use crate::core::util::error::lucene_error::{LuceneError, Result};
use crate::core::util::{Comparator, ToInt};
/// Represents a slice (offset + length) into an existing `Vec<i64>`.
///
/// The `longs` member should never be `None`; use an empty vector
/// (`Vec::new()`) if necessary.
#[derive(Debug, Eq)]
pub struct LongsRef {
/// The contents of the LongsRef. Should never be `None`.
pub longs: Vec<i64>,
/// Offset of the first valid long.
pub offset: usize,
/// Length of used longs.
pub length: usize,
}
impl Default for LongsRef {
fn default() -> Self {
Self::new()
}
}
impl LongsRef {
/// Create a [`LongsRef`] with an empty vector.
pub fn new() -> Self {
Self {
longs: Vec::new(),
offset: 0,
length: 0,
}
}
/// Create a [`LongsRef`] pointing to a new vector of the given capacity.
///
/// Offset and length will both be zero.
pub fn with_capacity(capacity: usize) -> Self {
Self {
longs: vec![0; capacity],
offset: 0,
length: 0,
}
}
/// This instance will directly reference the given `Vec<i64>` without
/// making a copy.
///
/// # Arguments
///
/// * `longs` - The vector to reference. May be empty.
/// * `offset` - The offset where valid longs start.
/// * `length` - The number of valid longs.
pub fn from_slice<L>(longs: L, offset: usize, length: usize) -> Self
where
L: Into<Vec<i64>>,
{
let longs = longs.into();
debug_assert!(matches!(
Self::is_valid(longs.as_slice(), offset, length),
Ok(true)
));
Self {
longs,
offset,
length,
}
}
/// Creates a new [`LongsRef`] that points to a copy of the longs from
/// `other`.
///
/// The returned [`LongsRef`] will have a length of `other.length` and an
/// offset of zero.
///
/// # Arguments
///
/// * `other` - The [`LongsRef`] to copy.
///
/// # Returns
///
/// A new [`LongsRef`] that is a deep copy of the provided `other`.
pub fn deep_copy_of(other: &LongsRef) -> Result<LongsRef> {
if other.offset > other.longs.len() || other.length > other.longs.len() - other.offset {
return Err(LuceneError::array_index_out_of_bounds(
"Offset and length exceed vector bounds",
));
}
let copied_longs = other.longs[other.offset..(other.offset + other.length)].to_vec();
Ok(LongsRef {
longs: copied_longs,
offset: 0,
length: other.length,
})
}
pub fn is_valid(longs: &[i64], offset: usize, length: usize) -> Result<bool> {
if length > longs.len() {
return Err(LuceneError::illegal_state(format!(
"length is out of bounds: {}, longs.len={}",
length,
longs.len()
)));
}
if offset > longs.len() {
return Err(LuceneError::illegal_state(format!(
"offset is out of bounds: {}, longs.len={}",
offset,
longs.len()
)));
}
if offset + length > longs.len() {
return Err(LuceneError::illegal_state(format!(
"offset + length out of bounds: offset={}, length={}, longs.len={}",
offset,
length,
longs.len()
)));
}
Ok(true)
}
pub fn longs_equals(&self, other: &LongsRef) -> bool {
debug_assert!(
(self.offset + self.length) <= self.longs.len()
&& (other.offset + other.length) <= other.longs.len()
);
self.longs[self.offset..(self.offset + self.length)]
== other.longs[other.offset..(other.offset + other.length)]
}
}
impl Clone for LongsRef {
fn clone(&self) -> Self {
Self {
longs: self.longs.clone(),
offset: self.offset,
length: self.length,
}
}
}
impl Hash for LongsRef {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
const PRIME: u64 = 31;
let mut result: u64 = 0;
let end = self.offset + self.length;
for &value in &self.longs[self.offset..end] {
result = PRIME
.wrapping_mul(result)
.wrapping_add((value ^ (value >> 32)) as u64);
}
state.write_u64(result);
}
}
impl PartialEq for LongsRef {
fn eq(&self, other: &Self) -> bool {
self.longs_equals(other)
}
}
impl Display for LongsRef {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "[")?;
let end = self.offset + self.length;
for i in self.offset..end {
if i > self.offset {
write!(f, " ")?;
}
write!(f, "{:x}", self.longs[i])?;
}
write!(f, "]")
}
}
pub struct LongsRefComparator;
impl Comparator<LongsRef> for LongsRefComparator {
const TYPE: &'static str = "LongsRefComparator";
/// Compares two [`LongsRef`] instances.
///
/// # Arguments
///
/// * `a` - The first [`LongsRef`] to compare.
/// * `b` - The second [`LongsRef`] to compare.
///
/// # Returns
///
/// * A negative integer if `a < b`.
/// * Zero if `a == b`.
/// * A positive integer if `a > b`.
fn compare(&self, a: &LongsRef, b: &LongsRef) -> Result<i32> {
let a_end = a
.offset
.checked_add(a.length)
.ok_or_else(|| LuceneError::illegal_argument("offset + length overflow"))?;
let a_slice = a.longs.get(a.offset..a_end).ok_or_else(|| {
LuceneError::array_index_out_of_bounds("Offset and length exceed vector bounds")
})?;
let b_end = b
.offset
.checked_add(b.length)
.ok_or_else(|| LuceneError::illegal_argument("offset + length overflow"))?;
let b_slice = b.longs.get(b.offset..b_end).ok_or_else(|| {
LuceneError::array_index_out_of_bounds("Offset and length exceed vector bounds")
})?;
Ok(a_slice.cmp(b_slice).to_int())
}
}