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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
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::bdd::*;
use crate::canonization::*;
use crate::decomposition::*;
use crate::operations::*;
use crate::Lut;

/// 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
    }

    /// Query the number of 64-bit blocks in the Lut
    pub fn num_blocks(&self) -> usize {
        table_size(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
    }

    /// Create a random Lut
    #[cfg(feature = "rand")]
    pub fn random() -> Self {
        let mut ret = Self::default();
        fill_random(N, ret.table.as_mut());
        ret
    }

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

    /// 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 (input bits packed in the mask)
    pub fn set_value(&mut self, mask: usize, value: bool) {
        if value {
            self.set_bit(mask)
        } else {
            self.unset_bit(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
    }

    /// Return the internal representation as 64-bit blocks
    pub fn blocks(&self) -> &[u64] {
        self.table.as_ref()
    }

    /// Create a Lut from its internal representation as 64-bit blocks
    pub fn from_blocks(blocks: &[u64]) -> Self {
        let mut ret = Self::default();
        ret.table.clone_from_slice(blocks);
        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)
    }

    /// Top decomposition of the function with respect to this variable
    pub fn top_decomposition(&self, ind: usize) -> DecompositionType {
        top_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,
        }
    }

    /// Compute the number of nodes in the BDD representing these functions
    ///
    /// This function uses the natural variable order (0 to num_vars) to build the BDD.
    /// This may not be the smallest possible BDD.
    pub fn bdd_complexity(luts: &[Self]) -> usize {
        let mut table = Vec::<u64>::new();
        for l in luts {
            table.extend(l.blocks().iter());
        }
        table_complexity(N, table.as_slice())
    }

    /// Return the hexadecimal string representing the function
    ///
    /// Contrary to display, nothing else in printed: `a45b` instead of `Lut4(a45b)`
    pub fn to_hex_string(&self) -> String {
        to_hex(self.num_vars(), self.table.as_ref())
    }

    /// Return the binary string representing the function
    ///
    /// Contrary to display, nothing else in printed: `0101` instead of `Lut2(0101)`
    pub fn to_bin_string(&self) -> String {
        to_bin(self.num_vars(), self.table.as_ref())
    }

    /// Build a Lut from an hexadecimal string
    pub fn from_hex_string(s: &str) -> Result<Self, ()> {
        let mut ret = Self::zero();
        fill_hex(ret.num_vars(), ret.table.as_mut(), s)?;
        Ok(ret)
    }
}

#[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<StaticLut<N, T>> for StaticLut<N, T> {
    fn bitand_assign(&mut self, rhs: Self) {
        and_inplace(self.table.as_mut(), rhs.table.as_ref());
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

impl<const N: usize, const T: usize> BitXor<&StaticLut<N, T>> for &StaticLut<N, T> {
    type Output = StaticLut<N, T>;
    fn bitxor(self, rhs: &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)
    }
}

impl<const N: usize, const T: usize> TryFrom<Lut> for StaticLut<N, T> {
    type Error = ();

    fn try_from(lut: Lut) -> Result<Self, Self::Error> {
        if lut.num_vars() != N {
            return Err(());
        }
        Ok(StaticLut::<N, T>::from_blocks(lut.blocks()))
    }
}

impl<const N: usize, const T: usize> From<StaticLut<N, T>> for Lut {
    fn from(lut: StaticLut<N, T>) -> Lut {
        Lut::from_blocks(lut.num_vars(), lut.blocks())
    }
}

/// 0-input Lut
pub type Lut0 = StaticLut<0, 1>;
/// 1-input Lut
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>;

impl From<u8> for Lut3 {
    fn from(table: u8) -> Lut3 {
        Lut3::from_blocks(&[table as u64])
    }
}

impl From<u16> for Lut4 {
    fn from(table: u16) -> Lut4 {
        Lut4::from_blocks(&[table as u64])
    }
}

impl From<u32> for Lut5 {
    fn from(table: u32) -> Lut5 {
        Lut5::from_blocks(&[table as u64])
    }
}

impl From<u64> for Lut6 {
    fn from(table: u64) -> Lut6 {
        Lut6::from_blocks(&[table])
    }
}

impl From<Lut3> for u8 {
    fn from(lut: Lut3) -> u8 {
        (lut.table[0] & !VAR_MASK[3]) as u8
    }
}

impl From<Lut4> for u16 {
    fn from(lut: Lut4) -> u16 {
        (lut.table[0] & !VAR_MASK[4]) as u16
    }
}

impl From<Lut5> for u32 {
    fn from(lut: Lut5) -> u32 {
        (lut.table[0] & !VAR_MASK[5]) as u32
    }
}

impl From<Lut6> for u64 {
    fn from(lut: Lut6) -> u64 {
        lut.table[0]
    }
}

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

    #[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)");
        assert_eq!(format!("{:}", Lut4::zero()), "Lut4(0000)");
        assert_eq!(format!("{:}", Lut4::one()), "Lut4(ffff)");
        assert_eq!(format!("{:}", Lut5::zero()), "Lut5(00000000)");
        assert_eq!(format!("{:}", Lut5::one()), "Lut5(ffffffff)");
        assert_eq!(format!("{:}", Lut6::zero()), "Lut6(0000000000000000)");
        assert_eq!(format!("{:}", Lut6::one()), "Lut6(ffffffffffffffff)");
        assert_eq!(
            format!("{:}", Lut7::zero()),
            "Lut7(00000000000000000000000000000000)"
        );
        assert_eq!(
            format!("{:}", Lut7::one()),
            "Lut7(ffffffffffffffffffffffffffffffff)"
        );
    }

    #[test]
    #[allow(
        unused_must_use,
        clippy::no_effect,
        clippy::unnecessary_operation,
        clippy::op_ref
    )]
    fn test_ops() {
        let mut a = Lut6::nth_var(0);
        let b = Lut6::nth_var(1);
        !a;
        !&a;
        &a & &b;
        &a & b;
        a & &b;
        a & b;
        &a | &b;
        &a | b;
        a | &b;
        a | b;
        &a ^ &b;
        &a ^ b;
        a ^ &b;
        a ^ b;
        a &= b;
        a &= &b;
        a |= b;
        a |= &b;
        a ^= b;
        a ^= &b;
    }

    #[test]
    #[cfg(feature = "rand")]
    fn test_random() {
        Lut0::random();
        Lut1::random();
        Lut2::random();
        Lut3::random();
        Lut4::random();
        Lut5::random();
        Lut6::random();
        Lut7::random();
    }

    #[test]
    #[cfg(feature = "rand")]
    fn test_lut_conversion() {
        use crate::{Lut, Lut7};
        for _ in 0..10 {
            let lut = Lut3::random();
            assert_eq!(lut, Lut3::try_from(Lut::from(lut)).unwrap());
        }
        for _ in 0..10 {
            let lut = Lut7::random();
            assert_eq!(lut, Lut7::try_from(Lut::from(lut)).unwrap());
        }
    }

    #[test]
    #[cfg(feature = "rand")]
    fn test_int_conversion() {
        for _ in 0..10 {
            let lut = Lut3::random();
            assert_eq!(lut, Lut3::from(u8::from(lut)));
        }
        for _ in 0..10 {
            let lut = Lut4::random();
            assert_eq!(lut, Lut4::from(u16::from(lut)));
        }
        for _ in 0..10 {
            let lut = Lut5::random();
            assert_eq!(lut, Lut5::from(u32::from(lut)));
        }
        for _ in 0..10 {
            let lut = Lut6::random();
            assert_eq!(lut, Lut6::from(u64::from(lut)));
        }
    }

    #[test]
    #[cfg(feature = "rand")]
    fn test_string_conversion() {
        use crate::Lut8;

        for _ in 0..10 {
            let lut = Lut0::random();
            assert_eq!(lut, Lut0::from_hex_string(&lut.to_hex_string()).unwrap());
        }
        for _ in 0..10 {
            let lut = Lut1::random();
            assert_eq!(lut, Lut1::from_hex_string(&lut.to_hex_string()).unwrap());
        }
        for _ in 0..10 {
            let lut = Lut2::random();
            assert_eq!(lut, Lut2::from_hex_string(&lut.to_hex_string()).unwrap());
        }
        for _ in 0..10 {
            let lut = Lut3::random();
            assert_eq!(lut, Lut3::from_hex_string(&lut.to_hex_string()).unwrap());
        }
        for _ in 0..10 {
            let lut = Lut8::random();
            assert_eq!(lut, Lut8::from_hex_string(&lut.to_hex_string()).unwrap());
        }
    }
}