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
/*
 *
 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
 * SPDX-FileCopyrightText: 2023 Inria
 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
 *
 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
 */

use crate::prelude::*;
use anyhow::Result;
use common_traits::SelectInWord;
use epserde::*;
use mem_dbg::*;

/**

A selection structure based on a one-level index.

More precisely, given a constant `LOG2_ONES_PER_INVENTORY`, this index records the position
of one every 2<sup>`LOG2_ONES_PER_INVENTORY`</sup>.
The positions are recorded in a [`BitFieldSlice`] whose [bit width](BitFieldSliceCore::bit_width)
must be sufficient to record all the positions.

Note that [`SelectFixed2`] has usually better performance than this structure, which is mainly
useful for testing, benchmarking and debugging.

The current implementation uses a [`Vec<usize>`] as the underlying [`BitFieldSlice`]. Thus,
the overhead of the structure is [`BitCount::count()`] * [`usize::BITS`] / 2<sup>`LOG2_ONES_PER_INVENTORY`</sup> bits.

The index takes a backend parameter `B` that can be any type that implements
[`SelectHinted`]. This will usually be something like [`CountBitVec`](crate::bits::bit_vec::CountBitVec), or possibly
a [`CountBitVec`](crate::bits::bit_vec::CountBitVec) wrapped in another index structure for which
this structure has delegation (e.g., [`SelectZeroFixed1`](crate::rank_sel::SelectZeroFixed1)). See the documentation
of [`EliasFano`](crate::dict::elias_fano::EliasFano) for an example of this approach.

See [`SelectZeroFixed1`](crate::rank_sel::SelectZeroFixed1) for the same structure for zeros.

*/
#[derive(Epserde, Debug, Clone, MemDbg, MemSize)]
pub struct SelectFixed1<
    B: SelectHinted = CountBitVec,
    O: BitFieldSlice<usize> = Vec<usize>,
    const LOG2_ONES_PER_INVENTORY: usize = 8,
> {
    bits: B,
    inventory: O,
    _marker: core::marker::PhantomData<[(); LOG2_ONES_PER_INVENTORY]>,
}

impl<B: SelectHinted + AsRef<[usize]>, const LOG2_ONES_PER_INVENTORY: usize>
    SelectFixed1<B, Vec<usize>, LOG2_ONES_PER_INVENTORY>
{
    pub fn new(bitvec: B, number_of_ones: usize) -> Self {
        let mut res = SelectFixed1 {
            inventory: vec![
                0;
                (number_of_ones + (1 << LOG2_ONES_PER_INVENTORY) - 1)
                    >> LOG2_ONES_PER_INVENTORY
            ],
            bits: bitvec,
            _marker: core::marker::PhantomData,
        };
        res.build_ones();
        res
    }
}

impl<
        B: SelectHinted + AsRef<[usize]>,
        O: BitFieldSlice<usize> + BitFieldSliceMut<usize>,
        const LOG2_ONES_PER_INVENTORY: usize,
    > SelectFixed1<B, O, LOG2_ONES_PER_INVENTORY>
{
    fn build_ones(&mut self) {
        let mut number_of_ones = 0;
        let mut next_quantum = 0;
        let mut ones_index = 0;

        for (i, word) in self.bits.as_ref().iter().copied().enumerate() {
            let ones_in_word = word.count_ones() as u64;
            // skip the word if we can
            while number_of_ones + ones_in_word > next_quantum {
                let in_word_index = word.select_in_word((next_quantum - number_of_ones) as usize);
                let index = (i * usize::BITS as usize) + in_word_index;
                self.inventory.set(ones_index, index);
                next_quantum += 1 << LOG2_ONES_PER_INVENTORY;
                ones_index += 1;
            }

            number_of_ones += ones_in_word;
        }
    }
}

/// Provide the hint to the underlying structure
impl<B: SelectHinted + BitCount, O: BitFieldSlice<usize>, const LOG2_ONES_PER_INVENTORY: usize>
    Select for SelectFixed1<B, O, LOG2_ONES_PER_INVENTORY>
{
    #[inline(always)]
    unsafe fn select_unchecked(&self, rank: usize) -> usize {
        let index = rank >> LOG2_ONES_PER_INVENTORY;
        let pos = self.inventory.get_unchecked(index);
        let rank_at_pos = index << LOG2_ONES_PER_INVENTORY;

        self.bits.select_hinted_unchecked(rank, pos, rank_at_pos)
    }
}

/// Forget the index.
impl<B: SelectHinted, T, const LOG2_ONES_PER_INVENTORY: usize> ConvertTo<B>
    for SelectFixed1<B, T, LOG2_ONES_PER_INVENTORY>
where
    T: AsRef<[usize]>,
{
    #[inline(always)]
    fn convert_to(self) -> Result<B> {
        Ok(self.bits)
    }
}

/// Create and add a selection structure.
impl<B: SelectHinted + BitCount + AsRef<[usize]>, const LOG2_ONES_PER_INVENTORY: usize>
    ConvertTo<SelectFixed1<B, Vec<usize>, LOG2_ONES_PER_INVENTORY>> for B
{
    #[inline(always)]
    fn convert_to(self) -> Result<SelectFixed1<B, Vec<usize>, LOG2_ONES_PER_INVENTORY>> {
        let count = self.count();
        Ok(SelectFixed1::new(self, count))
    }
}

/// Forward [`BitLength`] to the underlying implementation.
impl<
        B: SelectHinted + BitLength,
        O: BitFieldSlice<usize>,
        const LOG2_ONES_PER_INVENTORY: usize,
    > BitLength for SelectFixed1<B, O, LOG2_ONES_PER_INVENTORY>
{
    #[inline(always)]
    fn len(&self) -> usize {
        self.bits.len()
    }
}

/// Forward [`BitCount`] to the underlying implementation.
impl<B: SelectHinted + BitCount, O: BitFieldSlice<usize>, const LOG2_ONES_PER_INVENTORY: usize>
    BitCount for SelectFixed1<B, O, LOG2_ONES_PER_INVENTORY>
{
    #[inline(always)]
    fn count(&self) -> usize {
        self.bits.count()
    }
}

/// Forward [`SelectZero`] to the underlying implementation.
impl<
        B: SelectHinted + SelectZero,
        O: BitFieldSlice<usize>,
        const LOG2_ONES_PER_INVENTORY: usize,
    > SelectZero for SelectFixed1<B, O, LOG2_ONES_PER_INVENTORY>
{
    #[inline(always)]
    fn select_zero(&self, rank: usize) -> Option<usize> {
        self.bits.select_zero(rank)
    }
    #[inline(always)]
    unsafe fn select_zero_unchecked(&self, rank: usize) -> usize {
        self.bits.select_zero_unchecked(rank)
    }
}

/// Forward [`SelectZeroHinted`] to the underlying implementation.
impl<
        B: SelectHinted + SelectZeroHinted,
        O: BitFieldSlice<usize>,
        const LOG2_ONES_PER_INVENTORY: usize,
    > SelectZeroHinted for SelectFixed1<B, O, LOG2_ONES_PER_INVENTORY>
{
    #[inline(always)]
    unsafe fn select_zero_hinted_unchecked(
        &self,
        rank: usize,
        pos: usize,
        rank_at_pos: usize,
    ) -> usize {
        self.bits
            .select_zero_hinted_unchecked(rank, pos, rank_at_pos)
    }

    #[inline(always)]
    fn select_zero_hinted(&self, rank: usize, pos: usize, rank_at_pos: usize) -> Option<usize> {
        self.bits.select_zero_hinted(rank, pos, rank_at_pos)
    }
}

/// Forward [`Rank`] to the underlying implementation.
impl<B: SelectHinted + Rank, O: BitFieldSlice<usize>, const LOG2_ONES_PER_INVENTORY: usize> Rank
    for SelectFixed1<B, O, LOG2_ONES_PER_INVENTORY>
{
    fn rank(&self, pos: usize) -> usize {
        self.bits.rank(pos)
    }

    unsafe fn rank_unchecked(&self, pos: usize) -> usize {
        self.bits.rank_unchecked(pos)
    }
}

/// Forward [`RankZero`] to the underlying implementation.
impl<B: SelectHinted + RankZero, O: BitFieldSlice<usize>, const LOG2_ONES_PER_INVENTORY: usize>
    RankZero for SelectFixed1<B, O, LOG2_ONES_PER_INVENTORY>
{
    fn rank_zero(&self, pos: usize) -> usize {
        self.bits.rank_zero(pos)
    }

    unsafe fn rank_zero_unchecked(&self, pos: usize) -> usize {
        self.bits.rank_zero_unchecked(pos)
    }
}

/// Forward `AsRef<[usize]>` to the underlying implementation.
impl<
        B: SelectHinted + AsRef<[usize]>,
        O: BitFieldSlice<usize>,
        const LOG2_ONES_PER_INVENTORY: usize,
    > AsRef<[usize]> for SelectFixed1<B, O, LOG2_ONES_PER_INVENTORY>
{
    fn as_ref(&self) -> &[usize] {
        self.bits.as_ref()
    }
}