• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vigna / sux-rs / 18466861223

13 Oct 2025 01:09PM UTC coverage: 65.352% (+0.01%) from 65.341%
18466861223

push

github

vigna
Sparse partial array implementation

43 of 65 new or added lines in 2 files covered. (66.15%)

1 existing line in 1 file now uncovered.

3746 of 5732 relevant lines covered (65.35%)

116528486.3 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

65.43
/src/array/partial_array.rs
1
/*
2
 * SPDX-FileCopyrightText: 2025 Sebastiano Vigna
3
 *
4
 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
5
 */
6

7
//! Immutable partial array implementations.
8

9
use crate::bits::{BitVec, BitVecOps, BitVecOpsMut};
10
use crate::dict::EliasFanoBuilder;
11
use crate::dict::elias_fano::EfDict;
12
use crate::rank_sel::Rank9;
13
use crate::traits::{RankUnchecked, SuccUnchecked};
14
use mem_dbg::*;
15

16
/// Builder for creating an immutable partial array.
17
///
18
/// The builder allows you to specify the array length and then add
19
/// (position, value) pairs. Positions must be added in strictly
20
/// increasing order.
21
///
22
/// To get a builder you can use either [new_dense] or [new_sparse].
23
#[derive(Debug, Clone, MemDbg, MemSize)]
24
pub struct PartialArrayBuilder<T, B> {
25
    builder: B,
26
    values: Vec<T>,
27
    len: usize,
28
    min_next_pos: usize,
29
}
30

31
/// Creates a new builder for a dense partial array of the given length.
32
///
33
/// A dense partial array stores a bit vector of the given length to mark
34
/// which positions contain values, and use ranking on this bit vector to
35
/// map positions to indices in a contiguous value array.
36
///
37
/// If your set of values is really sparse, consider using a
38
/// [sparse partial array](new_sparse).
39
///
40
/// # Examples
41
///
42
/// ```rust
43
/// use sux::array::partial_array;
44
///
45
/// let mut builder = partial_array::new_dense(10);
46
/// builder.set(1, "foo");
47
/// builder.set(2, "hello");
48
/// builder.set(7, "world");
49
///
50
/// let array = builder.build();
51
/// assert_eq!(array.get(1), Some(&"foo"));
52
/// assert_eq!(array.get(2), Some(&"hello"));
53
/// assert_eq!(array.get(3), None);
54
/// assert_eq!(array.get(7), Some(&"world"));
55
/// ```
56
pub fn new_dense<T>(len: usize) -> PartialArrayBuilder<T, BitVec<Box<[usize]>>> {
6✔
57
    PartialArrayBuilder {
58
        builder: BitVec::new(len).into(),
24✔
59
        values: vec![],
6✔
60
        len,
61
        min_next_pos: 0,
62
    }
63
}
64

65
impl<T> PartialArrayBuilder<T, BitVec<Box<[usize]>>> {
66
    /// Sets a value at the given position.
67
    ///
68
    /// The provided position must be greater than the last position set.
69
    pub fn set(&mut self, position: usize, value: T) {
7✔
70
        if position < self.min_next_pos {
7✔
71
            panic!(
1✔
72
                "Positions must be set in increasing order: got {} after {}",
×
73
                position,
×
74
                self.min_next_pos - 1
×
75
            );
76
        }
77
        if position >= self.len {
6✔
78
            panic!(
1✔
79
                "Position {} is out of bounds for array of len {}",
1✔
NEW
80
                position, self.len
×
81
            );
82
        }
83
        // SAFETY: position < len
84
        unsafe {
NEW
85
            self.builder.set_unchecked(position, true);
×
86
        }
87
        self.values.push(value);
×
88
        self.min_next_pos = position + 1;
×
89
    }
90

91
    /// Builds the immutable dense partial array.
92
    pub fn build(self) -> PartialArray<T, Rank9<BitVec<Box<[usize]>>>> {
4✔
93
        let (bit_vec, values) = (self.builder, self.values);
12✔
94
        let rank9 = Rank9::new(bit_vec);
12✔
95
        let values = values.into_boxed_slice();
12✔
96

97
        PartialArray {
98
            index: rank9,
99
            values,
100
        }
101
    }
102
}
103

104
/// Creates a new builder for a sparse partial array of the given length.
105
///
106
/// A sparse partial array stores the non-empty positions of the array in an
107
/// [Elias-Fano](crate::dict::EliasFano) structure.
108
///
109
/// If your set of values is really dense, consider using a [dense partial
110
/// array](new_dense).
111
///
112
/// # Examples
113
///
114
/// ```rust
115
/// use sux::array::partial_array;
116
///
117
/// let mut builder = partial_array::new_sparse(10, 3);
118
/// builder.set(1, "foo");
119
/// builder.set(2, "hello");
120
/// builder.set(7, "world");
121
///
122
/// let array = builder.build();
123
/// assert_eq!(array.get(1), Some(&"foo"));
124
/// assert_eq!(array.get(2), Some(&"hello"));
125
/// assert_eq!(array.get(3), None);
126
/// assert_eq!(array.get(7), Some(&"world"));
127
/// ```
128
///
129
/// Note that you must specify the number of values in advance.
130
pub fn new_sparse<T>(len: usize, num_values: usize) -> PartialArrayBuilder<T, EliasFanoBuilder> {
6✔
131
    dbg!(len, num_values);
18✔
132

133
    PartialArrayBuilder {
134
        builder: EliasFanoBuilder::new(num_values, len).into(),
30✔
135
        values: vec![],
6✔
136
        len,
137
        min_next_pos: 0,
138
    }
139
}
140

141
impl<T> PartialArrayBuilder<T, EliasFanoBuilder> {
142
    /// Sets a value at the given position.
143
    ///
144
    /// The provided position must be greater than the last position
145
    /// set.
146
    pub fn set(&mut self, position: usize, value: T) {
7✔
147
        dbg!(position);
14✔
148
        if position < self.min_next_pos {
7✔
149
            panic!(
1✔
NEW
150
                "Positions must be set in increasing order: got {} after {}",
×
NEW
151
                position,
×
NEW
152
                self.min_next_pos - 1
×
153
            );
154
        }
155
        if position >= self.len {
6✔
156
            panic!(
1✔
157
                "Position {} is out of bounds for array of len {}",
1✔
NEW
158
                position, self.len
×
159
            );
160
        }
161
        // SAFETY: conditions have been just checked.
NEW
162
        unsafe { self.builder.push_unchecked(position) };
×
NEW
163
        self.values.push(value);
×
NEW
164
        self.min_next_pos = position + 1;
×
165
    }
166

167
    /// Builds the immutable sparse partial array.
168
    pub fn build(self) -> PartialArray<T, (EfDict, usize)> {
4✔
169
        let (builder, values) = (self.builder, self.values);
12✔
170
        let ef_dict = builder.build_with_dict();
12✔
171
        let values = values.into_boxed_slice();
12✔
172

173
        PartialArray {
174
            index: (ef_dict, self.min_next_pos),
4✔
175
            values,
176
        }
177
    }
178
}
179

180
/// Extends the builder with an iterator of (position, value) pairs.
181
///
182
/// Position must be in strictly increasing order. The first returned
183
/// position must be greater than the last position set.
184
impl<T> Extend<(usize, T)> for PartialArrayBuilder<T, BitVec<Box<[usize]>>> {
185
    fn extend<I: IntoIterator<Item = (usize, T)>>(&mut self, iter: I) {
×
186
        for (pos, val) in iter {
×
187
            self.set(pos, val);
×
188
        }
189
    }
190
}
191

192
/// Extends the builder with an iterator of (position, value) pairs.
193
///
194
/// Position must be in strictly increasing order. The first returned
195
/// position must be greater than the last position set.
196
impl<T> Extend<(usize, T)> for PartialArrayBuilder<T, EliasFanoBuilder> {
NEW
197
    fn extend<I: IntoIterator<Item = (usize, T)>>(&mut self, iter: I) {
×
NEW
198
        for (pos, val) in iter {
×
NEW
199
            self.set(pos, val);
×
200
        }
201
    }
202
}
203

204
/// An immutable partial array that supports efficient queries
205
/// in compacted storage.
206
///
207
/// This structure stores a *partial array*—an array in which only
208
/// some positions contain values. There is a [dense](new_dense)
209
/// and a [sparse](new_sparse) implementation with different
210
/// space/time trade-offs.
211
///
212
/// See [`PartialArrayBuilder`] for details on how to create a partial array.
213
#[derive(Debug, Clone, MemDbg, MemSize)]
214
#[cfg_attr(feature = "epserde", derive(epserde::Epserde))]
215
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
216
pub struct PartialArray<T, P> {
217
    index: P,
218
    values: Box<[T]>,
219
}
220

221
impl<T, P> PartialArray<T, P> {
222
    /// Returns the number of values stored in the array.
223
    #[inline(always)]
224
    pub fn num_values(&self) -> usize {
6✔
225
        self.values.len()
12✔
226
    }
227
}
228

229
impl<T> PartialArray<T, Rank9<BitVec<Box<[usize]>>>> {
230
    /// Returns the total length of the array.
231
    ///
232
    /// This is the length that was specified when creating the builder,
233
    /// not the number of values actually stored.
234
    #[inline(always)]
235
    pub fn len(&self) -> usize {
6✔
236
        self.index.len()
12✔
237
    }
238

239
    /// Returns true if the array length is 0.
240
    #[inline(always)]
241
    pub fn is_empty(&self) -> bool {
1✔
242
        self.len() == 0
1✔
243
    }
244

245
    /// Gets a reference to the value at the given position.
246
    ///
247
    /// Returns `Some(&value)` if a value is present at the position,
248
    /// or `None` if no value was stored there.
249
    ///
250
    /// # Examples
251
    ///
252
    /// ```rust
253
    /// use sux::array::partial_array;
254
    /// let mut builder = partial_array::new_dense(10);
255
    /// builder.set(5, 42);
256
    ///
257
    /// let array = builder.build();
258
    /// assert_eq!(array.get(5), Some(&42));
259
    /// assert_eq!(array.get(6), None);
260
    /// ```
261
    pub fn get(&self, position: usize) -> Option<&T> {
1,011✔
262
        if position >= self.len() {
2,022✔
263
            panic!(
1✔
NEW
264
                "Position {} is out of bounds for array of len {}",
×
NEW
265
                position,
×
NEW
266
                self.len()
×
267
            );
268
        }
269
        // Check if there's a value at this position
270
        // SAFETY: position < len()
271
        if !unsafe { self.index.get_unchecked(position) } {
2,020✔
272
            return None;
1,006✔
273
        }
274

275
        // Use ranking to find the index in the values array
276
        // SAFETY: position < len()
277
        let value_index = unsafe { self.index.rank_unchecked(position) };
16✔
278

279
        // SAFETY: necessarily value_index < num_values().
280
        Some(unsafe { self.values.get_unchecked(value_index) })
8✔
281
    }
282
}
283

284
impl<T> PartialArray<T, (EfDict, usize)> {
285
    /// Returns the total length of the array.
286
    ///
287
    /// This is the length that was specified when creating the builder,
288
    /// not the number of values actually stored.
289
    #[inline(always)]
290
    pub fn len(&self) -> usize {
5✔
291
        self.index.0.upper_bound()
10✔
292
    }
293

294
    /// Returns true if the array len is 0.
295
    #[inline(always)]
296
    pub fn is_empty(&self) -> bool {
1✔
297
        self.index.0.len() == 0
1✔
298
    }
299

300
    /// Gets a reference to the value at the given position.
301
    ///
302
    /// Returns `Some(&value)` if a value is present at the position,
303
    /// or `None` if no value was stored there.
304
    ///
305
    /// # Examples
306
    ///
307
    /// ```rust
308
    /// use sux::array::partial_array;
309
    /// let mut builder = partial_array::new_sparse(10, 1);
310
    /// builder.set(5, 42);
311
    ///
312
    /// let array = builder.build();
313
    /// assert_eq!(array.get(5), Some(&42));
314
    /// assert_eq!(array.get(6), None);
315
    /// ```
316
    pub fn get(&self, position: usize) -> Option<&T> {
1,011✔
317
        if position >= self.index.1 {
1,011✔
318
            if position >= self.len() {
1,004✔
319
                panic!(
1✔
NEW
320
                    "Position {} is out of bounds for array of len {}",
×
NEW
321
                    position,
×
NEW
322
                    self.len()
×
323
                );
324
            }
325
            return None;
501✔
326
        }
327
        // Check if there's a value at this position
328
        // SAFETY: position <= last set position
NEW
329
        let (index, pos) = unsafe { self.index.0.succ_unchecked::<false>(position) };
×
330

NEW
331
        return if pos != position {
×
332
            None
505✔
333
        } else {
334
            // SAFETY: necessarily value_index < num values.
335
            Some(unsafe { self.values.get_unchecked(index) })
4✔
336
        };
337
    }
338
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc