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
use core::fmt;
use std::cmp::Ordering;
use std::ops::BitAnd;
use std::ops::BitAndAssign;
use std::ops::BitOr;
use std::ops::BitOrAssign;
use std::ops::BitXor;
use std::ops::BitXorAssign;
use std::ops::Not;

use crate::canonization::n_canonization;
use crate::canonization::npn_canonization;
use crate::canonization::p_canonization;
use crate::operations::*;

/// Fixed-size truth table
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub struct StaticLut<const N: usize, const T: usize> {
    table: [u64; T],
}

impl<const N: usize, const T: usize> Default for StaticLut<N, T> {
    fn default() -> Self {
        Self { table: [0u64; T] }
    }
}

impl<const N: usize, const T: usize> StaticLut<N, T> {
    /// Query the number of variables of the Lut
    pub fn num_vars(&self) -> usize {
        N
    }

    /// Query the number of bits in the Lut
    pub fn num_bits(&self) -> usize {
        1 << N
    }

    /// Check that an input is valid for an operation
    fn check_var(&self, ind: usize) {
        assert!(ind < self.num_vars());
    }

    /// Check that another Lut is valid for an operation
    fn check_lut(&self, rhs: &Self) {
        assert_eq!(self.num_vars(), rhs.num_vars());
    }

    /// Check that a bit is valid for an operation
    fn check_bit(&self, ind: usize) {
        assert!(ind < self.num_bits());
    }

    /// Create a constant true Lut
    pub fn one() -> Self {
        let mut ret = Self::default();
        fill_one(N, ret.table.as_mut());
        ret
    }

    /// Create a constant false Lut
    pub fn zero() -> Self {
        Self::default()
    }

    /// Create a Lut returning the value of one of its variables
    pub fn nth_var(var: usize) -> Self {
        assert!(var < N);
        let mut ret = Self::default();
        fill_nth_var(N, ret.table.as_mut(), var);
        ret
    }

    /// Create a Lut returning true if the number of true variables is even
    pub fn parity() -> Self {
        let mut ret = Self::default();
        fill_parity(N, ret.table.as_mut());
        ret
    }

    /// Create a Lut returning true if the majority of the variables are true
    pub fn majority() -> Self {
        let mut ret = Self::default();
        fill_majority(N, ret.table.as_mut());
        ret
    }

    /// Create a Lut returning true if at least k variables are true
    pub fn threshold(k: usize) -> Self {
        let mut ret = Self::default();
        fill_threshold(N, ret.table.as_mut(), k);
        ret
    }

    /// Create a Lut returning true if exactly k variables are true
    pub fn equals(k: usize) -> Self {
        let mut ret = Self::default();
        fill_equals(N, ret.table.as_mut(), k);
        ret
    }

    /// Create a Lut representing a symmetric function. Bit at position k gives the value when k variables are true
    pub fn symmetric(count_values: usize) -> Self {
        let mut ret = Self::default();
        fill_symmetric(N, ret.table.as_mut(), count_values);
        ret
    }

    /// Get the value of the Lut for these inputs (input bits packed in the mask)
    pub fn get_bit(&self, mask: usize) -> bool {
        self.check_bit(mask);
        get_bit(N, self.table.as_ref(), mask)
    }

    /// Set the value of the Lut for these inputs to true (input bits packed in the mask)
    pub fn set_bit(&mut self, mask: usize) {
        self.check_bit(mask);
        set_bit(N, self.table.as_mut(), mask);
    }

    /// Set the value of the Lut for these inputs to false (input bits packed in the mask)
    pub fn unset_bit(&mut self, mask: usize) {
        self.check_bit(mask);
        unset_bit(N, self.table.as_mut(), mask);
    }

    /// Complement the Lut in place: f(x) --> !f(x)
    pub fn not_inplace(&mut self) {
        not_inplace(N, self.table.as_mut());
    }

    /// And two Luts in place
    pub fn and_inplace(&mut self, rhs: &Self) {
        self.check_lut(rhs);
        and_inplace(self.table.as_mut(), rhs.table.as_ref());
    }

    /// Or two Luts in place
    pub fn or_inplace(&mut self, rhs: &Self) {
        self.check_lut(rhs);
        or_inplace(self.table.as_mut(), rhs.table.as_ref());
    }

    /// Xor two Luts in place
    pub fn xor_inplace(&mut self, rhs: &Self) {
        self.check_lut(rhs);
        xor_inplace(self.table.as_mut(), rhs.table.as_ref());
    }

    /// Flip a variable in place: f(x1, ... xi, ... xn) --> f(x1, ... !xi, ... xn)
    pub fn flip_inplace(&mut self, ind: usize) {
        self.check_var(ind);
        flip_inplace(N, self.table.as_mut(), ind);
    }

    /// Swap two variables in place: f(..., xi, ..., xj, ...) --> f(..., xj, ..., xi, ...)
    pub fn swap_inplace(&mut self, ind1: usize, ind2: usize) {
        self.check_var(ind1);
        self.check_var(ind2);
        swap_inplace(N, self.table.as_mut(), ind1, ind2);
    }

    /// Swap two adjacent variables in place: f(..., xi, x+1, ...) --> f(..., xi+1, xi, ...)
    pub fn swap_adjacent_inplace(&mut self, ind: usize) {
        self.check_var(ind);
        self.check_var(ind + 1);
        swap_adjacent_inplace(N, self.table.as_mut(), ind);
    }

    /// Complement the Lut: f(x) --> !f(x)
    pub fn not(&self) -> StaticLut<N, T> {
        let mut l = *self;
        l.not_inplace();
        l
    }

    /// And two Luts
    pub fn and(&self, rhs: &Self) -> Self {
        let mut l = *self;
        l.and_inplace(rhs);
        l
    }

    /// Or two Luts
    pub fn or(&self, rhs: &Self) -> Self {
        let mut l = *self;
        l.or_inplace(rhs);
        l
    }

    /// Xor two Luts
    pub fn xor(&self, rhs: &Self) -> Self {
        let mut l = *self;
        l.xor_inplace(rhs);
        l
    }

    /// Flip a variable: f(x1, ... xi, ... xn) --> f(x1, ... !xi, ... xn)
    pub fn flip(&self, ind: usize) -> Self {
        let mut l = *self;
        l.flip_inplace(ind);
        l
    }

    /// Swap two variables: f(..., xi, ..., xj, ...) --> f(..., xj, ..., xi, ...)
    pub fn swap(&self, ind1: usize, ind2: usize) -> Self {
        let mut l = *self;
        l.swap_inplace(ind1, ind2);
        l
    }

    /// Swap two adjacent variables: f(..., xi, x+1, ...) --> f(..., xi+1, xi, ...)
    pub fn swap_adjacent(&mut self, ind: usize) -> Self {
        let mut l = *self;
        l.swap_adjacent_inplace(ind);
        l
    }

    /// Obtain the two cofactors with respect to a variable
    pub fn cofactors(&self, ind: usize) -> (Self, Self) {
        let mut c = (*self, *self);
        cofactor0_inplace(self.num_vars(), c.0.table.as_mut(), ind);
        cofactor1_inplace(self.num_vars(), c.1.table.as_mut(), ind);
        c
    }

    /// Create a Lut from its two cofactors
    pub fn from_cofactors(c0: &Self, c1: &Self, ind: usize) -> Self {
        let mut ret = Self::zero();
        from_cofactors_inplace(
            N,
            ret.table.as_mut(),
            c0.table.as_ref(),
            c1.table.as_ref(),
            ind,
        );
        ret
    }

    /// Find the smallest equivalent Lut up to permutation.
    /// Return the canonical representation and the input permutation to obtain it.
    pub fn p_canonization(&self) -> (Self, [u8; N]) {
        let mut work = *self;
        let mut ret = *self;
        let mut perm = [0; N];
        p_canonization(N, work.table.as_mut(), ret.table.as_mut(), perm.as_mut());
        (ret, perm)
    }

    /// Find the smallest equivalent Lut up to input flips and output flip.
    /// Return the canonical representation and the flips to obtain it.
    pub fn n_canonization(&self) -> (Self, u32) {
        let mut work = *self;
        let mut ret = *self;
        let flip = n_canonization(N, work.table.as_mut(), ret.table.as_mut());
        (ret, flip)
    }

    /// Find the smallest equivalent Lut up to permutation, input flips and output flip.
    /// Return the canonical representation and the permutation and flips to obtain it.
    pub fn npn_canonization(&self) -> (Self, [u8; N], u32) {
        let mut work = *self;
        let mut ret = *self;
        let mut perm = [0; N];
        let flip = npn_canonization(N, work.table.as_mut(), ret.table.as_mut(), perm.as_mut());
        (ret, perm, flip)
    }

    /// Decomposition of the function with respect to this variable
    pub fn decomposition(&self, ind: usize) -> DecompositionType {
        decomposition(N, self.table.as_ref(), ind)
    }

    /// Returns whether the function is positive unate
    pub fn is_pos_unate(&self, ind: usize) -> bool {
        input_pos_unate(N, self.table.as_ref(), ind)
    }

    /// Returns whether the function is negative unate
    pub fn is_neg_unate(&self, ind: usize) -> bool {
        input_neg_unate(N, self.table.as_ref(), ind)
    }

    /// Collection of all Luts of this size
    pub fn all_functions() -> StaticLutIterator<N, T> {
        StaticLutIterator {
            lut: StaticLut::zero(),
            ok: true,
        }
    }
}

#[doc(hidden)]
pub struct StaticLutIterator<const N: usize, const T: usize> {
    lut: StaticLut<N, T>,
    ok: bool,
}

impl<const N: usize, const T: usize> Iterator for StaticLutIterator<N, T> {
    type Item = StaticLut<N, T>;

    fn next(&mut self) -> Option<Self::Item> {
        if !self.ok {
            None
        } else {
            let ret = self.lut;
            self.ok = next_inplace(N, self.lut.table.as_mut());
            Some(ret)
        }
    }
}

impl<const N: usize, const T: usize> Ord for StaticLut<N, T> {
    fn cmp(&self, other: &Self) -> Ordering {
        return cmp(self.table.as_ref(), other.table.as_ref());
    }
}

impl<const N: usize, const T: usize> PartialOrd for StaticLut<N, T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<const N: usize, const T: usize> Not for StaticLut<N, T> {
    type Output = Self;
    fn not(self) -> Self::Output {
        let mut l = self;
        l.not_inplace();
        l
    }
}

impl<const N: usize, const T: usize> Not for &'_ StaticLut<N, T> {
    type Output = StaticLut<N, T>;
    fn not(self) -> Self::Output {
        let mut l = *self;
        l.not_inplace();
        l
    }
}

impl<const N: usize, const T: usize> BitAndAssign for StaticLut<N, T> {
    fn bitand_assign(&mut self, rhs: Self) {
        and_inplace(self.table.as_mut(), rhs.table.as_ref());
    }
}

impl<'a, const N: usize, const T: usize> BitAndAssign<&'a StaticLut<N, T>> for StaticLut<N, T> {
    fn bitand_assign(&mut self, rhs: &'a Self) {
        and_inplace(self.table.as_mut(), rhs.table.as_ref());
    }
}

impl<const N: usize, const T: usize> BitAnd for StaticLut<N, T> {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self::Output {
        let mut l = self;
        l &= rhs;
        l
    }
}

impl<'a, const N: usize, const T: usize> BitAnd<&'a StaticLut<N, T>> for StaticLut<N, T> {
    type Output = Self;
    fn bitand(self, rhs: &'a StaticLut<N, T>) -> Self::Output {
        let mut l = self;
        l &= rhs;
        l
    }
}

impl<const N: usize, const T: usize> BitOrAssign for StaticLut<N, T> {
    fn bitor_assign(&mut self, rhs: Self) {
        or_inplace(self.table.as_mut(), rhs.table.as_ref());
    }
}

impl<'a, const N: usize, const T: usize> BitOrAssign<&'a StaticLut<N, T>> for StaticLut<N, T> {
    fn bitor_assign(&mut self, rhs: &'a Self) {
        or_inplace(self.table.as_mut(), rhs.table.as_ref());
    }
}

impl<const N: usize, const T: usize> BitOr for StaticLut<N, T> {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self::Output {
        let mut l = self;
        l |= rhs;
        l
    }
}

impl<'a, const N: usize, const T: usize> BitOr<&'a StaticLut<N, T>> for StaticLut<N, T> {
    type Output = Self;
    fn bitor(self, rhs: &'a StaticLut<N, T>) -> Self::Output {
        let mut l = self;
        l |= rhs;
        l
    }
}

impl<const N: usize, const T: usize> BitXorAssign for StaticLut<N, T> {
    fn bitxor_assign(&mut self, rhs: Self) {
        xor_inplace(self.table.as_mut(), rhs.table.as_ref());
    }
}

impl<'a, const N: usize, const T: usize> BitXorAssign<&'a StaticLut<N, T>> for StaticLut<N, T> {
    fn bitxor_assign(&mut self, rhs: &'a Self) {
        xor_inplace(self.table.as_mut(), rhs.table.as_ref());
    }
}

impl<const N: usize, const T: usize> BitXor for StaticLut<N, T> {
    type Output = Self;
    fn bitxor(self, rhs: Self) -> Self::Output {
        let mut l = self;
        l ^= rhs;
        l
    }
}

impl<'a, const N: usize, const T: usize> BitXor<&'a StaticLut<N, T>> for StaticLut<N, T> {
    type Output = Self;
    fn bitxor(self, rhs: &'a StaticLut<N, T>) -> Self::Output {
        let mut l = self;
        l ^= rhs;
        l
    }
}

impl<const N: usize, const T: usize> fmt::Display for StaticLut<N, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt_hex(N, self.table.as_ref(), f)
    }
}

impl<const N: usize, const T: usize> fmt::LowerHex for StaticLut<N, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt_hex(N, self.table.as_ref(), f)
    }
}

impl<const N: usize, const T: usize> fmt::Binary for StaticLut<N, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt_bin(N, self.table.as_ref(), f)
    }
}

/// 0-input Lut
#[doc(hidden)]
pub type Lut0 = StaticLut<0, 1>;
/// 1-input Lut
#[doc(hidden)]
pub type Lut1 = StaticLut<1, 1>;
/// 2-input Lut
pub type Lut2 = StaticLut<2, 1>;
/// 3-input Lut
pub type Lut3 = StaticLut<3, 1>;
/// 4-input Lut
pub type Lut4 = StaticLut<4, 1>;
/// 5-input Lut
pub type Lut5 = StaticLut<5, 1>;
/// 6-input Lut
pub type Lut6 = StaticLut<6, 1>;
/// 7-input Lut
pub type Lut7 = StaticLut<7, 2>;
/// 8-input Lut
pub type Lut8 = StaticLut<8, 4>;
/// 9-input Lut
pub type Lut9 = StaticLut<9, 8>;
/// 10-input Lut
pub type Lut10 = StaticLut<10, 16>;
/// 11-input Lut
pub type Lut11 = StaticLut<11, 32>;
/// 12-input Lut
pub type Lut12 = StaticLut<12, 64>;

#[cfg(test)]
mod tests {
    use crate::{Lut0, Lut1, Lut2, Lut3, Lut4};

    #[test]
    fn test_symmetric() {
        assert_eq!(Lut3::majority().to_string(), "Lut3(e8)");
        assert_eq!(Lut4::majority().to_string(), "Lut4(fee8)");
        assert_eq!(Lut3::equals(0).to_string(), "Lut3(01)");
        assert_eq!(Lut4::equals(0).to_string(), "Lut4(0001)");
        assert_eq!(Lut3::equals(1).to_string(), "Lut3(16)");
        assert_eq!(Lut4::equals(1).to_string(), "Lut4(0116)");
        assert_eq!(Lut3::parity().to_string(), "Lut3(96)");
        assert_eq!(Lut4::parity().to_string(), "Lut4(6996)");
    }

    #[test]
    fn test_display() {
        assert_eq!(format!("{:}", Lut0::zero()), "Lut0(0)");
        assert_eq!(format!("{:}", Lut0::one()), "Lut0(1)");
        assert_eq!(format!("{:}", Lut1::zero()), "Lut1(0)");
        assert_eq!(format!("{:}", Lut1::one()), "Lut1(3)");
        assert_eq!(format!("{:}", Lut2::zero()), "Lut2(0)");
        assert_eq!(format!("{:}", Lut2::one()), "Lut2(f)");
        assert_eq!(format!("{:}", Lut3::zero()), "Lut3(00)");
        assert_eq!(format!("{:}", Lut3::one()), "Lut3(ff)");
    }
}