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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
#![cfg_attr(is_nightly, feature(portable_simd))]
//! SEEC-BitMatrix
//!
//! A library for fast bitmatrix transpose intended for MPC implementations.

use bitvec::order::Lsb0;
use bitvec::slice::BitSlice;
use bitvec::store::BitStore;
use bitvec::vec::BitVec;
use cfg_if::cfg_if;
use rand::distributions::Standard;
use rand::prelude::Distribution;
use rand::Rng;
#[cfg(feature = "rayon")]
use rayon::iter::IndexedParallelIterator;
#[cfg(feature = "rayon")]
use rayon::slice::{ParallelSlice, ParallelSliceMut};
use serde::{Deserialize, Serialize};
use std::fmt::{Binary, Debug, Formatter};
use std::ops::{BitAnd, BitXor, Not, Range};
use std::slice::{ChunksExact, ChunksExactMut};

#[cfg(is_nightly)]
mod portable_transpose;
mod simple;
#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
mod sse2_transpose;

#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct BitMatrix<T: Storage> {
    rows: usize,
    cols: usize,
    data: Vec<T>,
}

#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct BitMatrixView<'a, T> {
    rows: usize,
    cols: usize,
    data: &'a [T],
}

#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct BitMatrixViewMut<'a, T> {
    rows: usize,
    cols: usize,
    data: &'a mut [T],
}

pub trait Storage:
    bytemuck::Pod + BitXor<Output = Self> + BitAnd<Output = Self> + Not<Output = Self> + Send + Sync
{
    const BITS: usize;

    fn zero() -> Self;
}

impl<T: Storage> BitMatrix<T> {
    pub fn new(rows: usize, cols: usize) -> Self {
        Self::zeros(rows, cols)
    }

    pub fn from_vec(data: Vec<T>, rows: usize, cols: usize) -> Self {
        Self { rows, cols, data }
    }

    pub fn zeros(rows: usize, cols: usize) -> Self {
        check_dim::<T>(rows, cols);
        Self {
            data: vec![T::zero(); rows * cols / T::BITS],
            rows,
            cols,
        }
    }

    pub fn random<R: Rng>(rng: R, rows: usize, cols: usize) -> Self
    where
        Standard: Distribution<T>,
    {
        check_dim::<T>(rows, cols);
        let data = rng
            .sample_iter(Standard)
            .take(rows * cols / T::BITS)
            .collect();
        Self { data, rows, cols }
    }

    pub fn view(&self) -> BitMatrixView<'_, T> {
        BitMatrixView {
            rows: self.rows,
            cols: self.cols,
            data: self.data.as_slice(),
        }
    }

    pub fn view_mut(&mut self) -> BitMatrixViewMut<'_, T> {
        BitMatrixViewMut {
            rows: self.rows,
            cols: self.cols,
            data: self.data.as_mut_slice(),
        }
    }

    pub fn rows(&self) -> usize {
        self.rows
    }

    pub fn cols(&self) -> usize {
        self.cols
    }

    // Returns dimensions (rows, columns).
    pub fn dim(&self) -> (usize, usize) {
        (self.rows, self.cols)
    }

    pub fn storage_len(&self) -> usize {
        self.data.len()
    }

    pub fn into_vec(self) -> Vec<T> {
        self.data
    }

    pub fn iter_rows(&self) -> Rows<'_, T> {
        Rows::new(self.view())
    }

    pub fn iter_raw_rows(&self) -> RawRows<'_, T> {
        RawRows::new(self.view())
    }

    pub fn iter_raw_rows_mut(&mut self) -> RawRowsMut<'_, T> {
        RawRowsMut::new(self.view_mut())
    }

    #[cfg(feature = "rayon")]
    pub fn par_iter_raw_rows(&self) -> impl IndexedParallelIterator<Item = &[T]> {
        assert_eq!(
            0,
            self.cols % T::BITS,
            "cols must be divisable by bits for raw iterator"
        );
        self.data.par_chunks_exact(self.cols / T::BITS)
    }

    #[cfg(feature = "rayon")]
    pub fn par_iter_raw_rows_mut(&mut self) -> impl IndexedParallelIterator<Item = &mut [T]> {
        assert_eq!(
            0,
            self.cols % T::BITS,
            "cols must be divisable by bits for raw iterator"
        );
        self.data.par_chunks_exact_mut(self.cols / T::BITS)
    }

    pub fn scalar_and(&self, rhs: &Self) -> Self {
        assert_eq!(
            self.dim(),
            rhs.dim(),
            "Dimensions must be identical for scalar_and"
        );
        let data = self
            .data
            .iter()
            .zip(&rhs.data)
            .map(|(a, b)| *a & *b)
            .collect();
        Self {
            rows: self.rows,
            cols: self.cols,
            data,
        }
    }
}

impl<T> BitMatrix<T>
where
    T: Storage + BitStore<Unalias = T>,
{
    pub fn from_bits(bits: &BitSlice<T, Lsb0>, rows: usize, cols: usize) -> Self {
        assert_eq!(
            bits.len() % T::BITS,
            0,
            "Length of bits must be  multiple of T::BITS"
        );
        assert_eq!(bits.len(), rows * cols, "bits.len() != rows * cols");
        let data = bits.to_bitvec().into_vec();
        Self { rows, cols, data }
    }

    pub fn identity(size: usize) -> Self {
        check_dim::<T>(size, size);
        let mut bv: BitVec<T> = BitVec::repeat(false, size * size);
        let mut idx = 0;
        while idx < size * size {
            bv.set(idx, true);
            idx += size + 1;
        }
        Self::from_vec(bv.into_vec(), size, size)
    }

    pub fn mat_mul(self, rhs: &Self) -> Self {
        assert_eq!(
            self.cols, rhs.rows,
            "Illegal dimensions for matrix multiplication"
        );
        // TODO this can likely be heavily optimized. One option is to use the raw_rows iterator
        //  if possible to do the dotp on the raw elements. This should be significantly faster.
        let dotp = |l_row: &BitSlice<T>, r_row| -> bool {
            let and = l_row.to_bitvec() & r_row;
            and.iter().by_vals().reduce(BitXor::bitxor).unwrap()
        };

        let rhs = rhs.view().transpose();
        let bits = self
            .iter_rows()
            .flat_map(|l_row| rhs.iter_rows().map(|r_row| dotp(l_row, r_row)));
        let mut bv: BitVec<T> = BitVec::with_capacity(self.rows * rhs.rows);
        bv.extend(bits);
        Self::from_vec(bv.into_vec(), self.rows, rhs.rows)
    }

    pub fn into_bitvec(self) -> BitVec<T> {
        BitVec::from_vec(self.data)
    }
}

impl<'a, T: Storage> BitMatrixView<'a, T> {
    pub fn from_slice(data: &'a [T], rows: usize, cols: usize) -> Self {
        assert_eq!(
            data.len() * T::BITS,
            rows * cols,
            "data.len() does not match rows * cols"
        );
        Self { rows, cols, data }
    }

    pub fn fast_transpose(&self) -> BitMatrix<T> {
        cfg_if! {
            if #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] {
                let transposed = sse2_transpose::transpose(self.data, self.rows, self.cols);
            } else if #[cfg(is_nightly)] {
                let transposed = portable_transpose::transpose(self.data, self.rows, self.cols);
            } else {
                use std::compile_error;

                compile_error!("Target must either be x86_64 with sse2 enabled or crate \
                feature \"portable_transpose\" must be enabled (requires nightly)")
            }
        }

        BitMatrix::from_vec(transposed, self.cols, self.rows)
    }

    #[inline]
    pub fn raw_row(&self, row: usize) -> Option<&'a [T]> {
        let idx = raw_row_idx::<T>(row, self.cols);
        self.data.get(idx)
    }

    fn can_do_sse_trans(&self) -> bool {
        self.rows % 8 == 0 && self.cols % 8 == 0 && self.rows >= 16 && self.cols >= 16
    }
}

impl<'a, T: BitStore<Unalias = T>> BitMatrixView<'a, T> {
    pub fn as_bitslice(&self) -> &'a BitSlice<T> {
        BitSlice::from_slice(self.data)
    }

    #[inline]
    pub fn row(&self, row: usize) -> Option<&'a BitSlice<T>> {
        let data = self.as_bitslice();
        let start_idx = row * self.cols;
        let end_idx = (row + 1) * self.cols;
        data.get(start_idx..end_idx)
    }
}

impl<'a, T: Storage + BitStore<Unalias = T>> BitMatrixView<'a, T> {
    pub fn transpose(&self) -> BitMatrix<T> {
        let transposed = if self.can_do_sse_trans()
            && (cfg!(is_nightly) || cfg!(all(target_arch = "x86_64", target_feature = "sse2")))
        {
            cfg_if! {
                if #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] {
                    sse2_transpose::transpose(self.data, self.rows, self.cols)
                } else if #[cfg(is_nightly)] {
                    portable_transpose::transpose(self.data, self.rows, self.cols)
                } else {
                    simple::transpose(self.data, self.rows, self.cols)
                }
            }
        } else {
            simple::transpose(self.data, self.rows, self.cols)
        };
        BitMatrix::from_vec(transposed, self.cols, self.rows)
    }
}

impl<'a, T: Storage> BitMatrixViewMut<'a, T> {
    pub fn raw_row_mut(&'a mut self, row: usize) -> Option<&'a mut [T]> {
        let idx = raw_row_idx::<T>(row, self.cols);
        self.data.get_mut(idx)
    }
}

#[inline]
fn raw_row_idx<T: Storage>(row: usize, cols: usize) -> Range<usize> {
    assert_eq!(
        0,
        cols % T::BITS,
        "cols must be divisable by T::BITS for raw_row. Use row() instead."
    );
    let cols_el = cols / T::BITS;
    let start_idx = row * cols_el;
    let end_idx = (row + 1) * cols_el;
    start_idx..end_idx
}

impl<T: Storage> Not for BitMatrix<T> {
    type Output = Self;

    fn not(mut self) -> Self::Output {
        self.data.iter_mut().for_each(|el| *el = !*el);
        self
    }
}

impl<T: Storage> BitXor for BitMatrix<T> {
    type Output = BitMatrix<T>;

    fn bitxor(mut self, rhs: Self) -> Self::Output {
        assert_eq!(
            self.dim(),
            rhs.dim(),
            "BitXor on matrices with different dimensions"
        );
        self.data.iter_mut().zip(rhs.data).for_each(|(a, b)| {
            *a = *a ^ b;
        });
        self
    }
}

impl<T: Storage> BitXor<&Self> for BitMatrix<T> {
    type Output = BitMatrix<T>;

    fn bitxor(mut self, rhs: &Self) -> Self::Output {
        assert_eq!(
            self.dim(),
            rhs.dim(),
            "BitXor on matrices with different dimensions"
        );
        self.data.iter_mut().zip(&rhs.data).for_each(|(a, b)| {
            *a = *a ^ *b;
        });
        self
    }
}

impl<T: Binary + Storage> Binary for BitMatrix<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let fmt_bin: Vec<_> = self.data.iter().map(|el| format!("{el:b}")).collect();

        f.debug_struct("BitMatrix")
            .field("rows", &self.rows)
            .field("cols", &self.cols)
            .field("data", &fmt_bin)
            .finish()
    }
}

impl Storage for u8 {
    const BITS: usize = 8;
    fn zero() -> Self {
        0
    }
}
impl Storage for u16 {
    const BITS: usize = 16;
    fn zero() -> Self {
        0
    }
}
impl Storage for u32 {
    const BITS: usize = 32;
    fn zero() -> Self {
        0
    }
}
impl Storage for u64 {
    const BITS: usize = 64;
    fn zero() -> Self {
        0
    }
}
impl Storage for u128 {
    const BITS: usize = 128;
    fn zero() -> Self {
        0
    }
}

#[derive(Clone, Debug)]
pub struct Rows<'a, T> {
    view: BitMatrixView<'a, T>,
    row: usize,
}

impl<'a, T> Rows<'a, T> {
    pub fn new(view: BitMatrixView<'a, T>) -> Self {
        Self { view, row: 0 }
    }
}

impl<'a, T: BitStore<Unalias = T>> Iterator for Rows<'a, T> {
    type Item = &'a BitSlice<T>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let ret = self.view.row(self.row);
        self.row += 1;
        ret
    }
}

#[derive(Clone, Debug)]
pub struct RawRows<'a, T> {
    chunks: ChunksExact<'a, T>,
}

impl<'a, T: Storage> RawRows<'a, T> {
    pub fn new(view: BitMatrixView<'a, T>) -> Self {
        assert_eq!(
            0,
            view.cols % T::BITS,
            "cols of BitMatrix must be multiple of T::BITS for raw rows iterator"
        );
        let chunks = view.data.chunks_exact(view.cols / T::BITS);
        Self { chunks }
    }
}

impl<'a, T: Storage> Iterator for RawRows<'a, T> {
    type Item = &'a [T];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.chunks.next()
    }
}

#[derive(Debug)]
pub struct RawRowsMut<'a, T> {
    chunks: ChunksExactMut<'a, T>,
}

impl<'a, T: Storage> RawRowsMut<'a, T> {
    pub fn new(view: BitMatrixViewMut<'a, T>) -> Self {
        assert_eq!(
            0,
            view.cols % T::BITS,
            "cols of BitMatrix must be multiple of T::BITS for raw rows iterator"
        );
        let chunks = view.data.chunks_exact_mut(view.cols / T::BITS);
        Self { chunks }
    }
}

impl<'a, T: Storage> Iterator for RawRowsMut<'a, T> {
    type Item = &'a mut [T];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.chunks.next()
    }
}

fn check_dim<T: Storage>(rows: usize, cols: usize) {
    assert_eq!(
        (rows * cols) % T::BITS,
        0,
        "rows * cols must be divisable by T::BITS"
    );
}

#[cfg(test)]
mod tests {
    use crate::BitMatrix;
    use bitvec::vec::BitVec;
    use ndarray::Array2;
    use num_traits::{One, Zero};
    use rand::{thread_rng, Rng};
    use std::fmt::{Debug, Formatter};
    use std::ops::{Add, Div, Mul, Sub};

    #[derive(Copy, Clone)]
    struct Z2(u8);

    #[test]
    fn mul() {
        let id: BitMatrix<u8> = BitMatrix::identity(128);
        let other = BitMatrix::random(thread_rng(), 128, 256);
        let mul = id.mat_mul(&other);
        assert_eq!(other, mul)
    }

    #[test]
    fn mul_ndarray() {
        let cols = 128;
        let rows = 128;
        let mut rng = thread_rng();
        let nd_arr1: Vec<_> = (0..rows * cols).map(|_| Z2(rng.gen_range(0..2))).collect();
        let bitmat1 = BitMatrix::from_bits(
            &nd_arr1.iter().map(|bit| bit.0 == 1).collect::<BitVec<u8>>(),
            rows,
            cols,
        );
        let nd_arr1 = Array2::from_shape_vec((rows, cols), nd_arr1).unwrap();

        let nd_arr2: Vec<_> = (0..rows * cols).map(|_| Z2(rng.gen_range(0..2))).collect();
        let bitmat2 = BitMatrix::from_bits(
            &nd_arr2.iter().map(|bit| bit.0 == 1).collect::<BitVec<u8>>(),
            rows,
            cols,
        );
        let nd_arr2 = Array2::from_shape_vec((rows, cols), nd_arr2).unwrap();

        let res_nd_arr = nd_arr1.dot(&nd_arr2);
        let res_bit_mat = bitmat1.mat_mul(&bitmat2);

        for (nd_row, bit_mat_row) in res_nd_arr.rows().into_iter().zip(res_bit_mat.iter_rows()) {
            for (nd_bit, bit_mat_bit) in nd_row.iter().zip(bit_mat_row) {
                assert_eq!(
                    nd_bit.0 == 1,
                    *bit_mat_bit,
                    "BitMatrix::mat_mult differs from nd_array"
                );
            }
        }
    }

    impl Add for Z2 {
        type Output = Z2;

        fn add(self, rhs: Self) -> Self::Output {
            Self(self.0 + rhs.0 % 2)
        }
    }

    impl Sub for Z2 {
        type Output = Z2;

        fn sub(self, rhs: Self) -> Self::Output {
            Self(self.0 + rhs.0 % 2)
        }
    }

    impl Mul for Z2 {
        type Output = Z2;

        fn mul(self, rhs: Self) -> Self::Output {
            Self(self.0 * rhs.0 % 2)
        }
    }

    impl Div for Z2 {
        type Output = Z2;

        fn div(self, rhs: Self) -> Self::Output {
            Self(self.0 / rhs.0 % 2)
        }
    }

    impl Zero for Z2 {
        fn zero() -> Self {
            Self(0)
        }

        fn is_zero(&self) -> bool {
            self.0 == 0
        }
    }

    impl One for Z2 {
        fn one() -> Self {
            Self(1)
        }
    }

    impl Debug for Z2 {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            write!(f, "{:?}", self.0)
        }
    }

    impl PartialEq<Array2<Z2>> for BitMatrix<u8> {
        fn eq(&self, other: &Array2<Z2>) -> bool {
            other
                .rows()
                .into_iter()
                .zip(self.iter_rows())
                .all(|(r1, r2)| {
                    r1.iter()
                        .zip(r2)
                        .all(|(el1, el2)| matches!((el1, *el2), (Z2(0), false) | (Z2(1), true)))
                })
        }
    }
}