Skip to main content

prjunnamed_netlist/
logic.rs

1use std::{
2    borrow::{Borrow, BorrowMut, Cow},
3    fmt::{Debug, Display},
4    ops::{Index, IndexMut},
5    slice::SliceIndex,
6    str::FromStr,
7};
8
9use bytemuck::TransparentWrapper;
10
11use crate::ValueBit;
12
13/// An extended binary value.
14///
15/// In addition to the usual `0` and `1`, the `X` value (also known as "undef") means that either `0` and `1`
16/// may be encountered. The undef value is used in both optimization and simulation, and its exact semantics
17/// depends on the context where it is used.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum ConstBit {
20    Undef = -1,
21    Zero = 0,
22    One = 1,
23}
24
25#[derive(Debug, Copy, Clone)]
26pub struct InvalidConstCharacter;
27
28impl ConstBit {
29    pub fn from_char(chr: char) -> Result<Self, InvalidConstCharacter> {
30        match chr {
31            '0' => Ok(ConstBit::Zero),
32            '1' => Ok(ConstBit::One),
33            'X' => Ok(ConstBit::Undef),
34            _ => Err(InvalidConstCharacter),
35        }
36    }
37
38    pub fn lit(chr: char) -> Self {
39        Self::from_char(chr).unwrap()
40    }
41
42    pub fn combine(lft: ConstBit, rgt: ConstBit) -> Option<ConstBit> {
43        match (lft, rgt) {
44            (ConstBit::Undef, bit) | (bit, ConstBit::Undef) => Some(bit),
45            _ if lft == rgt => Some(lft),
46            _ => None,
47        }
48    }
49
50    pub fn mux(self, values: [impl AsRef<ConstSlice>; 2]) -> Const {
51        let [val0, val1] = values;
52        let val0 = val0.as_ref();
53        let val1 = val1.as_ref();
54        match self {
55            ConstBit::Zero => val0.to_owned(),
56            ConstBit::One => val1.to_owned(),
57            ConstBit::Undef => {
58                Const::from_iter(val0.iter().zip(val1.iter()).map(|(x, y)| if x == y { x } else { ConstBit::Undef }))
59            }
60        }
61    }
62}
63
64impl Display for ConstBit {
65    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
66        match self {
67            ConstBit::Undef => write!(f, "X"),
68            ConstBit::Zero => write!(f, "0"),
69            ConstBit::One => write!(f, "1"),
70        }
71    }
72}
73
74impl FromStr for ConstBit {
75    type Err = ();
76
77    fn from_str(s: &str) -> Result<Self, Self::Err> {
78        match s {
79            "X" => Ok(ConstBit::Undef),
80            "0" => Ok(ConstBit::Zero),
81            "1" => Ok(ConstBit::One),
82            _ => Err(()),
83        }
84    }
85}
86
87impl From<bool> for ConstBit {
88    fn from(value: bool) -> Self {
89        match value {
90            false => ConstBit::Zero,
91            true => ConstBit::One,
92        }
93    }
94}
95
96impl TryFrom<ValueBit> for ConstBit {
97    type Error = ();
98
99    fn try_from(value: ValueBit) -> Result<Self, Self::Error> {
100        if value == ValueBit::UNDEF {
101            Ok(ConstBit::Undef)
102        } else if value == ValueBit::ZERO {
103            Ok(ConstBit::Zero)
104        } else if value == ValueBit::ONE {
105            Ok(ConstBit::One)
106        } else {
107            Err(())
108        }
109    }
110}
111
112impl std::ops::Not for ConstBit {
113    type Output = ConstBit;
114
115    fn not(self) -> Self::Output {
116        match self {
117            ConstBit::One => ConstBit::Zero,
118            ConstBit::Zero => ConstBit::One,
119            ConstBit::Undef => ConstBit::Undef,
120        }
121    }
122}
123
124impl std::ops::BitAnd<ConstBit> for ConstBit {
125    type Output = ConstBit;
126
127    fn bitand(self, rhs: ConstBit) -> Self::Output {
128        match (self, rhs) {
129            (ConstBit::Zero, _) => ConstBit::Zero,
130            (_, ConstBit::Zero) => ConstBit::Zero,
131            (ConstBit::Undef, _) => ConstBit::Undef,
132            (_, ConstBit::Undef) => ConstBit::Undef,
133            (ConstBit::One, ConstBit::One) => ConstBit::One,
134        }
135    }
136}
137
138impl std::ops::BitOr<ConstBit> for ConstBit {
139    type Output = ConstBit;
140
141    fn bitor(self, rhs: ConstBit) -> Self::Output {
142        !(!self & !rhs)
143    }
144}
145
146impl std::ops::BitXor<ConstBit> for ConstBit {
147    type Output = ConstBit;
148
149    fn bitxor(self, rhs: ConstBit) -> Self::Output {
150        match (self, rhs) {
151            (ConstBit::Undef, _) => ConstBit::Undef,
152            (_, ConstBit::Undef) => ConstBit::Undef,
153            (ConstBit::One, ConstBit::One) => ConstBit::Zero,
154            (ConstBit::One, ConstBit::Zero) => ConstBit::One,
155            (ConstBit::Zero, ConstBit::One) => ConstBit::One,
156            (ConstBit::Zero, ConstBit::Zero) => ConstBit::Zero,
157        }
158    }
159}
160
161/// A constant is a (possibly empty) sequence of [`ConstBit`]s.
162#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
163pub struct Const {
164    bits: Vec<ConstBit>,
165}
166
167#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
168#[repr(transparent)]
169pub struct ConstSlice {
170    bits: [ConstBit],
171}
172
173// SAFETY: `ConstSlice` is `repr(transparent)` and has only one field, which is of type `[ConstBit]`.
174// There is no additional alignment requirement.
175unsafe impl TransparentWrapper<[ConstBit]> for ConstSlice {}
176
177impl Const {
178    /// Creates an empty constant.
179    pub const fn new() -> Self {
180        Self { bits: vec![] }
181    }
182
183    /// Creates an all-`0` constant of given width.
184    pub fn zero(width: usize) -> Self {
185        Self::from_iter(std::iter::repeat_n(ConstBit::Zero, width))
186    }
187
188    /// Creates an all-`1` constant of given width.
189    pub fn ones(width: usize) -> Self {
190        Self::from_iter(std::iter::repeat_n(ConstBit::One, width))
191    }
192
193    /// Creates an all-`X` constant of given width.
194    pub fn undef(width: usize) -> Self {
195        Self::from_iter(std::iter::repeat_n(ConstBit::Undef, width))
196    }
197
198    /// Creates a constant of given width that has a `1` at position `hot_at` and `0` elsewhere.
199    pub fn one_hot(width: usize, hot_at: usize) -> Self {
200        assert!(hot_at < width);
201        Self::from_iter((0..width).map(|index| ConstBit::from(index == hot_at)))
202    }
203
204    /// Expands the constant by a single position with the given value.
205    pub fn push(&mut self, bit: impl Into<ConstBit>) {
206        self.bits.push(bit.into());
207    }
208
209    pub fn truncate(&mut self, width: usize) {
210        assert!(width <= self.len());
211        self.bits.truncate(width);
212    }
213
214    pub fn from_uint(val: u128, width: usize) -> Self {
215        if width < 128 {
216            assert!(val < (1 << width));
217        }
218        Self::from_iter((0..width).map(|i| ConstBit::from(i < u128::BITS as usize && ((val >> i) & 1) != 0)))
219    }
220
221    pub fn lit(value: &str) -> Self {
222        value.parse().unwrap()
223    }
224
225    pub fn combine(lft: impl AsRef<ConstSlice>, rgt: impl AsRef<ConstSlice>) -> Option<Const> {
226        let (lft, rgt) = (lft.as_ref(), rgt.as_ref());
227        assert_eq!(lft.len(), rgt.len());
228        let mut bits = vec![];
229        for (lft, rgt) in std::iter::zip(lft.iter(), rgt.iter()) {
230            bits.push(ConstBit::combine(lft, rgt)?);
231        }
232        Some(Const { bits })
233    }
234
235    pub fn as_slice(&self) -> &ConstSlice {
236        &self[..]
237    }
238
239    pub fn as_slice_mut(&mut self) -> &mut ConstSlice {
240        &mut self[..]
241    }
242}
243
244impl ConstSlice {
245    pub fn len(&self) -> usize {
246        self.bits.len()
247    }
248
249    pub fn is_empty(&self) -> bool {
250        self.bits.is_empty()
251    }
252
253    pub fn iter(&self) -> impl DoubleEndedIterator<Item = ConstBit> + ExactSizeIterator + '_ {
254        self.bits.iter().copied()
255    }
256
257    pub fn lsb(&self) -> ConstBit {
258        *self.bits.first().unwrap()
259    }
260
261    pub fn msb(&self) -> ConstBit {
262        *self.bits.last().unwrap()
263    }
264
265    pub fn is_zero(&self) -> bool {
266        self.bits.iter().all(|&bit| bit == ConstBit::Zero)
267    }
268
269    pub fn is_ones(&self) -> bool {
270        self.bits.iter().all(|&bit| bit == ConstBit::One)
271    }
272
273    pub fn is_undef(&self) -> bool {
274        self.bits.iter().all(|&bit| bit == ConstBit::Undef)
275    }
276
277    pub fn has_undef(&self) -> bool {
278        self.bits.contains(&ConstBit::Undef)
279    }
280
281    pub fn as_power_of_two(&self) -> Option<u32> {
282        let mut result = None;
283        for (offset, bit) in self.bits.iter().copied().enumerate() {
284            if bit == ConstBit::Undef {
285                return None;
286            }
287            if bit == ConstBit::One {
288                if result.is_some() {
289                    return None;
290                }
291                result = Some(offset as u32);
292            }
293        }
294        result
295    }
296
297    pub fn concat(&self, other: impl AsRef<ConstSlice>) -> Const {
298        Const::from_iter(self.iter().chain(other.as_ref()))
299    }
300
301    pub fn repeat(&self, count: usize) -> Const {
302        Const::from_iter((0..count).flat_map(|_| self))
303    }
304
305    pub fn adc(&self, other: impl AsRef<ConstSlice>, ci: ConstBit) -> Const {
306        let other = other.as_ref();
307        assert_eq!(self.len(), other.len());
308        let mut sum = vec![];
309        let mut carry = ci;
310        for (a, b) in self.iter().zip(other) {
311            let (y, co) = match (a, b, carry) {
312                (ConstBit::Undef, _, _) => (ConstBit::Undef, ConstBit::Undef),
313                (_, ConstBit::Undef, _) => (ConstBit::Undef, ConstBit::Undef),
314                (_, _, ConstBit::Undef) => (ConstBit::Undef, ConstBit::Undef),
315                (ConstBit::Zero, ConstBit::Zero, s) => (s, ConstBit::Zero),
316                (ConstBit::Zero, s, ConstBit::Zero) => (s, ConstBit::Zero),
317                (s, ConstBit::Zero, ConstBit::Zero) => (s, ConstBit::Zero),
318                (ConstBit::One, ConstBit::One, s) => (s, ConstBit::One),
319                (ConstBit::One, s, ConstBit::One) => (s, ConstBit::One),
320                (s, ConstBit::One, ConstBit::One) => (s, ConstBit::One),
321            };
322            carry = co;
323            sum.push(y);
324        }
325        sum.push(carry);
326        Const::from_iter(sum)
327    }
328
329    pub fn eq_inner(&self, other: impl AsRef<ConstSlice>) -> ConstBit {
330        let other = other.as_ref();
331        assert_eq!(self.len(), other.len());
332        let mut undef = false;
333        for (x, y) in self.iter().zip(other) {
334            if x == ConstBit::Undef || y == ConstBit::Undef {
335                undef = true;
336            } else if x != y {
337                return ConstBit::Zero;
338            }
339        }
340        if undef { ConstBit::Undef } else { ConstBit::One }
341    }
342
343    pub fn ult(&self, other: impl AsRef<ConstSlice>) -> ConstBit {
344        let other = other.as_ref();
345        assert_eq!(self.len(), other.len());
346        if self.has_undef() || other.has_undef() {
347            ConstBit::Undef
348        } else {
349            for (x, y) in self.iter().zip(other).rev() {
350                if x != y {
351                    return ConstBit::from(x < y);
352                }
353            }
354            ConstBit::Zero
355        }
356    }
357
358    pub fn slt(&self, other: impl AsRef<ConstSlice>) -> ConstBit {
359        let other = other.as_ref();
360        assert_eq!(self.len(), other.len());
361        if self.has_undef() || other.has_undef() {
362            ConstBit::Undef
363        } else if self.msb() != other.msb() {
364            ConstBit::from(self.msb() > other.msb())
365        } else {
366            for (x, y) in self.iter().zip(other).rev() {
367                if x != y {
368                    return ConstBit::from(x < y);
369                }
370            }
371            ConstBit::Zero
372        }
373    }
374
375    pub fn mul(&self, other: impl AsRef<ConstSlice>) -> Const {
376        let other = other.as_ref();
377        assert_eq!(self.len(), other.len());
378        if self.has_undef() || other.has_undef() {
379            Const::undef(self.len())
380        } else {
381            let mut res = Const::zero(self.len());
382            for (i, bit) in other.iter().enumerate() {
383                if bit == ConstBit::One {
384                    res = res.adc(Const::zero(i).concat(self), ConstBit::Zero);
385                } else {
386                    res.bits.push(ConstBit::Zero);
387                }
388            }
389            res.truncate(self.len());
390            res
391        }
392    }
393
394    pub fn copy_from_slice(&mut self, other: impl AsRef<ConstSlice>) {
395        self.bits.copy_from_slice(&other.as_ref().bits);
396    }
397}
398
399impl AsRef<ConstSlice> for ConstSlice {
400    fn as_ref(&self) -> &ConstSlice {
401        self
402    }
403}
404
405impl AsMut<ConstSlice> for ConstSlice {
406    fn as_mut(&mut self) -> &mut ConstSlice {
407        self
408    }
409}
410
411impl AsRef<ConstSlice> for Const {
412    fn as_ref(&self) -> &ConstSlice {
413        ConstSlice::wrap_ref(&self.bits)
414    }
415}
416
417impl AsMut<ConstSlice> for Const {
418    fn as_mut(&mut self) -> &mut ConstSlice {
419        ConstSlice::wrap_mut(&mut self.bits)
420    }
421}
422
423impl AsRef<ConstSlice> for ConstBit {
424    fn as_ref(&self) -> &ConstSlice {
425        ConstSlice::wrap_ref(std::slice::from_ref(self))
426    }
427}
428
429impl AsMut<ConstSlice> for ConstBit {
430    fn as_mut(&mut self) -> &mut ConstSlice {
431        ConstSlice::wrap_mut(std::slice::from_mut(self))
432    }
433}
434
435impl Borrow<ConstSlice> for Const {
436    fn borrow(&self) -> &ConstSlice {
437        self
438    }
439}
440
441impl BorrowMut<ConstSlice> for Const {
442    fn borrow_mut(&mut self) -> &mut ConstSlice {
443        self
444    }
445}
446
447impl std::borrow::ToOwned for ConstSlice {
448    type Owned = Const;
449
450    fn to_owned(&self) -> Self::Owned {
451        Const::from_iter(self)
452    }
453}
454
455impl std::ops::Deref for Const {
456    type Target = ConstSlice;
457
458    fn deref(&self) -> &Self::Target {
459        self.as_ref()
460    }
461}
462
463impl std::ops::DerefMut for Const {
464    fn deref_mut(&mut self) -> &mut Self::Target {
465        self.as_mut()
466    }
467}
468
469impl<Idx, Wrap: ?Sized> Index<Idx> for ConstSlice
470where
471    Idx: SliceIndex<[ConstBit], Output = Wrap>,
472    Wrap: ConstIndexWrapper + 'static,
473{
474    type Output = Wrap::Output;
475
476    fn index(&self, index: Idx) -> &Self::Output {
477        self.bits[index].wrap()
478    }
479}
480
481impl<Idx, Wrap: ?Sized> IndexMut<Idx> for ConstSlice
482where
483    Idx: SliceIndex<[ConstBit], Output = Wrap>,
484    Wrap: ConstIndexWrapper + 'static,
485{
486    fn index_mut(&mut self, index: Idx) -> &mut Self::Output {
487        self.bits[index].wrap_mut()
488    }
489}
490
491pub trait ConstIndexWrapper {
492    type Output: ?Sized;
493
494    fn wrap(&self) -> &Self::Output;
495    fn wrap_mut(&mut self) -> &mut Self::Output;
496}
497
498impl ConstIndexWrapper for ConstBit {
499    type Output = ConstBit;
500
501    fn wrap(&self) -> &Self::Output {
502        self
503    }
504
505    fn wrap_mut(&mut self) -> &mut Self::Output {
506        self
507    }
508}
509
510impl ConstIndexWrapper for [ConstBit] {
511    type Output = ConstSlice;
512
513    fn wrap(&self) -> &Self::Output {
514        ConstSlice::wrap_ref(self)
515    }
516
517    fn wrap_mut(&mut self) -> &mut Self::Output {
518        ConstSlice::wrap_mut(self)
519    }
520}
521
522impl Debug for ConstSlice {
523    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
524        write!(f, "Const::lit(\"{self}\")[..]")
525    }
526}
527
528impl Debug for Const {
529    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
530        write!(f, "Const::lit(\"{self}\")")
531    }
532}
533
534impl Display for ConstSlice {
535    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
536        for bit in self.bits.iter().rev() {
537            write!(f, "{bit}")?;
538        }
539        Ok(())
540    }
541}
542
543impl Display for Const {
544    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
545        write!(f, "{}", self.as_slice())
546    }
547}
548
549impl FromStr for Const {
550    type Err = InvalidConstCharacter;
551
552    fn from_str(s: &str) -> Result<Self, Self::Err> {
553        let mut bits = vec![];
554        for char in s.chars().rev() {
555            bits.push(ConstBit::from_char(char)?)
556        }
557        Ok(Const { bits })
558    }
559}
560
561#[derive(Debug, Copy, Clone)]
562pub enum ConstToIntError {
563    HasUndef,
564    Overflow,
565}
566
567impl TryFrom<&ConstSlice> for u64 {
568    type Error = ConstToIntError;
569
570    fn try_from(value: &ConstSlice) -> Result<Self, Self::Error> {
571        if value.has_undef() {
572            return Err(ConstToIntError::HasUndef);
573        }
574        let mut result = 0;
575        for (index, bit) in value.iter().enumerate() {
576            if bit == ConstBit::One {
577                if index >= 64 {
578                    return Err(ConstToIntError::Overflow);
579                }
580                result |= 1 << index;
581            }
582        }
583        Ok(result)
584    }
585}
586
587impl TryFrom<&ConstSlice> for i64 {
588    type Error = ConstToIntError;
589
590    fn try_from(value: &ConstSlice) -> Result<Self, Self::Error> {
591        if value.has_undef() {
592            return Err(ConstToIntError::HasUndef);
593        }
594        let mut width = value.len();
595        while width > 1 && value[width - 1] == value[width - 2] {
596            width -= 1;
597        }
598        if width > Self::BITS as usize {
599            return Err(ConstToIntError::Overflow);
600        }
601        let mut result = 0;
602        for (index, bit) in value.iter().enumerate() {
603            if bit == ConstBit::One {
604                if index == width - 1 {
605                    result |= -1 << index;
606                } else {
607                    result |= 1 << index;
608                }
609            }
610        }
611        Ok(result)
612    }
613}
614
615impl TryFrom<&Const> for u64 {
616    type Error = ConstToIntError;
617
618    fn try_from(value: &Const) -> Result<Self, Self::Error> {
619        value.as_slice().try_into()
620    }
621}
622
623impl TryFrom<&Const> for i64 {
624    type Error = ConstToIntError;
625
626    fn try_from(value: &Const) -> Result<Self, Self::Error> {
627        value.as_slice().try_into()
628    }
629}
630
631impl Extend<ConstBit> for Const {
632    fn extend<T: IntoIterator<Item = ConstBit>>(&mut self, iter: T) {
633        for bit in iter {
634            self.bits.push(bit);
635        }
636    }
637}
638
639impl From<ConstBit> for Const {
640    fn from(bit: ConstBit) -> Self {
641        Const { bits: vec![bit] }
642    }
643}
644
645impl From<Vec<ConstBit>> for Const {
646    fn from(bit: Vec<ConstBit>) -> Self {
647        Const { bits: bit }
648    }
649}
650
651impl From<ConstBit> for Cow<'_, ConstSlice> {
652    fn from(value: ConstBit) -> Self {
653        Cow::Owned(Const::from(value))
654    }
655}
656
657impl From<Const> for Cow<'_, ConstSlice> {
658    fn from(value: Const) -> Self {
659        Cow::Owned(value)
660    }
661}
662
663impl<'a> From<&'a Const> for Cow<'a, ConstSlice> {
664    fn from(value: &'a Const) -> Self {
665        Cow::Borrowed(value)
666    }
667}
668
669impl<'a> From<&'a ConstSlice> for Cow<'a, ConstSlice> {
670    fn from(value: &'a ConstSlice) -> Self {
671        Cow::Borrowed(value)
672    }
673}
674
675impl FromIterator<ConstBit> for Const {
676    fn from_iter<T: IntoIterator<Item = ConstBit>>(iter: T) -> Self {
677        Const { bits: iter.into_iter().collect() }
678    }
679}
680
681impl<'a> IntoIterator for &'a ConstSlice {
682    type Item = ConstBit;
683
684    type IntoIter = std::iter::Copied<std::slice::Iter<'a, ConstBit>>;
685
686    fn into_iter(self) -> Self::IntoIter {
687        self.bits.iter().copied()
688    }
689}
690
691impl<'a> IntoIterator for &'a Const {
692    type Item = ConstBit;
693
694    type IntoIter = std::iter::Copied<std::slice::Iter<'a, ConstBit>>;
695
696    fn into_iter(self) -> Self::IntoIter {
697        self[..].into_iter()
698    }
699}
700
701impl IntoIterator for Const {
702    type Item = ConstBit;
703    type IntoIter = std::vec::IntoIter<ConstBit>;
704
705    fn into_iter(self) -> Self::IntoIter {
706        self.bits.into_iter()
707    }
708}
709
710impl std::ops::Not for &ConstSlice {
711    type Output = Const;
712
713    fn not(self) -> Const {
714        Const::from_iter(self.iter().map(|x| !x))
715    }
716}
717
718impl std::ops::Not for &Const {
719    type Output = Const;
720
721    fn not(self) -> Const {
722        !self.as_ref()
723    }
724}
725
726impl std::ops::Not for Const {
727    type Output = Const;
728
729    fn not(self) -> Const {
730        !self.as_ref()
731    }
732}
733
734macro_rules! impl_bitop {
735    ($BitTrait:ident, $bitmthd:ident, $op:tt) => {
736        impl<Rhs: AsRef<ConstSlice>> std::ops::$BitTrait<Rhs> for &ConstSlice {
737            type Output = Const;
738
739            fn $bitmthd(self, rhs: Rhs) -> Self::Output {
740                let rhs = rhs.as_ref();
741                assert_eq!(self.len(), rhs.len());
742                Const::from_iter(self.iter().zip(rhs.iter()).map(|(x, y)| x $op y))
743            }
744        }
745
746        impl<Rhs: AsRef<ConstSlice>> std::ops::$BitTrait<Rhs> for &Const {
747            type Output = Const;
748
749            fn $bitmthd(self, rhs: Rhs) -> Self::Output {
750                self.as_ref() $op rhs
751            }
752        }
753
754        impl<Rhs: AsRef<ConstSlice>> std::ops::$BitTrait<Rhs> for Const {
755            type Output = Const;
756
757            fn $bitmthd(self, rhs: Rhs) -> Self::Output {
758                self.as_ref() $op rhs
759            }
760        }
761    }
762}
763
764impl_bitop!(BitAnd, bitand, &);
765impl_bitop!(BitOr, bitor, |);
766impl_bitop!(BitXor, bitxor, ^);
767
768#[cfg(test)]
769mod test {
770    use crate::{Const, ConstBit};
771
772    #[test]
773    fn test_not() {
774        for (a, y) in [("", ""), ("01", "10"), ("X10", "X01")] {
775            assert_eq!(!Const::lit(a), Const::lit(y));
776        }
777    }
778
779    #[test]
780    fn test_and() {
781        for (a, b, y) in [("", "", ""), ("1010", "1100", "1000"), ("X0X0", "XX00", "X000"), ("X1X1", "XX11", "XXX1")] {
782            assert_eq!(Const::lit(a) & Const::lit(b), Const::lit(y));
783        }
784    }
785
786    #[test]
787    fn test_or() {
788        for (a, b, y) in [("", "", ""), ("1010", "1100", "1110"), ("X0X0", "XX00", "XXX0"), ("X1X1", "XX11", "X111")] {
789            assert_eq!(Const::lit(a) | Const::lit(b), Const::lit(y));
790        }
791    }
792
793    #[test]
794    fn test_xor() {
795        for (a, b, y) in [("", "", ""), ("1010", "1100", "0110"), ("X0X0", "XX00", "XXX0"), ("X1X1", "XX11", "XXX0")] {
796            assert_eq!(Const::lit(a) ^ Const::lit(b), Const::lit(y));
797        }
798    }
799
800    #[test]
801    fn test_mux() {
802        for (s, vals, y) in [
803            ('0', ["", ""], ""),
804            ('0', ["X10XX1100", "XXX101010"], "X10XX1100"),
805            ('1', ["X10XX1100", "XXX101010"], "XXX101010"),
806            ('X', ["X10XX1100", "XXX101010"], "XXXXX1XX0"),
807        ] {
808            assert_eq!(ConstBit::lit(s).mux(vals.map(Const::lit)), Const::lit(y));
809        }
810    }
811
812    #[test]
813    fn test_adc() {
814        for (a, b, c, y) in [
815            ("", "", '0', "0"),
816            ("", "", '1', "1"),
817            ("10101010", "11001100", '0', "101110110"),
818            ("1101", "1111", '1', "11101"),
819            ("1010X010", "11001100", '0', "XXXXXX110"),
820        ] {
821            assert_eq!(Const::lit(a).adc(Const::lit(b), ConstBit::lit(c)), Const::lit(y));
822        }
823    }
824
825    #[test]
826    fn test_mul() {
827        for (a, b, y) in [("", "", ""), ("0011", "0011", "1001"), ("0X11", "0011", "XXXX"), ("1101", "1101", "1001")] {
828            assert_eq!(Const::lit(a).mul(Const::lit(b)), Const::lit(y));
829        }
830    }
831}