Skip to main content

columnar/
sums.rs

1//! Containers for enumerations ("sum types") that store variants separately.
2//!
3//! The main work of these types is storing a discriminant and index efficiently,
4//! as containers for each of the variant types can hold the actual data.
5
6/// Stores for maintaining discriminants, and associated sequential indexes.
7///
8/// The sequential indexes are not explicitly maintained, but are supported
9/// by a `rank(index)` function that indicates how many of a certain variant
10/// precede the given index. While this could potentially be done with a scan
11/// of all preceding discriminants, the stores maintain running accumulations
12/// that make the operation constant time (using additional amortized memory).
13pub mod rank_select {
14
15    use alloc::{vec::Vec, string::String};
16    use crate::primitive::Bools;
17
18    use crate::{Borrow, Len, Index, IndexAs, Push, Clear};
19
20    /// Number of 64-bit words per cumulative-popcount chunk. Smaller values
21    /// reduce the worst-case word scan in `select` (and the catch-up scan
22    /// in `rank`) at the cost of more `counts` entries (~6% overhead per
23    /// halving). 16 → 1024 bits/chunk is the historical default; 8 → 512
24    /// bits gives faster random `select` for ~12% counts memory.
25    const WORDS_PER_CHUNK: usize = 16;
26    const BITS_PER_CHUNK: usize = 64 * WORDS_PER_CHUNK;
27
28    /// A store for maintaining `Vec<bool>` with fast `rank` and `select` access.
29    ///
30    /// The design is to have `u64` running counts for each block of 1024 bits,
31    /// which are roughly the size of a cache line. This is roughly 6% overhead,
32    /// above the bits themselves, which seems pretty solid.
33    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34    #[derive(Copy, Clone, Debug, Default, PartialEq)]
35    pub struct RankSelect<CC = Vec<u64>, VC = Vec<u64>, WC = [u64; 2]> {
36        /// Counts of the number of cumulative set (true) bits, *after* each block of 1024 bits.
37        pub counts: CC,
38        /// The bits themselves.
39        pub values: Bools<VC, WC>,
40    }
41
42    impl<CC: crate::common::BorrowIndexAs<u64>, VC: crate::common::BorrowIndexAs<u64>> RankSelect<CC, VC> {
43        #[inline(always)]
44        pub fn borrow<'a>(&'a self) -> RankSelect<CC::Borrowed<'a>, VC::Borrowed<'a>, &'a [u64]> {
45            RankSelect {
46                counts: self.counts.borrow(),
47                values: self.values.borrow(),
48            }
49        }
50        #[inline(always)]
51        pub fn reborrow<'b, 'a: 'b>(thing: RankSelect<CC::Borrowed<'a>, VC::Borrowed<'a>, &'a [u64]>) -> RankSelect<CC::Borrowed<'b>, VC::Borrowed<'b>, &'b [u64]> {
52            RankSelect {
53                counts: CC::reborrow(thing.counts),
54                values: Bools::<VC, [u64; 2]>::reborrow(thing.values),
55            }
56        }
57    }
58
59    impl<'a, CC: crate::AsBytes<'a>, VC: crate::AsBytes<'a>> crate::AsBytes<'a> for RankSelect<CC, VC, &'a [u64]> {
60        const SLICE_COUNT: usize = CC::SLICE_COUNT + <Bools<VC, &'a [u64]> as crate::AsBytes<'a>>::SLICE_COUNT;
61        #[inline]
62        fn get_byte_slice(&self, index: usize) -> (u64, &'a [u8]) {
63            debug_assert!(index < Self::SLICE_COUNT);
64            if index < CC::SLICE_COUNT {
65                self.counts.get_byte_slice(index)
66            } else {
67                self.values.get_byte_slice(index - CC::SLICE_COUNT)
68            }
69        }
70    }
71    impl<'a, CC: crate::FromBytes<'a>, VC: crate::FromBytes<'a>> crate::FromBytes<'a> for RankSelect<CC, VC, &'a [u64]> {
72        const SLICE_COUNT: usize = CC::SLICE_COUNT + <crate::primitive::Bools<VC, &'a [u64]>>::SLICE_COUNT;
73        #[inline(always)]
74        fn from_bytes(bytes: &mut impl Iterator<Item=&'a [u8]>) -> Self {
75            Self {
76                counts: crate::FromBytes::from_bytes(bytes),
77                values: crate::FromBytes::from_bytes(bytes),
78            }
79        }
80        #[inline(always)]
81        fn from_store(store: &crate::bytes::indexed::DecodedStore<'a>, offset: &mut usize) -> Self {
82            Self {
83                counts: CC::from_store(store, offset),
84                values: <crate::primitive::Bools<VC, &'a [u64]>>::from_store(store, offset),
85            }
86        }
87        #[inline(always)]
88        fn element_sizes(sizes: &mut Vec<usize>) -> Result<(), String> {
89            CC::element_sizes(sizes)?;
90            <crate::primitive::Bools<VC, &'a [u64]>>::element_sizes(sizes)?;
91            Ok(())
92        }
93    }
94
95
96    impl<CC, VC: Len + IndexAs<u64>, WC: IndexAs<u64>> RankSelect<CC, VC, WC> {
97        #[inline(always)]
98        pub fn get(&self, index: usize) -> bool {
99            Index::get(&self.values, index)
100        }
101    }
102    impl<CC: Len + IndexAs<u64>, VC: Len + IndexAs<u64>, WC: IndexAs<u64>> RankSelect<CC, VC, WC> {
103        /// The number of set bits *strictly* preceding `index`.
104        ///
105        /// This number is accumulated first by reading out of `self.counts` at the correct position,
106        /// then by summing the ones in strictly prior `u64` entries, then by counting the ones in the
107        /// masked `u64` in which the bit lives.
108        pub fn rank(&self, index: usize) -> usize {
109            let bit = index % 64;
110            let block = index / 64;
111            let chunk = block / WORDS_PER_CHUNK;
112            let mut count = if chunk > 0 { self.counts.index_as(chunk - 1) as usize } else { 0 };
113            for pos in (WORDS_PER_CHUNK * chunk) .. block {
114                count += self.values.values.index_as(pos).count_ones() as usize;
115            }
116            // TODO: Panic if out of bounds?
117            let intra_word = if block == self.values.values.len() { self.values.tail.index_as(0) } else { self.values.values.index_as(block) };
118            count += (intra_word & ((1 << bit) - 1)).count_ones() as usize;
119            count
120        }
121        /// The position of the `rank`-th set bit (0-indexed), if it exists.
122        ///
123        /// `select(0)` returns the position of the first set bit. In general,
124        /// `select(rank(p)) == p` when `p` is the position of a set bit, mirroring
125        /// the convention of [`Self::rank`] (which counts bits strictly before
126        /// its argument).
127        #[inline]
128        pub fn select(&self, rank: u64) -> Option<usize> {
129            // Step one: find the BITS_PER_CHUNK-bit chunk containing the rank-th set bit.
130            // We want the smallest `chunk` for which `counts[chunk] > rank` — the
131            // chunk whose cumulative count first exceeds `rank`. Equivalent to a
132            // partition point over `counts` on the predicate `counts[i] <= rank`.
133            let chunk = {
134                let mut lo = 0;
135                let mut hi = self.counts.len();
136                while lo < hi {
137                    let mid = lo + (hi - lo) / 2;
138                    if self.counts.index_as(mid) <= rank { lo = mid + 1; } else { hi = mid; }
139                }
140                lo
141            };
142            // Number of set bits strictly before `chunk`'s BITS_PER_CHUNK bits.
143            let mut count = if chunk > 0 { self.counts.index_as(chunk - 1) } else { 0 };
144
145            // Step two: find the 64-bit word within `chunk` containing the rank-th set bit.
146            let mut block = WORDS_PER_CHUNK * chunk;
147            while block < self.values.values.len() {
148                let pop = self.values.values.index_as(block).count_ones() as u64;
149                if count + pop > rank { break; }
150                count += pop;
151                block += 1;
152            }
153
154            // Step three: locate the bit within the chosen word, or return `None`
155            // if `rank` is past the total set-bit count.
156            let (last_word, last_bits) = if block == self.values.values.len() {
157                (self.values.tail.index_as(0), self.values.tail.index_as(1) as usize)
158            } else {
159                (self.values.values.index_as(block), 64)
160            };
161            // Mask off any padding past the last valid bit (only relevant for the tail).
162            let masked = if last_bits == 64 { last_word } else { last_word & ((1u64 << last_bits) - 1) };
163            let k = (rank - count) as u32;
164            let shift = select_in_word(masked, k);
165            if shift >= last_bits as u32 { None } else { Some(64 * block + shift as usize) }
166        }
167    }
168
169    /// Position of the `k`-th set bit (0-indexed) within a 64-bit word. Returns 64 if
170    /// the word has fewer than `k + 1` set bits. Portable, ~6 conditional shifts based
171    /// on byte/half popcounts — independent of bit density, unlike a linear scan.
172    #[inline]
173    fn select_in_word(mut w: u64, mut k: u32) -> u32 {
174        if k >= w.count_ones() { return 64; }
175        let mut pos = 0u32;
176        // Halve the search range repeatedly. At each step, popcount of the low half
177        // tells us whether the k-th bit is in the low half (recurse) or the high half
178        // (subtract that count and shift).
179        let pop = (w & 0xFFFF_FFFF).count_ones();
180        if k >= pop { k -= pop; pos += 32; w >>= 32; }
181        let pop = (w & 0xFFFF).count_ones();
182        if k >= pop { k -= pop; pos += 16; w >>= 16; }
183        let pop = (w & 0xFF).count_ones();
184        if k >= pop { k -= pop; pos += 8; w >>= 8; }
185        let pop = (w & 0xF).count_ones();
186        if k >= pop { k -= pop; pos += 4; w >>= 4; }
187        let pop = (w & 0x3).count_ones();
188        if k >= pop { k -= pop; pos += 2; w >>= 2; }
189        let pop = w & 0x1;
190        if (k as u64) >= pop { pos += 1; }
191        pos
192    }
193
194    /// Forward cursor over a [`RankSelect`].
195    ///
196    /// Use this instead of repeated `rank`/`select` calls when you want to traverse
197    /// the bitvector in order. The cursor caches a current word and running rank,
198    /// so a single word load serves many subsequent operations — no re-probing
199    /// `counts` or rescanning words.
200    ///
201    /// At a high level the cursor maintains an *invariant pair* (`pos`, `rank`):
202    /// `pos` is the next bit to consider, and `rank` is the number of 1-bits in
203    /// `[0, pos)`. Every operation maintains this pair so that callers can read
204    /// either coordinate freely.
205    ///
206    /// Pick the method that matches the question you want to answer:
207    ///
208    /// | Operation         | Use when you want…                                        |
209    /// |-------------------|-----------------------------------------------------------|
210    /// | [`next_one`][n1]  | "Where is the next 1-bit?" — emits 1-bit positions in order. |
211    /// | [`step`][s]       | "What is the bit at the current position?" — read-by-bit traversal. |
212    /// | [`seek_to_pos`][stp] | "Jump to bit position p; what is its rank?" — random forward seek. |
213    /// | [`seek_to_rank`][str] | "Jump to the k-th 1-bit; where is it?" — equivalent to `select`. |
214    ///
215    /// The cursor is **forward-only**: every operation advances `pos` and `rank`
216    /// monotonically. Trying to seek backward triggers a debug-assertion failure.
217    ///
218    /// [n1]: Cursor::next_one
219    /// [s]: Cursor::step
220    /// [stp]: Cursor::seek_to_pos
221    /// [str]: Cursor::seek_to_rank
222    pub struct Cursor<'a, CC, VC, WC> {
223        rs: &'a RankSelect<CC, VC, WC>,
224        /// Index of the current 64-bit word within `values` (or `== values.len()` for tail).
225        word_idx: usize,
226        /// 1-bits remaining in the current word at positions ≥ `bit_pos % 64`.
227        /// Bits at positions strictly below `bit_pos % 64` are cleared.
228        word_remaining: u64,
229        /// Position of the next bit to consider.
230        bit_pos: usize,
231        /// Number of 1-bits in `[0, bit_pos)`.
232        rank: u64,
233        /// Cached total bit count of the underlying RankSelect.
234        total_bits: usize,
235    }
236
237    impl<CC: Len + IndexAs<u64>, VC: Len + IndexAs<u64>, WC: IndexAs<u64>> RankSelect<CC, VC, WC> {
238        /// Create a forward cursor positioned at bit 0.
239        pub fn cursor(&self) -> Cursor<'_, CC, VC, WC> {
240            let total_bits = self.len();
241            let mut c = Cursor {
242                rs: self,
243                word_idx: 0,
244                word_remaining: 0,
245                bit_pos: 0,
246                rank: 0,
247                total_bits,
248            };
249            c.load_word();
250            c
251        }
252    }
253
254    impl<'a, CC: Len + IndexAs<u64>, VC: Len + IndexAs<u64>, WC: IndexAs<u64>> Cursor<'a, CC, VC, WC> {
255        /// Position of the next bit to consider.
256        #[inline] pub fn pos(&self) -> usize { self.bit_pos }
257        /// Number of 1-bits strictly before `pos()`.
258        #[inline] pub fn rank(&self) -> u64 { self.rank }
259        /// Total number of bits in the underlying vector.
260        #[inline] pub fn total_bits(&self) -> usize { self.total_bits }
261
262        /// Load the word at `self.word_idx`, masked to its valid bits, and align
263        /// `bit_pos` to the start of that word. No-op past the end.
264        fn load_word(&mut self) {
265            let vlen = self.rs.values.values.len();
266            if self.word_idx < vlen {
267                self.word_remaining = self.rs.values.values.index_as(self.word_idx);
268                self.bit_pos = self.word_idx * 64;
269            } else if self.word_idx == vlen {
270                let raw = self.rs.values.tail.index_as(0);
271                let valid = self.rs.values.tail.index_as(1);
272                let mask = if valid >= 64 { !0u64 } else if valid == 0 { 0 } else { (1u64 << valid) - 1 };
273                self.word_remaining = raw & mask;
274                self.bit_pos = self.word_idx * 64;
275            } else {
276                self.word_remaining = 0;
277            }
278        }
279
280        /// Emit the next 1-bit position in order; advance past it.
281        ///
282        /// Equivalent to `select(self.rank())` followed by stepping one past that
283        /// position, but amortized: a single word load serves up to 64 results.
284        ///
285        /// **Use this for streaming through every set bit.** The canonical example
286        /// is recovering monotone Vecs bounds from an RS-encoded unary bitvector:
287        /// each call returns the next bound's bit position, no per-call re-probing
288        /// of `counts`. Returns `None` once all set bits have been emitted.
289        pub fn next_one(&mut self) -> Option<usize> {
290            loop {
291                if self.word_remaining != 0 {
292                    let bit_in_word = self.word_remaining.trailing_zeros() as usize;
293                    let pos = self.word_idx * 64 + bit_in_word;
294                    self.word_remaining &= self.word_remaining - 1;
295                    self.bit_pos = pos + 1;
296                    self.rank += 1;
297                    return Some(pos);
298                }
299                if self.bit_pos >= self.total_bits { return None; }
300                self.word_idx += 1;
301                self.load_word();
302                if self.word_idx > self.rs.values.values.len() { return None; }
303            }
304        }
305
306        /// Advance one bit. Return its value: `Some(true)` for 1, `Some(false)` for 0,
307        /// or `None` if past the end.
308        ///
309        /// **Use this when you need to visit every bit in order, regardless of value.**
310        /// Common pattern: the lookup-walk loop in a hash table that probes consecutive
311        /// slots, deciding what to do based on whether each slot is occupied. Each
312        /// call is a single bit-test + an occasional word-boundary crossing.
313        pub fn step(&mut self) -> Option<bool> {
314            if self.bit_pos >= self.total_bits { return None; }
315            let bit_in_word = self.bit_pos & 63;
316            let is_one = (self.word_remaining >> bit_in_word) & 1 == 1;
317            if is_one {
318                self.word_remaining &= !(1u64 << bit_in_word);
319                self.rank += 1;
320            }
321            self.bit_pos += 1;
322            if (self.bit_pos & 63) == 0 && self.bit_pos < self.total_bits {
323                self.word_idx += 1;
324                self.load_word();
325            }
326            Some(is_one)
327        }
328
329        /// Jump forward to bit position `target` and report its `rank` (via the
330        /// cursor's state) without consuming the bit there.
331        ///
332        /// After return, `pos() == target` and `rank() == rank(target)` (the count
333        /// of 1-bits strictly before `target`). A subsequent [`step`][Self::step]
334        /// reads the bit *at* `target`.
335        ///
336        /// **Use this when you have a known target position and want to read or
337        /// continue from there.** Typical use is hash-table lookup: a query's slot
338        /// position is computed from its hash; you want to jump there and then
339        /// walk forward through the probe chain.
340        ///
341        /// Fast path: if `target` lies within the cursor's current word, this is a
342        /// popcount + mask. Otherwise it pays one `RankSelect::rank` call to
343        /// re-anchor.
344        ///
345        /// `target` must be `>= self.pos()` (forward-only; debug-asserts otherwise).
346        /// Returns `false` if `target` is past the end of the bitvector.
347        pub fn seek_to_pos(&mut self, target: usize) -> bool {
348            debug_assert!(target >= self.bit_pos, "seek_to_pos is forward-only");
349            if target >= self.total_bits {
350                self.bit_pos = self.total_bits;
351                self.word_remaining = 0;
352                return false;
353            }
354            let target_word = target / 64;
355            if target_word == self.word_idx {
356                // Same word: count 1-bits we skip past, then mask the word.
357                let cur_bit = (self.bit_pos & 63) as u32;
358                let tgt_bit = (target & 63) as u32;
359                let skipped_mask = if tgt_bit == 64 { !0u64 } else { (1u64 << tgt_bit) - 1 };
360                let skipped = self.word_remaining & skipped_mask;
361                self.rank += skipped.count_ones() as u64;
362                // Clear consumed low bits (positions < target).
363                self.word_remaining &= !skipped_mask;
364                let _ = cur_bit;
365                self.bit_pos = target;
366                return true;
367            }
368            // Different word: re-anchor rank via the standard rank() formula, then
369            // load the target word and mask off bits below `target`.
370            self.rank = self.rs.rank(target) as u64;
371            self.word_idx = target_word;
372            self.load_word();
373            let tgt_bit = target & 63;
374            let mask = if tgt_bit == 0 { !0u64 } else { !((1u64 << tgt_bit) - 1) };
375            self.word_remaining &= mask;
376            self.bit_pos = target;
377            true
378        }
379
380        /// Jump forward to the `target`-th set bit (0-indexed) and return its
381        /// position. Equivalent to [`RankSelect::select`] for the cursor's
382        /// current state.
383        ///
384        /// After return, `rank() == target + 1` (the target bit has been consumed).
385        ///
386        /// **Use this when you have a target rank and want the position.** Typical
387        /// use is "give me bound[k]" against an RS-encoded Vecs-bounds bitvector,
388        /// possibly skipping forward over a stretch of consecutive bounds you
389        /// don't care about.
390        ///
391        /// Fast path: if the target's bit lies within the cursor's current word,
392        /// this is a `select_in_word` + bit-clear. Otherwise it pays a binary
393        /// search over `counts`, mirroring `RankSelect::select`.
394        ///
395        /// `target` must be `>= self.rank()` (forward-only; debug-asserts otherwise).
396        /// Returns `None` if there are fewer than `target + 1` set bits in total.
397        pub fn seek_to_rank(&mut self, target: u64) -> Option<usize> {
398            debug_assert!(target >= self.rank, "seek_to_rank is forward-only");
399            // Cheap path: target is within the current word's remaining 1-bits.
400            let here_pop = self.word_remaining.count_ones() as u64;
401            if target < self.rank + here_pop {
402                let k = (target - self.rank) as u32;
403                let bit_in_word = select_in_word(self.word_remaining, k) as usize;
404                let pos = self.word_idx * 64 + bit_in_word;
405                // Consume up to and including the target bit: clear the lowest k+1 set bits.
406                let mut w = self.word_remaining;
407                for _ in 0..=k { w &= w.wrapping_sub(1); }
408                self.word_remaining = w;
409                self.rank = target + 1;
410                self.bit_pos = pos + 1;
411                return Some(pos);
412            }
413            // Otherwise: jump via chunk binary search, mirroring `select`.
414            let counts = &self.rs.counts;
415            let chunk = {
416                let mut lo = 0;
417                let mut hi = counts.len();
418                while lo < hi {
419                    let mid = lo + (hi - lo) / 2;
420                    if counts.index_as(mid) <= target { lo = mid + 1; } else { hi = mid; }
421                }
422                lo
423            };
424            let mut count = if chunk > 0 { counts.index_as(chunk - 1) } else { 0 };
425            let vlen = self.rs.values.values.len();
426            let mut block = WORDS_PER_CHUNK * chunk;
427            while block < vlen {
428                let pop = self.rs.values.values.index_as(block).count_ones() as u64;
429                if count + pop > target { break; }
430                count += pop;
431                block += 1;
432            }
433            self.word_idx = block;
434            self.load_word();
435            self.rank = count;
436            // Now finish within the freshly loaded word.
437            if target >= count + self.word_remaining.count_ones() as u64 {
438                // Exhausted.
439                self.bit_pos = self.total_bits;
440                self.word_remaining = 0;
441                return None;
442            }
443            let k = (target - count) as u32;
444            let bit_in_word = select_in_word(self.word_remaining, k) as usize;
445            let pos = self.word_idx * 64 + bit_in_word;
446            let mut w = self.word_remaining;
447            for _ in 0..=k { w &= w.wrapping_sub(1); }
448            self.word_remaining = w;
449            self.rank = target + 1;
450            self.bit_pos = pos + 1;
451            Some(pos)
452        }
453    }
454
455    impl<CC, VC: Len, WC: IndexAs<u64>> RankSelect<CC, VC, WC> {
456        pub fn len(&self) -> usize {
457            self.values.len()
458        }
459    }
460
461    // This implementation probably only works for `Vec<u64>` and `Vec<u64>`, but we could fix that.
462    // Partly, it's hard to name the `Index` flavor that allows one to get back a `u64`.
463    impl<CC: for<'a> Push<&'a u64> + Len + IndexAs<u64>, VC: for<'a> Push<&'a u64> + Len + IndexAs<u64>> RankSelect<CC, VC> {
464        #[inline]
465        pub fn push(&mut self, bit: bool) {
466            self.values.push(&bit);
467            while self.counts.len() < self.values.len() / BITS_PER_CHUNK {
468                let mut count = self.counts.last().unwrap_or(0);
469                let lower = WORDS_PER_CHUNK * self.counts.len();
470                let upper = lower + WORDS_PER_CHUNK;
471                for i in lower .. upper {
472                    count += self.values.values.index_as(i).count_ones() as u64;
473                }
474                self.counts.push(&count);
475            }
476        }
477    }
478    impl<CC: Clear, VC: Clear> Clear for RankSelect<CC, VC> {
479        fn clear(&mut self) {
480            self.counts.clear();
481            self.values.clear();
482        }
483    }
484
485    #[cfg(test)]
486    mod tests {
487        use alloc::{vec, vec::Vec};
488        use super::RankSelect;
489
490        fn build(bits: &[bool]) -> RankSelect {
491            let mut rs: RankSelect = RankSelect::default();
492            for &b in bits { rs.push(b); }
493            rs
494        }
495
496        /// All true bits are recovered by `select(rank(p))` for every set position `p`,
497        /// and `rank` agrees with a naive count.
498        fn check_round_trip(bits: &[bool]) {
499            let rs = build(bits);
500            let mut expected = 0u64;
501            for (i, &b) in bits.iter().enumerate() {
502                assert_eq!(rs.rank(i), expected as usize, "rank({}) on pattern of len {}", i, bits.len());
503                if b {
504                    let pos = rs.select(expected).unwrap_or_else(|| panic!("select({}) returned None for set bit at {}", expected, i));
505                    assert_eq!(pos, i, "select({}) on pattern of len {}", expected, bits.len());
506                    expected += 1;
507                }
508            }
509            // Out-of-range select returns None.
510            assert!(rs.select(expected).is_none());
511        }
512
513        #[test]
514        fn select_first_bit() {
515            // Bit 0 set, nothing else.
516            let mut bits = vec![false; 2048];
517            bits[0] = true;
518            check_round_trip(&bits);
519        }
520
521        #[test]
522        fn select_small_dense() {
523            // First five bits set in a 2048-bit vector (spans two chunks).
524            let mut bits = vec![false; 2048];
525            for i in 0..5 { bits[i] = true; }
526            check_round_trip(&bits);
527        }
528
529        #[test]
530        fn select_chunk_boundary() {
531            // Set bits exactly at the chunk boundary positions 1023 and 1024.
532            let mut bits = vec![false; 4096];
533            bits[1023] = true;
534            bits[1024] = true;
535            check_round_trip(&bits);
536        }
537
538        #[test]
539        fn select_in_tail() {
540            // Bits 0..3 set, then nothing through bit 1100. Pattern length 1100 puts
541            // the final bits in the tail (not a complete 1024-bit chunk).
542            let mut bits = vec![false; 1100];
543            bits[0] = true;
544            bits[1099] = true;
545            check_round_trip(&bits);
546        }
547
548        #[test]
549        fn select_every_other() {
550            // Dense, multiple chunks.
551            let bits: Vec<bool> = (0..3000).map(|i| i % 2 == 0).collect();
552            check_round_trip(&bits);
553        }
554
555        #[test]
556        fn select_sparse_multi_chunk() {
557            // One set bit per 1024-bit chunk, six chunks.
558            let mut bits = vec![false; 6 * 1024];
559            for c in 0..6 { bits[1024 * c + 17] = true; }
560            check_round_trip(&bits);
561        }
562
563        #[test]
564        fn select_out_of_range() {
565            let rs = build(&[true, false, true]);
566            assert_eq!(rs.select(0), Some(0));
567            assert_eq!(rs.select(1), Some(2));
568            assert_eq!(rs.select(2), None);
569            assert_eq!(rs.select(1000), None);
570        }
571
572        #[test]
573        fn cursor_next_one_matches_select() {
574            // For each set bit in a 3000-bit pattern, walking next_one gives the
575            // same positions as repeated select calls.
576            let bits: Vec<bool> = (0..3000).map(|i| i % 7 == 0).collect();
577            let rs = build(&bits);
578            let mut cur = rs.cursor();
579            let mut k = 0u64;
580            while let Some(pos) = cur.next_one() {
581                assert_eq!(Some(pos), rs.select(k));
582                assert_eq!(cur.rank(), k + 1);
583                assert_eq!(cur.pos(), pos + 1);
584                k += 1;
585            }
586            assert_eq!(k, rs.rank(rs.len()) as u64);
587        }
588
589        #[test]
590        fn cursor_step_walks_every_bit() {
591            let bits: Vec<bool> = (0..2050).map(|i| i % 3 == 0).collect();
592            let rs = build(&bits);
593            let mut cur = rs.cursor();
594            let mut expected_rank = 0u64;
595            for (i, &b) in bits.iter().enumerate() {
596                assert_eq!(cur.pos(), i);
597                assert_eq!(cur.rank(), expected_rank);
598                assert_eq!(cur.step(), Some(b));
599                if b { expected_rank += 1; }
600            }
601            assert_eq!(cur.step(), None);
602        }
603
604        #[test]
605        fn cursor_seek_to_rank_skips_far_forward() {
606            // 3 chunks worth of bits, with set bits clustered. Seek directly to
607            // the 100-th set bit from a fresh cursor; result matches select(100).
608            let bits: Vec<bool> = (0..3200).map(|i| i % 3 == 1).collect();
609            let rs = build(&bits);
610            let mut cur = rs.cursor();
611            let pos = cur.seek_to_rank(100).unwrap();
612            assert_eq!(Some(pos), rs.select(100));
613            assert_eq!(cur.rank(), 101);
614            // A subsequent next_one continues correctly.
615            let next = cur.next_one().unwrap();
616            assert_eq!(Some(next), rs.select(101));
617        }
618
619        #[test]
620        fn cursor_seek_to_rank_within_current_word() {
621            // Set bits in a known pattern within the first word; cursor should
622            // satisfy seek_to_rank from the current-word fast path without re-probing.
623            let bits: Vec<bool> = (0..64).map(|i| matches!(i, 1 | 5 | 13 | 30 | 50)).collect();
624            let rs = build(&bits);
625            let mut cur = rs.cursor();
626            assert_eq!(cur.seek_to_rank(0), Some(1));
627            assert_eq!(cur.seek_to_rank(2), Some(13));
628            assert_eq!(cur.seek_to_rank(4), Some(50));
629            assert_eq!(cur.next_one(), None);
630        }
631
632        #[test]
633        fn cursor_seek_to_pos_same_word_and_cross_word() {
634            let bits: Vec<bool> = (0..256).map(|i| matches!(i % 5, 0 | 2)).collect();
635            let rs = build(&bits);
636            // Same-word seek.
637            let mut cur = rs.cursor();
638            assert!(cur.seek_to_pos(10));
639            assert_eq!(cur.pos(), 10);
640            assert_eq!(cur.rank(), rs.rank(10) as u64);
641            assert!(cur.seek_to_pos(40));
642            assert_eq!(cur.rank(), rs.rank(40) as u64);
643            // Cross-word seek.
644            assert!(cur.seek_to_pos(200));
645            assert_eq!(cur.pos(), 200);
646            assert_eq!(cur.rank(), rs.rank(200) as u64);
647            // Step reads the bit at the target.
648            assert_eq!(cur.step(), Some(bits[200]));
649        }
650
651        #[test]
652        fn cursor_seek_to_pos_out_of_range() {
653            let bits: Vec<bool> = (0..100).map(|_| true).collect();
654            let rs = build(&bits);
655            let mut cur = rs.cursor();
656            assert!(!cur.seek_to_pos(1000));
657            assert_eq!(cur.step(), None);
658        }
659
660        #[test]
661        fn cursor_seek_to_rank_out_of_range() {
662            let bits: Vec<bool> = (0..200).map(|i| i % 10 == 0).collect();
663            let rs = build(&bits);
664            let mut cur = rs.cursor();
665            assert_eq!(cur.seek_to_rank(10_000), None);
666        }
667
668        #[test]
669        fn select_in_word_basic() {
670            use super::select_in_word;
671            // 0b10110: set bits at positions 1, 2, 4.
672            assert_eq!(select_in_word(0b10110, 0), 1);
673            assert_eq!(select_in_word(0b10110, 1), 2);
674            assert_eq!(select_in_word(0b10110, 2), 4);
675            assert_eq!(select_in_word(0b10110, 3), 64);
676            // Edges of the word.
677            assert_eq!(select_in_word(1u64 << 63, 0), 63);
678            assert_eq!(select_in_word(u64::MAX, 0), 0);
679            assert_eq!(select_in_word(u64::MAX, 63), 63);
680            assert_eq!(select_in_word(u64::MAX, 64), 64);
681            assert_eq!(select_in_word(0, 0), 64);
682        }
683    }
684}
685
686pub mod result {
687
688    use alloc::{vec::Vec, string::String};
689
690    use crate::{Clear, Columnar, Container, Len, IndexMut, Index, IndexAs, Push, Borrow};
691    use crate::RankSelect;
692
693    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
694    #[derive(Copy, Clone, Debug, Default, PartialEq)]
695    pub struct Results<SC, TC, CC=Vec<u64>, VC=Vec<u64>, WC=[u64; 2]> {
696        /// Bits set to `true` correspond to `Ok` variants.
697        pub indexes: RankSelect<CC, VC, WC>,
698        pub oks: SC,
699        pub errs: TC,
700    }
701
702    impl<S: Columnar, T: Columnar> Columnar for Result<S, T> {
703        fn copy_from<'a>(&mut self, other: crate::Ref<'a, Self>) {
704            match (&mut *self, other) {
705                (Ok(x), Ok(y)) => x.copy_from(y),
706                (Err(x), Err(y)) => x.copy_from(y),
707                (_, other) => { *self = Self::into_owned(other); },
708            }
709        }
710        fn into_owned<'a>(other: crate::Ref<'a, Self>) -> Self {
711            match other {
712                Ok(y) => Ok(S::into_owned(y)),
713                Err(y) => Err(T::into_owned(y)),
714            }
715        }
716        type Container = Results<S::Container, T::Container>;
717    }
718
719    impl<SC: Borrow, TC: Borrow> Borrow for Results<SC, TC> {
720        type Ref<'a> = Result<SC::Ref<'a>, TC::Ref<'a>> where SC: 'a, TC: 'a;
721        type Borrowed<'a> = Results<SC::Borrowed<'a>, TC::Borrowed<'a>, &'a [u64], &'a [u64], &'a [u64]> where SC: 'a, TC: 'a;
722        fn borrow<'a>(&'a self) -> Self::Borrowed<'a> {
723            Results {
724                indexes: self.indexes.borrow(),
725                oks: self.oks.borrow(),
726                errs: self.errs.borrow(),
727            }
728        }
729        #[inline(always)]
730        fn reborrow<'b, 'a: 'b>(thing: Self::Borrowed<'a>) -> Self::Borrowed<'b> where SC: 'a, TC: 'a {
731            Results {
732                indexes: RankSelect::<Vec<u64>, Vec<u64>>::reborrow(thing.indexes),
733                oks: SC::reborrow(thing.oks),
734                errs: TC::reborrow(thing.errs),
735            }
736        }
737        #[inline(always)]
738        fn reborrow_ref<'b, 'a: 'b>(thing: Self::Ref<'a>) -> Self::Ref<'b> where Self: 'a {
739            match thing {
740                Ok(y) => Ok(SC::reborrow_ref(y)),
741                Err(y) => Err(TC::reborrow_ref(y)),
742            }
743        }
744    }
745
746    impl<SC: Container, TC: Container> Container for Results<SC, TC> {
747        #[inline(always)]
748        fn extend_from_self(&mut self, other: Self::Borrowed<'_>, range: core::ops::Range<usize>) {
749            if !range.is_empty() {
750                // Starting offsets of each variant in `other`.
751                let oks_start = other.indexes.rank(range.start);
752                let errs_start = range.start - oks_start;
753
754                // Count the number of `Ok` and `Err` variants as we push, to determine the range.
755                // TODO: This could probably be `popcnt` somehow.
756                let mut oks = 0;
757                for index in range.clone() {
758                    let bit = other.indexes.get(index);
759                    self.indexes.push(bit);
760                    if bit { oks += 1; }
761                }
762                let errs = range.len() - oks;
763
764                self.oks.extend_from_self(other.oks, oks_start .. oks_start + oks);
765                self.errs.extend_from_self(other.errs, errs_start .. errs_start + errs);
766            }
767        }
768
769        fn reserve_for<'a, I>(&mut self, selves: I) where Self: 'a, I: Iterator<Item = Self::Borrowed<'a>> + Clone {
770            // TODO: reserve room in `self.indexes`.
771            self.oks.reserve_for(selves.clone().map(|x| x.oks));
772            self.errs.reserve_for(selves.map(|x| x.errs));
773        }
774    }
775
776    impl<'a, SC: crate::AsBytes<'a>, TC: crate::AsBytes<'a>, CC: crate::AsBytes<'a>, VC: crate::AsBytes<'a>> crate::AsBytes<'a> for Results<SC, TC, CC, VC, &'a [u64]> {
777        const SLICE_COUNT: usize = <RankSelect<CC, VC, &'a [u64]> as crate::AsBytes<'a>>::SLICE_COUNT + SC::SLICE_COUNT + TC::SLICE_COUNT;
778        #[inline]
779        fn get_byte_slice(&self, index: usize) -> (u64, &'a [u8]) {
780            debug_assert!(index < Self::SLICE_COUNT);
781            let idx_count = <RankSelect<CC, VC, &'a [u64]> as crate::AsBytes<'a>>::SLICE_COUNT;
782            if index < idx_count {
783                self.indexes.get_byte_slice(index)
784            } else if index < idx_count + SC::SLICE_COUNT {
785                self.oks.get_byte_slice(index - idx_count)
786            } else {
787                self.errs.get_byte_slice(index - idx_count - SC::SLICE_COUNT)
788            }
789        }
790    }
791    impl<'a, SC: crate::FromBytes<'a>, TC: crate::FromBytes<'a>, CC: crate::FromBytes<'a>, VC: crate::FromBytes<'a>> crate::FromBytes<'a> for Results<SC, TC, CC, VC, &'a [u64]> {
792        const SLICE_COUNT: usize = <RankSelect<CC, VC, &'a [u64]>>::SLICE_COUNT + SC::SLICE_COUNT + TC::SLICE_COUNT;
793        #[inline(always)]
794        fn from_bytes(bytes: &mut impl Iterator<Item=&'a [u8]>) -> Self {
795            Self {
796                indexes: crate::FromBytes::from_bytes(bytes),
797                oks: crate::FromBytes::from_bytes(bytes),
798                errs: crate::FromBytes::from_bytes(bytes),
799            }
800        }
801        #[inline(always)]
802        fn from_store(store: &crate::bytes::indexed::DecodedStore<'a>, offset: &mut usize) -> Self {
803            Self {
804                indexes: crate::FromBytes::from_store(store, offset),
805                oks: SC::from_store(store, offset),
806                errs: TC::from_store(store, offset),
807            }
808        }
809        #[inline(always)]
810        fn element_sizes(sizes: &mut Vec<usize>) -> Result<(), String> {
811            <RankSelect<CC, VC, &'a [u64]>>::element_sizes(sizes)?;
812            SC::element_sizes(sizes)?;
813            TC::element_sizes(sizes)?;
814            Ok(())
815        }
816    }
817
818    impl<SC, TC, CC, VC: Len, WC: IndexAs<u64>> Len for Results<SC, TC, CC, VC, WC> {
819        #[inline(always)] fn len(&self) -> usize { self.indexes.len() }
820    }
821
822    impl<SC, TC, CC, VC, WC> Index for Results<SC, TC, CC, VC, WC>
823    where
824        SC: Index,
825        TC: Index,
826        CC: IndexAs<u64> + Len,
827        VC: IndexAs<u64> + Len,
828        WC: IndexAs<u64>,
829    {
830        type Ref = Result<SC::Ref, TC::Ref>;
831        #[inline(always)]
832        fn get(&self, index: usize) -> Self::Ref {
833            if self.indexes.get(index) {
834                Ok(self.oks.get(self.indexes.rank(index)))
835            } else {
836                Err(self.errs.get(index - self.indexes.rank(index)))
837            }
838        }
839    }
840    impl<'a, SC, TC, CC, VC, WC> Index for &'a Results<SC, TC, CC, VC, WC>
841    where
842        &'a SC: Index,
843        &'a TC: Index,
844        CC: IndexAs<u64> + Len,
845        VC: IndexAs<u64> + Len,
846        WC: IndexAs<u64>,
847    {
848        type Ref = Result<<&'a SC as Index>::Ref, <&'a TC as Index>::Ref>;
849        #[inline(always)]
850        fn get(&self, index: usize) -> Self::Ref {
851            if self.indexes.get(index) {
852                Ok((&self.oks).get(self.indexes.rank(index)))
853            } else {
854                Err((&self.errs).get(index - self.indexes.rank(index)))
855            }
856        }
857    }
858
859    // NB: You are not allowed to change the variant, but can change its contents.
860    impl<SC: IndexMut, TC: IndexMut, CC: IndexAs<u64> + Len, VC: IndexAs<u64> + Len> IndexMut for Results<SC, TC, CC, VC> {
861        type IndexMut<'a> = Result<SC::IndexMut<'a>, TC::IndexMut<'a>> where SC: 'a, TC: 'a, CC: 'a, VC: 'a;
862        #[inline(always)]
863        fn get_mut(&mut self, index: usize) -> Self::IndexMut<'_> {
864            if self.indexes.get(index) {
865                Ok(self.oks.get_mut(self.indexes.rank(index)))
866            } else {
867                Err(self.errs.get_mut(index - self.indexes.rank(index)))
868            }
869        }
870    }
871
872    impl<S, SC: Push<S>, T, TC: Push<T>> Push<Result<S, T>> for Results<SC, TC> {
873        #[inline]
874        fn push(&mut self, item: Result<S, T>) {
875            match item {
876                Ok(item) => {
877                    self.indexes.push(true);
878                    self.oks.push(item);
879                }
880                Err(item) => {
881                    self.indexes.push(false);
882                    self.errs.push(item);
883                }
884            }
885        }
886    }
887    impl<'a, S, SC: Push<&'a S>, T, TC: Push<&'a T>> Push<&'a Result<S, T>> for Results<SC, TC> {
888        #[inline]
889        fn push(&mut self, item: &'a Result<S, T>) {
890            match item {
891                Ok(item) => {
892                    self.indexes.push(true);
893                    self.oks.push(item);
894                }
895                Err(item) => {
896                    self.indexes.push(false);
897                    self.errs.push(item);
898                }
899            }
900        }
901    }
902
903    impl<SC: Clear, TC: Clear> Clear for Results<SC, TC> {
904        fn clear(&mut self) {
905            self.indexes.clear();
906            self.oks.clear();
907            self.errs.clear();
908        }
909    }
910
911    impl<SC, TC, CC, VC, WC> Results<SC, TC, CC, VC, WC> {
912        /// Returns ok values if no errors exist.
913        pub fn unwrap(self) -> SC where TC: Len {
914            assert!(self.errs.is_empty());
915            self.oks
916        }
917        /// Returns error values if no oks exist.
918        pub fn unwrap_err(self) -> TC where SC: Len {
919            assert!(self.oks.is_empty());
920            self.errs
921        }
922        /// Returns ok values if no errors exist, or `None`.
923        pub fn try_unwrap(self) -> Option<SC> where TC: Len {
924            if self.errs.is_empty() { Some(self.oks) } else { None }
925        }
926        /// Returns error values if no oks exist, or `None`.
927        pub fn try_unwrap_err(self) -> Option<TC> where SC: Len {
928            if self.oks.is_empty() { Some(self.errs) } else { None }
929        }
930    }
931    #[cfg(test)]
932    mod test {
933        #[test]
934        fn round_trip() {
935
936            use crate::common::{Index, Push, Len};
937
938            let mut column: crate::ContainerOf<Result<u64, u64>> = Default::default();
939            for i in 0..100 {
940                column.push(Ok::<u64, u64>(i));
941                column.push(Err::<u64, u64>(i));
942            }
943
944            assert_eq!(column.len(), 200);
945
946            for i in 0..100 {
947                assert_eq!(column.get(2*i+0), Ok(i as u64));
948                assert_eq!(column.get(2*i+1), Err(i as u64));
949            }
950
951            let mut column: crate::ContainerOf<Result<u64, u8>> = Default::default();
952            for i in 0..100 {
953                column.push(Ok::<u64, u8>(i as u64));
954                column.push(Err::<u64, u8>(i as u8));
955            }
956
957            assert_eq!(column.len(), 200);
958
959            for i in 0..100 {
960                assert_eq!(column.get(2*i+0), Ok(i as u64));
961                assert_eq!(column.get(2*i+1), Err(i as u8));
962            }
963        }
964    }
965}
966
967pub mod option {
968
969    use alloc::{vec::Vec, string::String};
970
971    use crate::{Clear, Columnar, Container, Len, IndexMut, Index, IndexAs, Push, Borrow};
972    use crate::RankSelect;
973
974#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
975    #[derive(Copy, Clone, Debug, Default, PartialEq)]
976    pub struct Options<TC, CC=Vec<u64>, VC=Vec<u64>, WC=[u64; 2]> {
977        /// Uses two bits for each item, one to indicate the variant and one (amortized)
978        /// to enable efficient rank determination.
979        pub indexes: RankSelect<CC, VC, WC>,
980        pub somes: TC,
981    }
982
983    impl<T: Columnar> Columnar for Option<T> {
984        fn copy_from<'a>(&mut self, other: crate::Ref<'a, Self>) {
985            match (&mut *self, other) {
986                (Some(x), Some(y)) => { x.copy_from(y); }
987                (_, other) => { *self = Self::into_owned(other); }
988            }
989        }
990        fn into_owned<'a>(other: crate::Ref<'a, Self>) -> Self {
991            other.map(|x| T::into_owned(x))
992        }
993        type Container = Options<T::Container>;
994    }
995
996    impl<TC: Borrow> Borrow for Options<TC> {
997        type Ref<'a> = Option<TC::Ref<'a>> where TC: 'a;
998        type Borrowed<'a> = Options<TC::Borrowed<'a>, &'a [u64], &'a [u64], &'a [u64]> where TC: 'a;
999        fn borrow<'a>(&'a self) -> Self::Borrowed<'a> {
1000            Options {
1001                indexes: self.indexes.borrow(),
1002                somes: self.somes.borrow(),
1003            }
1004        }
1005        #[inline(always)]
1006        fn reborrow<'b, 'a: 'b>(thing: Self::Borrowed<'a>) -> Self::Borrowed<'b> where TC: 'a {
1007            Options {
1008                indexes: RankSelect::<Vec<u64>, Vec<u64>>::reborrow(thing.indexes),
1009                somes: TC::reborrow(thing.somes),
1010            }
1011        }
1012        #[inline(always)]
1013        fn reborrow_ref<'b, 'a: 'b>(thing: Self::Ref<'a>) -> Self::Ref<'b> where Self: 'a {
1014            thing.map(TC::reborrow_ref)
1015        }
1016    }
1017
1018    impl<TC: Container> Container for Options<TC> {
1019        #[inline(always)]
1020        fn extend_from_self(&mut self, other: Self::Borrowed<'_>, range: core::ops::Range<usize>) {
1021            if !range.is_empty() {
1022                // Starting offsets of `Some` variants in `other`.
1023                let somes_start = other.indexes.rank(range.start);
1024
1025                // Count the number of `Some` variants as we push, to determine the range.
1026                // TODO: This could probably be `popcnt` somehow.
1027                let mut somes = 0;
1028                for index in range {
1029                    let bit = other.indexes.get(index);
1030                    self.indexes.push(bit);
1031                    if bit { somes += 1; }
1032                }
1033
1034                self.somes.extend_from_self(other.somes, somes_start .. somes_start + somes);
1035            }
1036        }
1037
1038        fn reserve_for<'a, I>(&mut self, selves: I) where Self: 'a, I: Iterator<Item = Self::Borrowed<'a>> + Clone {
1039            // TODO: reserve room in `self.indexes`.
1040            self.somes.reserve_for(selves.map(|x| x.somes));
1041        }
1042    }
1043
1044    impl<'a, TC: crate::AsBytes<'a>, CC: crate::AsBytes<'a>, VC: crate::AsBytes<'a>> crate::AsBytes<'a> for Options<TC, CC, VC, &'a [u64]> {
1045        const SLICE_COUNT: usize = <RankSelect<CC, VC, &'a [u64]> as crate::AsBytes<'a>>::SLICE_COUNT + TC::SLICE_COUNT;
1046        #[inline]
1047        fn get_byte_slice(&self, index: usize) -> (u64, &'a [u8]) {
1048            debug_assert!(index < Self::SLICE_COUNT);
1049            let idx_count = <RankSelect<CC, VC, &'a [u64]> as crate::AsBytes<'a>>::SLICE_COUNT;
1050            if index < idx_count {
1051                self.indexes.get_byte_slice(index)
1052            } else {
1053                self.somes.get_byte_slice(index - idx_count)
1054            }
1055        }
1056    }
1057
1058    impl <'a, TC: crate::FromBytes<'a>, CC: crate::FromBytes<'a>, VC: crate::FromBytes<'a>> crate::FromBytes<'a> for Options<TC, CC, VC, &'a [u64]> {
1059        const SLICE_COUNT: usize = <RankSelect<CC, VC, &'a [u64]>>::SLICE_COUNT + TC::SLICE_COUNT;
1060        #[inline(always)]
1061        fn from_bytes(bytes: &mut impl Iterator<Item=&'a [u8]>) -> Self {
1062            Self {
1063                indexes: crate::FromBytes::from_bytes(bytes),
1064                somes: crate::FromBytes::from_bytes(bytes),
1065            }
1066        }
1067        #[inline(always)]
1068        fn from_store(store: &crate::bytes::indexed::DecodedStore<'a>, offset: &mut usize) -> Self {
1069            Self {
1070                indexes: crate::FromBytes::from_store(store, offset),
1071                somes: TC::from_store(store, offset),
1072            }
1073        }
1074        #[inline(always)]
1075        fn element_sizes(sizes: &mut Vec<usize>) -> Result<(), String> {
1076            <RankSelect<CC, VC, &'a [u64]>>::element_sizes(sizes)?;
1077            TC::element_sizes(sizes)?;
1078            Ok(())
1079        }
1080    }
1081
1082    impl<T, CC, VC: Len, WC: IndexAs<u64>> Len for Options<T, CC, VC, WC> {
1083        #[inline(always)] fn len(&self) -> usize { self.indexes.len() }
1084    }
1085
1086    impl<TC: Index, CC: IndexAs<u64> + Len, VC: IndexAs<u64> + Len, WC: IndexAs<u64>> Index for Options<TC, CC, VC, WC> {
1087        type Ref = Option<TC::Ref>;
1088        #[inline(always)]
1089        fn get(&self, index: usize) -> Self::Ref {
1090            if self.indexes.get(index) {
1091                Some(self.somes.get(self.indexes.rank(index)))
1092            } else {
1093                None
1094            }
1095        }
1096    }
1097    impl<'a, TC, CC: IndexAs<u64> + Len, VC: IndexAs<u64> + Len, WC: IndexAs<u64>> Index for &'a Options<TC, CC, VC, WC>
1098    where &'a TC: Index
1099    {
1100        type Ref = Option<<&'a TC as Index>::Ref>;
1101        #[inline(always)]
1102        fn get(&self, index: usize) -> Self::Ref {
1103            if self.indexes.get(index) {
1104                Some((&self.somes).get(self.indexes.rank(index)))
1105            } else {
1106                None
1107            }
1108        }
1109    }
1110    impl<TC: IndexMut, CC: IndexAs<u64> + Len, VC: IndexAs<u64> + Len> IndexMut for Options<TC, CC, VC> {
1111        type IndexMut<'a> = Option<TC::IndexMut<'a>> where TC: 'a, CC: 'a, VC: 'a;
1112        #[inline(always)]
1113        fn get_mut(&mut self, index: usize) -> Self::IndexMut<'_> {
1114            if self.indexes.get(index) {
1115                Some(self.somes.get_mut(self.indexes.rank(index)))
1116            } else {
1117                None
1118            }
1119        }
1120    }
1121
1122    impl<T, TC: Push<T> + Len> Push<Option<T>> for Options<TC> {
1123        #[inline]
1124        fn push(&mut self, item: Option<T>) {
1125            match item {
1126                Some(item) => {
1127                    self.indexes.push(true);
1128                    self.somes.push(item);
1129                }
1130                None => {
1131                    self.indexes.push(false);
1132                }
1133            }
1134        }
1135    }
1136    impl<'a, T, TC: Push<&'a T> + Len> Push<&'a Option<T>> for Options<TC> {
1137        #[inline]
1138        fn push(&mut self, item: &'a Option<T>) {
1139            match item {
1140                Some(item) => {
1141                    self.indexes.push(true);
1142                    self.somes.push(item);
1143                }
1144                None => {
1145                    self.indexes.push(false);
1146                }
1147            }
1148        }
1149    }
1150
1151    impl<TC, CC, VC, WC> Options<TC, CC, VC, WC> {
1152        /// Returns the inner container if all elements are `Some`, or `None`.
1153        pub fn try_unwrap(self) -> Option<TC> where TC: Len, VC: Len, WC: IndexAs<u64> {
1154            if self.somes.len() == self.indexes.len() { Some(self.somes) } else { None }
1155        }
1156        /// True if all elements are `None`.
1157        pub fn is_all_none(&self) -> bool where TC: Len {
1158            self.somes.is_empty()
1159        }
1160    }
1161
1162    impl<TC: Clear> Clear for Options<TC> {
1163        fn clear(&mut self) {
1164            self.indexes.clear();
1165            self.somes.clear();
1166        }
1167    }
1168
1169    #[cfg(test)]
1170    mod test {
1171        use alloc::vec::Vec;
1172
1173        use crate::Columnar;
1174        use crate::common::{Index, Len};
1175        use crate::Options;
1176
1177        #[test]
1178        fn round_trip_some() {
1179            // Type annotation is important to avoid some inference overflow.
1180            let store: Options<Vec<i32>> = Columnar::into_columns((0..100).map(Some));
1181            assert_eq!(store.len(), 100);
1182            assert!((&store).index_iter().zip(0..100).all(|(a, b)| a == Some(&b)));
1183        }
1184
1185        #[test]
1186        fn round_trip_none() {
1187            let store = Columnar::into_columns((0..100).map(|_x| None::<i32>));
1188            assert_eq!(store.len(), 100);
1189            let foo = &store;
1190            assert!(foo.index_iter().zip(0..100).all(|(a, _b)| a == None));
1191        }
1192
1193        #[test]
1194        fn round_trip_mixed() {
1195            // Type annotation is important to avoid some inference overflow.
1196            let store: Options<Vec<i32>>  = Columnar::into_columns((0..100).map(|x| if x % 2 == 0 { Some(x) } else { None }));
1197            assert_eq!(store.len(), 100);
1198            assert!((&store).index_iter().zip(0..100).all(|(a, b)| a == if b % 2 == 0 { Some(&b) } else { None }));
1199        }
1200    }
1201}
1202
1203pub mod discriminant {
1204
1205    use alloc::{vec::Vec, string::String};
1206    use crate::{Clear, Container, Len, Index, IndexAs, Borrow};
1207
1208    /// Tracks variant discriminants and offsets for enum containers.
1209    ///
1210    /// Uses two arrays (`variant` and `offset`) with three states:
1211    /// - **Empty**: both arrays empty, length is 0.
1212    /// - **Homogeneous**: `variant` is empty, `offset` holds `[tag, count]` where
1213    ///   `tag = variant_index + 1`. All elements share a single variant with
1214    ///   identity offsets (element `i` maps to offset `i`).
1215    /// - **Heterogeneous**: `variant` has per-element discriminants (`u8`),
1216    ///   `offset` has per-element offsets into variant containers (`u64`).
1217    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1218    #[derive(Clone, Debug, Default, PartialEq)]
1219    pub struct Discriminant<CVar = Vec<u8>, COff = Vec<u64>> {
1220        /// Per-element variant discriminants; empty when homogeneous.
1221        pub variant: CVar,
1222        /// Per-element offsets (heterogeneous), or `[tag, count]` (homogeneous), or empty.
1223        pub offset: COff,
1224    }
1225
1226    impl<CVar: Copy, COff: Copy> Copy for Discriminant<CVar, COff> {}
1227
1228    impl Discriminant {
1229        /// Push a variant discriminant and the offset into its variant container.
1230        #[inline]
1231        pub fn push(&mut self, variant: u8, offset: u64) {
1232            let tag = variant as u64 + 1;
1233            if self.variant.is_empty() {
1234                if self.offset.is_empty() {
1235                    // Empty → start homogeneous: offset = [tag, 1].
1236                    self.offset.push(tag);
1237                    self.offset.push(1);
1238                } else if self.offset[0] == tag {
1239                    // Same variant; stay homogeneous, increment count.
1240                    self.offset[1] += 1;
1241                } else {
1242                    // Different variant; transition to heterogeneous.
1243                    let prev = (self.offset[0] - 1) as u8;
1244                    let count = self.offset[1];
1245                    self.variant.reserve(count as usize + 1);
1246                    self.offset.clear();
1247                    self.offset.reserve(count as usize + 1);
1248                    for i in 0..count {
1249                        self.variant.push(prev);
1250                        self.offset.push(i);
1251                    }
1252                    self.variant.push(variant);
1253                    self.offset.push(offset);
1254                }
1255            } else {
1256                // Already heterogeneous.
1257                self.variant.push(variant);
1258                self.offset.push(offset);
1259            }
1260        }
1261
1262        /// Pre-allocate for the given borrowed discriminants.
1263        pub fn reserve_for<'a>(&mut self, selves: impl Iterator<Item = Discriminant<&'a [u8], &'a [u64]>> + Clone) {
1264            self.variant.reserve_for(selves.clone().map(|x| x.variant));
1265            self.offset.reserve_for(selves.map(|x| x.offset));
1266        }
1267    }
1268
1269    impl<CVar: Len, COff: Len> Discriminant<CVar, COff> {
1270        /// True if elements have mixed variants, with per-element discriminants and offsets.
1271        #[inline]
1272        pub fn is_heterogeneous(&self) -> bool {
1273            !self.variant.is_empty()
1274        }
1275        /// Returns `Some(variant)` if all elements share a single variant.
1276        #[inline]
1277        pub fn homogeneous(&self) -> Option<u8> where COff: IndexAs<u64> {
1278            if self.variant.is_empty() && self.offset.len() >= 2 {
1279                Some((self.offset.index_as(0) - 1) as u8)
1280            } else {
1281                None
1282            }
1283        }
1284        /// Returns `(variant, offset)` for the element at `index`.
1285        #[inline(always)]
1286        pub fn get(&self, index: usize) -> (u8, u64) where CVar: IndexAs<u8>, COff: IndexAs<u64> {
1287            if self.is_heterogeneous() {
1288                (self.variant.index_as(index), self.offset.index_as(index))
1289            } else {
1290                let tag: u64 = self.offset.index_as(0);
1291                ((tag - 1) as u8, index as u64)
1292            }
1293        }
1294    }
1295
1296    impl<CVar: Len, COff: Len + IndexAs<u64>> Len for Discriminant<CVar, COff> {
1297        #[inline(always)]
1298        fn len(&self) -> usize {
1299            if self.is_heterogeneous() { self.variant.len() }
1300            else if self.offset.len() >= 2 { self.offset.index_as(1) as usize }
1301            else { 0 }
1302        }
1303    }
1304
1305    // Index for the borrowed form: returns (variant, offset).
1306    impl<'a> Index for Discriminant<&'a [u8], &'a [u64]> {
1307        type Ref = (u8, u64);
1308        #[inline(always)]
1309        fn get(&self, index: usize) -> (u8, u64) {
1310            if self.is_heterogeneous() {
1311                (self.variant.index_as(index), self.offset.index_as(index))
1312            } else {
1313                ((self.offset[0] - 1) as u8, index as u64)
1314            }
1315        }
1316    }
1317
1318    // Borrow
1319    impl Borrow for Discriminant {
1320        type Ref<'a> = (u8, u64);
1321        type Borrowed<'a> = Discriminant<&'a [u8], &'a [u64]>;
1322        #[inline(always)]
1323        fn borrow<'a>(&'a self) -> Self::Borrowed<'a> {
1324            Discriminant {
1325                variant: &self.variant[..],
1326                offset: &self.offset[..],
1327            }
1328        }
1329        #[inline(always)]
1330        fn reborrow<'b, 'a: 'b>(thing: Self::Borrowed<'a>) -> Self::Borrowed<'b> {
1331            Discriminant {
1332                variant: thing.variant,
1333                offset: thing.offset,
1334            }
1335        }
1336        #[inline(always)]
1337        fn reborrow_ref<'b, 'a: 'b>(thing: Self::Ref<'a>) -> Self::Ref<'b> { thing }
1338    }
1339
1340    impl<CVar: Clear, COff: Clear> Clear for Discriminant<CVar, COff> {
1341        #[inline(always)]
1342        fn clear(&mut self) {
1343            self.variant.clear();
1344            self.offset.clear();
1345        }
1346    }
1347
1348
1349    // AsBytes for Discriminant, generic over container types.
1350    impl<'a, CVar: crate::AsBytes<'a>, COff: crate::AsBytes<'a>> crate::AsBytes<'a> for Discriminant<CVar, COff> {
1351        const SLICE_COUNT: usize = CVar::SLICE_COUNT + COff::SLICE_COUNT;
1352        #[inline]
1353        fn get_byte_slice(&self, index: usize) -> (u64, &'a [u8]) {
1354            debug_assert!(index < Self::SLICE_COUNT);
1355            if index < CVar::SLICE_COUNT {
1356                self.variant.get_byte_slice(index)
1357            } else {
1358                self.offset.get_byte_slice(index - CVar::SLICE_COUNT)
1359            }
1360        }
1361    }
1362
1363    // FromBytes for borrowed form
1364    impl<'a> crate::FromBytes<'a> for Discriminant<&'a [u8], &'a [u64]> {
1365        const SLICE_COUNT: usize = <&'a [u8]>::SLICE_COUNT + <&'a [u64]>::SLICE_COUNT;
1366        #[inline(always)]
1367        fn from_bytes(bytes: &mut impl Iterator<Item=&'a [u8]>) -> Self {
1368            let variant = crate::FromBytes::from_bytes(bytes);
1369            let offset = crate::FromBytes::from_bytes(bytes);
1370            Self { variant, offset }
1371        }
1372        #[inline(always)]
1373        fn from_store(store: &crate::bytes::indexed::DecodedStore<'a>, offset: &mut usize) -> Self {
1374            let variant = crate::FromBytes::from_store(store, offset);
1375            let offset_field = crate::FromBytes::from_store(store, offset);
1376            Self { variant, offset: offset_field }
1377        }
1378        #[inline(always)]
1379        fn element_sizes(sizes: &mut Vec<usize>) -> Result<(), String> {
1380            <&[u8]>::element_sizes(sizes)?;
1381            <&[u64]>::element_sizes(sizes)?;
1382            Ok(())
1383        }
1384    }
1385
1386    #[cfg(test)]
1387    mod test {
1388        use crate::Len;
1389
1390        #[test]
1391        fn homogeneous_push() {
1392            let mut d = super::Discriminant::default();
1393            d.push(2, 0);
1394            d.push(2, 1);
1395            d.push(2, 2);
1396            assert_eq!(d.len(), 3);
1397            assert_eq!(d.homogeneous(), Some(2));
1398            assert!(d.variant.is_empty());
1399            // offset holds [tag, count] = [3, 3] in homogeneous mode.
1400            assert_eq!(d.offset, vec![3, 3]);
1401        }
1402
1403        #[test]
1404        fn heterogeneous_transition() {
1405            let mut d = super::Discriminant::default();
1406            d.push(0, 0);
1407            d.push(0, 1);
1408            d.push(1, 0); // transition
1409            assert_eq!(d.len(), 3);
1410            assert_eq!(d.homogeneous(), None);
1411            assert_eq!(d.variant, vec![0, 0, 1]);
1412            assert_eq!(d.offset, vec![0, 1, 0]);
1413        }
1414
1415        #[test]
1416        fn clear_resets() {
1417            use crate::Clear;
1418            let mut d = super::Discriminant::default();
1419            d.push(1, 0);
1420            d.push(1, 1);
1421            d.clear();
1422            assert_eq!(d.len(), 0);
1423            // After clear, first push starts homogeneous again.
1424            d.push(3, 0);
1425            assert_eq!(d.homogeneous(), Some(3));
1426            assert_eq!(d.len(), 1);
1427        }
1428
1429        #[test]
1430        fn borrow_index() {
1431            use crate::Borrow;
1432            let mut d = super::Discriminant::default();
1433            d.push(2, 0);
1434            d.push(2, 1);
1435            d.push(2, 2);
1436            let b = d.borrow();
1437            assert_eq!(b.get(0), (2, 0));
1438            assert_eq!(b.get(1), (2, 1));
1439            assert_eq!(b.get(2), (2, 2));
1440        }
1441
1442        #[test]
1443        fn borrow_index_heterogeneous() {
1444            use crate::Borrow;
1445            let mut d = super::Discriminant::default();
1446            d.push(0, 0);
1447            d.push(1, 0);
1448            d.push(0, 1);
1449            let b = d.borrow();
1450            assert_eq!(b.get(0), (0, 0));
1451            assert_eq!(b.get(1), (1, 0));
1452            assert_eq!(b.get(2), (0, 1));
1453        }
1454    }
1455}