binar 0.1.1

High-performance binary arithmetic.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::BitView;
use crate::matrix::Column;
use crate::vec::{AlignedBitVec, AlignedBitView, AlignedBitViewMut, BitBlock, BitVec, BitViewMut};
use crate::{BitLength, Bitwise, BitwiseMut, BitwisePair, BitwisePairMut, FromBits};
use sorted_iter::{SortedIterator, assume::AssumeSortedByItemExt};
use sorted_vec::SortedSet;

/// A sparse representation of a bit vector using a sorted set of indices.
///
/// `IndexSet` stores only the indices of set bits, making it memory-efficient for sparse
/// bit vectors (those with few set bits relative to their length). It implements the same
/// [`Bitwise`] trait family as [`BitVec`], allowing it to be used interchangeably in
/// generic code.
///
/// # When to Use
///
/// Use `IndexSet` when:
/// - Your bit vector is sparse (most bits are 0)
/// - You need to iterate over set bits frequently
/// - Memory usage is more important than constant-time random access
///
/// Use [`BitVec`] when:
/// - Your bit vector is dense or of unknown density
/// - You need constant-time indexed access
/// - You perform many bitwise operations
///
/// # Example
///
/// ```
/// use binar::{IndexSet, BitVec, Bitwise, BitwiseMut, BitwisePairMut};
///
/// // Create a sparse set with just a few bits set
/// let mut sparse = IndexSet::new();
/// sparse.assign_index(10, true);
/// sparse.assign_index(100, true);
/// sparse.assign_index(1000, true);
///
/// assert_eq!(sparse.weight(), 3);
///
/// // Can convert to BitVec when needed
/// let mut dense = BitVec::zeros(1001);
/// dense.assign(&sparse);
/// assert_eq!(dense.weight(), 3);
/// assert_eq!(dense.index(100), true);
/// ```
///
/// # Performance Characteristics
///
/// - **Memory**: O(k) where k is the number of set bits
/// - **`index()`**: O(log k) via binary search
/// - **`assign_index()`**: O(k) due to sorted insertion
/// - **`support()`**: O(k) iteration over set bits
/// - **`weight()`**: O(1)
///
/// # See Also
///
/// - [`BitVec`](crate::BitVec) - Dense bit vector representation
/// - [`Bitwise`] - Read-only bit operations trait
/// - [`BitwiseMut`] - Mutable bit operations trait
#[must_use]
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct IndexSet {
    indexes: SortedSet<usize>,
}

impl IndexSet {
    /// Creates a new empty `IndexSet`.
    ///
    /// # Example
    ///
    /// ```
    /// use binar::{IndexSet, Bitwise};
    ///
    /// let set = IndexSet::new();
    /// assert_eq!(set.weight(), 0);
    /// assert!(set.is_zero());
    /// ```
    pub fn new() -> IndexSet {
        IndexSet {
            indexes: SortedSet::new(),
        }
    }

    /// Creates an `IndexSet` with a single bit set at the given index.
    ///
    /// # Example
    ///
    /// ```
    /// use binar::{IndexSet, Bitwise};
    ///
    /// let set = IndexSet::singleton(42);
    /// assert_eq!(set.weight(), 1);
    /// assert_eq!(set.index(42), true);
    /// assert_eq!(set.index(41), false);
    /// ```
    pub fn singleton(value: usize) -> Self {
        IndexSet {
            indexes: unsafe { SortedSet::from_sorted(vec![value]) },
        }
    }

    /// Returns a new `IndexSet` that is the complement of this set with respect to a universe of the given size.
    /// The universe is defined as the set of all indices from `0` to `universe_size - 1`.
    /// # Example
    ///
    /// ```
    /// use binar::{IndexSet, Bitwise};
    ///
    /// let set = IndexSet::singleton(42);
    /// let complement = set.complement(100);
    /// assert_eq!(complement.index(42), false);
    /// assert_eq!(complement.index(41), true);
    /// ```
    pub fn complement(&self, universe_size: usize) -> Self {
        let indexes = (0..universe_size).difference(self.support());
        IndexSet {
            indexes: unsafe { SortedSet::from_sorted(indexes.collect()) },
        }
    }

    pub fn union(&self, other: &Self) -> Self {
        let indexes = self.support().union(other.support());
        IndexSet {
            indexes: unsafe { SortedSet::from_sorted(indexes.collect()) },
        }
    }

    pub fn intersection(&self, other: &Self) -> Self {
        let indexes = self.support().intersection(other.support());
        IndexSet {
            indexes: unsafe { SortedSet::from_sorted(indexes.collect()) },
        }
    }

    pub fn difference(&self, other: &Self) -> Self {
        let indexes = self.support().difference(other.support());
        IndexSet {
            indexes: unsafe { SortedSet::from_sorted(indexes.collect()) },
        }
    }

    pub fn symmetric_difference(&self, other: &Self) -> Self {
        let indexes = self.support().symmetric_difference(other.support());
        IndexSet {
            indexes: unsafe { SortedSet::from_sorted(indexes.collect()) },
        }
    }
}

impl Default for IndexSet {
    fn default() -> Self {
        Self::new()
    }
}

impl FromIterator<usize> for IndexSet {
    fn from_iter<Iterator: IntoIterator<Item = usize>>(iterator: Iterator) -> Self {
        let indexes = SortedSet::from_unsorted(iterator.into_iter().collect());
        IndexSet { indexes }
    }
}

// Should this be a bool iterator instead?
impl IntoIterator for IndexSet {
    type Item = usize;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.indexes.into_iter()
    }
}

impl Extend<usize> for IndexSet {
    fn extend<T: IntoIterator<Item = usize>>(&mut self, iter: T) {
        for index in iter {
            self.indexes.push(index);
        }
    }
}

impl Bitwise for IndexSet {
    #[inline]
    fn index(&self, index: usize) -> bool {
        self.indexes.binary_search(&index).is_ok()
    }

    #[inline]
    fn weight(&self) -> usize {
        self.indexes.len()
    }

    #[inline]
    fn support(&self) -> impl SortedIterator<Item = usize> {
        self.indexes.iter().copied().assume_sorted_by_item()
    }
}

impl<Bits: Bitwise> BitwisePairMut<Bits> for IndexSet {
    #[inline]
    fn assign(&mut self, other: &Bits) {
        let indexes: Vec<usize> = other.support().collect();
        self.indexes = indexes.into();
    }

    #[inline]
    fn bitxor_assign(&mut self, other: &Bits) {
        for index in other.support() {
            let found = self.indexes.find_or_insert(index);
            if found.is_found() {
                self.indexes.remove_index(found.index());
            }
        }
    }

    #[inline]
    fn bitand_assign(&mut self, other: &Bits) {
        let self_support = self.indexes.iter().copied().assume_sorted_by_item();
        let other_support = other.support();
        let indexes: Vec<usize> = self_support.intersection(other_support).collect();
        self.indexes = indexes.into();
    }

    #[inline]
    fn bitor_assign(&mut self, other: &Bits) {
        let self_support = self.indexes.iter().copied().assume_sorted_by_item();
        let other_support = other.support();
        let indexes: Vec<usize> = self_support.union(other_support).collect();
        self.indexes = indexes.into();
    }
}

impl BitwiseMut for IndexSet {
    #[inline]
    fn assign_index(&mut self, index: usize, to: bool) {
        if to {
            self.indexes.push(index);
        } else {
            self.indexes.remove_item(&index);
        }
    }

    #[inline]
    fn negate_index(&mut self, index: usize) {
        if self.indexes.contains(&index) {
            self.indexes.remove_item(&index);
        } else {
            self.indexes.push(index);
        }
    }

    #[inline]
    fn clear_bits(&mut self) {
        self.indexes.clear();
    }
}

impl<Bits: Bitwise> BitwisePair<Bits> for IndexSet {
    #[inline]
    fn dot(&self, other: &Bits) -> bool {
        let mut res = false;
        for index in &self.indexes {
            res ^= other.index(*index);
        }
        res
    }

    #[inline]
    fn and_weight(&self, other: &Bits) -> usize {
        self.support().intersection(other.support()).count()
    }

    #[inline]
    fn or_weight(&self, other: &Bits) -> usize {
        self.support().union(other.support()).count()
    }

    #[inline]
    fn xor_weight(&self, other: &Bits) -> usize {
        self.support().symmetric_difference(other.support()).count()
    }
}

impl<T: BitwiseMut + BitLength> BitwisePair<IndexSet> for T {
    #[inline]
    fn dot(&self, other: &IndexSet) -> bool {
        other.dot(self)
    }

    #[inline]
    fn and_weight(&self, other: &IndexSet) -> usize {
        other.and_weight(self)
    }

    #[inline]
    fn or_weight(&self, other: &IndexSet) -> usize {
        other.or_weight(self)
    }

    #[inline]
    fn xor_weight(&self, other: &IndexSet) -> usize {
        other.xor_weight(self)
    }
}

impl<T: BitwiseMut + BitLength> BitwisePairMut<IndexSet> for T {
    #[inline]
    fn assign(&mut self, other: &IndexSet) {
        self.clear_bits();
        for index in &other.indexes {
            self.assign_index(*index, true);
        }
    }

    #[inline]
    fn bitxor_assign(&mut self, other: &IndexSet) {
        for index in other.support() {
            self.negate_index(index);
        }
    }

    #[inline]
    fn bitand_assign(&mut self, other: &IndexSet) {
        let intersection: Vec<usize> = self.support().intersection(other.support()).collect();
        self.clear_bits();
        for k in intersection {
            self.assign_index(k, true);
        }
    }

    #[inline]
    fn bitor_assign(&mut self, other: &IndexSet) {
        let union: Vec<usize> = self.support().union(other.support()).collect();
        self.clear_bits();
        for k in union {
            self.assign_index(k, true);
        }
    }
}

impl<T: BitwiseMut + BitLength> PartialEq<T> for IndexSet {
    #[inline]
    fn eq(&self, other: &T) -> bool {
        self.support().eq(other.support())
    }
}

impl<Other: Bitwise> FromBits<Other> for IndexSet {
    fn from_bits(other: &Other) -> Self {
        IndexSet {
            indexes: other.support().collect::<Vec<usize>>().into(),
        }
    }
}

impl<'life, T> From<&'life T> for IndexSet
where
    T: Bitwise + 'life,
{
    fn from(value: &'life T) -> Self {
        unsafe {
            IndexSet {
                indexes: SortedSet::from_sorted(value.support().collect::<Vec<_>>()),
            }
        }
    }
}

pub fn remapped(bits: &IndexSet, support: &[usize]) -> IndexSet {
    bits.support().map(|id| support[id]).collect()
}

impl PartialEq<IndexSet> for AlignedBitVec {
    fn eq(&self, other: &IndexSet) -> bool {
        self.support().eq(other.support())
    }
}

impl PartialEq<IndexSet> for AlignedBitView<'_> {
    fn eq(&self, other: &IndexSet) -> bool {
        self.support().eq(other.support())
    }
}

impl PartialEq<IndexSet> for AlignedBitViewMut<'_> {
    fn eq(&self, other: &IndexSet) -> bool {
        self.support().eq(other.support())
    }
}

impl PartialEq<IndexSet> for BitVec {
    fn eq(&self, other: &IndexSet) -> bool {
        self.support().eq(other.support())
    }
}

impl PartialEq<IndexSet> for BitView<'_> {
    fn eq(&self, other: &IndexSet) -> bool {
        self.support().eq(other.support())
    }
}

impl PartialEq<IndexSet> for BitViewMut<'_> {
    fn eq(&self, other: &IndexSet) -> bool {
        self.support().eq(other.support())
    }
}

impl PartialEq<IndexSet> for Column<'_> {
    fn eq(&self, other: &IndexSet) -> bool {
        self.support().eq(other.support())
    }
}

impl PartialEq<IndexSet> for BitBlock {
    fn eq(&self, other: &IndexSet) -> bool {
        self.support().eq(other.support())
    }
}