Skip to main content

prjunnamed_netlist/
value.rs

1use std::{
2    borrow::{Borrow, BorrowMut, Cow},
3    fmt::{Debug, Display},
4    hash::Hash,
5    ops::{Index, IndexMut},
6    slice::SliceIndex,
7};
8
9use bytemuck::TransparentWrapper;
10
11use crate::{Const, ConstBit, ConstSlice, Design};
12
13/// A net is a driver in the design: a reference to a single position from
14/// the output of a [`Cell`].
15///
16/// Constant nets are represented as outputs of three singleton [`Cell::Const`] cells that are always present at fixed positions in the design.
17///
18/// [`Cell`]: crate::Cell
19#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub struct ValueBit {
21    pub(crate) index: u32,
22}
23
24impl ValueBit {
25    pub const UNDEF: ValueBit = ValueBit { index: 2 };
26    pub const ZERO: ValueBit = ValueBit { index: 0 };
27    pub const ONE: ValueBit = ValueBit { index: 1 };
28
29    pub fn as_const(self) -> Option<ConstBit> {
30        if self == Self::UNDEF {
31            Some(ConstBit::Undef)
32        } else if self == Self::ZERO {
33            Some(ConstBit::Zero)
34        } else if self == Self::ONE {
35            Some(ConstBit::One)
36        } else {
37            None
38        }
39    }
40
41    pub(crate) fn from_cell_index(cell_index: usize) -> ValueBit {
42        ValueBit { index: cell_index as u32 }
43    }
44
45    pub(crate) fn as_cell_index(self) -> usize {
46        self.index as usize
47    }
48
49    pub fn is_const(self) -> bool {
50        self.as_const().is_some()
51    }
52
53    pub fn visit(self, mut f: impl FnMut(ValueBit)) {
54        f(self)
55    }
56
57    pub fn visit_mut(&mut self, mut f: impl FnMut(&mut ValueBit)) {
58        f(self)
59    }
60
61    pub fn repeat(self, count: usize) -> Value {
62        Value::from_iter(std::iter::repeat_n(self, count))
63    }
64}
65
66impl From<bool> for ValueBit {
67    fn from(value: bool) -> Self {
68        match value {
69            false => ValueBit::ZERO,
70            true => ValueBit::ONE,
71        }
72    }
73}
74
75impl From<ConstBit> for ValueBit {
76    fn from(value: ConstBit) -> Self {
77        match value {
78            ConstBit::Undef => Self::UNDEF,
79            ConstBit::Zero => Self::ZERO,
80            ConstBit::One => Self::ONE,
81        }
82    }
83}
84
85impl From<&ValueBit> for ValueBit {
86    fn from(net: &ValueBit) -> Self {
87        *net
88    }
89}
90
91impl TryFrom<Value> for ValueBit {
92    type Error = ();
93
94    fn try_from(value: Value) -> Result<Self, Self::Error> {
95        value.as_net().ok_or(())
96    }
97}
98
99impl Debug for ValueBit {
100    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
101        match *self {
102            ValueBit::ZERO => write!(f, "Net::ZERO"),
103            ValueBit::ONE => write!(f, "Net::ONE"),
104            ValueBit::UNDEF => write!(f, "Net::UNDEF"),
105            _ => {
106                write!(f, "Net::from_cell({cell_index})", cell_index = self.index)
107            }
108        }
109    }
110}
111
112impl Display for ValueBit {
113    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
114        match *self {
115            ValueBit::ZERO => write!(f, "0"),
116            ValueBit::ONE => write!(f, "1"),
117            ValueBit::UNDEF => write!(f, "X"),
118            _ => {
119                write!(f, "%_{cell_index}", cell_index = self.index)
120            }
121        }
122    }
123}
124
125#[derive(Clone)]
126enum ValueRepr {
127    None,
128    Some(ValueBit),
129    Many(Vec<ValueBit>),
130}
131
132impl ValueRepr {
133    fn as_slice(&self) -> &[ValueBit] {
134        match self {
135            ValueRepr::None => &[],
136            ValueRepr::Some(net) => std::slice::from_ref(net),
137            ValueRepr::Many(nets) => nets.as_slice(),
138        }
139    }
140
141    fn as_slice_mut(&mut self) -> &mut [ValueBit] {
142        match self {
143            ValueRepr::None => &mut [],
144            ValueRepr::Some(net) => std::slice::from_mut(net),
145            ValueRepr::Many(nets) => nets.as_mut_slice(),
146        }
147    }
148
149    fn push(&mut self, new_net: ValueBit) {
150        match self {
151            ValueRepr::None => *self = ValueRepr::Some(new_net),
152            ValueRepr::Some(net) => *self = ValueRepr::Many(vec![*net, new_net]),
153            ValueRepr::Many(nets) => {
154                nets.push(new_net);
155            }
156        }
157    }
158}
159
160impl PartialEq for ValueRepr {
161    fn eq(&self, other: &Self) -> bool {
162        match (self, other) {
163            (ValueRepr::Some(lft), ValueRepr::Some(rgt)) => lft.eq(rgt),
164            _ => self.as_slice().eq(other.as_slice()),
165        }
166    }
167}
168
169impl Eq for ValueRepr {}
170
171impl PartialOrd for ValueRepr {
172    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
173        Some(self.cmp(other))
174    }
175}
176
177impl Ord for ValueRepr {
178    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
179        match (self, other) {
180            (ValueRepr::Some(lft), ValueRepr::Some(rgt)) => lft.cmp(rgt),
181            _ => self.as_slice().cmp(other.as_slice()),
182        }
183    }
184}
185
186impl Hash for ValueRepr {
187    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
188        self.as_slice().hash(state);
189    }
190}
191
192#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
193#[repr(transparent)]
194pub struct ValueSlice([ValueBit]);
195
196// SAFETY: `ValueSlice` is `repr(transparent)` and has only one field, which is of type `[ValueBit]`.
197// There is no additional alignment requirement.
198unsafe impl TransparentWrapper<[ValueBit]> for ValueSlice {}
199
200/// A value is a (possibly empty) sequence of [`ValueBit`]s.
201#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
202pub struct Value(ValueRepr);
203
204impl Value {
205    /// Creates an empty value.
206    pub fn new() -> Self {
207        Value(ValueRepr::None)
208    }
209
210    /// Creates an all-`0` value of given width.
211    pub fn zero(width: usize) -> Self {
212        ValueBit::ZERO.repeat(width)
213    }
214
215    /// Creates an all-`1` value of given width.
216    pub fn ones(width: usize) -> Self {
217        ValueBit::ONE.repeat(width)
218    }
219
220    /// Creates an all-`X` value of given width.
221    pub fn undef(width: usize) -> Self {
222        ValueBit::UNDEF.repeat(width)
223    }
224
225    /// Creates a reference to `count` outputs of cell at position `cell_index` in their natural order.
226    pub(crate) fn from_cell_range(cell_index: usize, count: usize) -> Value {
227        Value::from_iter((cell_index..(cell_index + count)).map(ValueBit::from_cell_index))
228    }
229
230    pub fn push(&mut self, new_net: impl Into<ValueBit>) {
231        self.0.push(new_net.into())
232    }
233
234    pub fn as_slice(&self) -> &ValueSlice {
235        &self[..]
236    }
237
238    pub fn as_slice_mut(&mut self) -> &mut ValueSlice {
239        &mut self[..]
240    }
241}
242
243impl ValueSlice {
244    pub fn len(&self) -> usize {
245        self.0.len()
246    }
247
248    pub fn is_empty(&self) -> bool {
249        self.0.is_empty()
250    }
251
252    pub fn iter(&self) -> impl DoubleEndedIterator<Item = ValueBit> + ExactSizeIterator + '_ {
253        self.0.iter().copied()
254    }
255
256    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut ValueBit> + ExactSizeIterator + '_ {
257        self.0.iter_mut()
258    }
259
260    pub fn is_undef(&self) -> bool {
261        self.iter().all(|net| net == ValueBit::UNDEF)
262    }
263
264    pub fn is_zero(&self) -> bool {
265        self.iter().all(|net| net == ValueBit::ZERO)
266    }
267
268    pub fn is_ones(&self) -> bool {
269        self.iter().all(|net| net == ValueBit::ONE)
270    }
271
272    pub fn lsb(&self) -> ValueBit {
273        self[0]
274    }
275
276    pub fn msb(&self) -> ValueBit {
277        self[self.len() - 1]
278    }
279
280    pub fn has_undef(&self) -> bool {
281        self.iter().any(|net| net == ValueBit::UNDEF)
282    }
283
284    pub fn as_const(&self) -> Option<Const> {
285        if self.iter().all(|net| net.is_const()) {
286            Some(Const::from_iter(self.iter().map(|net| net.as_const().unwrap())))
287        } else {
288            None
289        }
290    }
291
292    pub fn as_net(&self) -> Option<ValueBit> {
293        if self.len() == 1 { Some(self[0]) } else { None }
294    }
295
296    pub fn unwrap_net(&self) -> ValueBit {
297        self.as_net().unwrap()
298    }
299
300    pub fn concat(&self, other: impl AsRef<ValueSlice>) -> Value {
301        Value::from_iter(self.iter().chain(other.as_ref()))
302    }
303
304    pub fn repeat(&self, count: usize) -> Value {
305        Value::from_iter((0..count).flat_map(|_| self))
306    }
307
308    pub fn slice(&self, range: impl std::ops::RangeBounds<usize>) -> Value {
309        self[(range.start_bound().cloned(), range.end_bound().cloned())].to_owned()
310    }
311
312    pub fn zext(&self, width: usize) -> Value {
313        assert!(width >= self.len());
314        self.concat(Value::zero(width - self.len()))
315    }
316
317    pub fn sext(&self, width: usize) -> Value {
318        assert!(!self.is_empty());
319        assert!(width >= self.len());
320        Value::from_iter(self.iter().chain(std::iter::repeat_n(self.msb(), width - self.len())))
321    }
322
323    fn shift_count(value: &ConstSlice, stride: u32) -> usize {
324        let stride = stride as usize;
325        let mut result: usize = 0;
326        for (index, bit) in value.iter().enumerate() {
327            if bit == ConstBit::One {
328                if index >= usize::BITS as usize {
329                    return usize::MAX;
330                } else {
331                    result |= 1 << index;
332                }
333            }
334        }
335        result.saturating_mul(stride)
336    }
337
338    pub fn shl(&self, other: impl AsRef<ConstSlice>, stride: u32) -> Value {
339        let other = other.as_ref();
340        if other.has_undef() {
341            return Value::undef(self.len());
342        }
343        let shcnt = Self::shift_count(other, stride);
344        if shcnt >= self.len() {
345            return Value::zero(self.len());
346        }
347        Value::zero(shcnt).concat(&self[..self.len() - shcnt])
348    }
349
350    pub fn ushr(&self, other: impl AsRef<ConstSlice>, stride: u32) -> Value {
351        let other = other.as_ref();
352        if other.has_undef() {
353            return Value::undef(self.len());
354        }
355        let shcnt = Self::shift_count(other, stride);
356        if shcnt >= self.len() {
357            return Value::zero(self.len());
358        }
359        self[shcnt..].zext(self.len())
360    }
361
362    pub fn sshr(&self, other: impl AsRef<ConstSlice>, stride: u32) -> Value {
363        let other = other.as_ref();
364        if other.has_undef() {
365            return Value::undef(self.len());
366        }
367        let shcnt = Self::shift_count(other, stride);
368        if shcnt >= self.len() {
369            return Value::from(self.msb()).sext(self.len());
370        }
371        self[shcnt..].sext(self.len())
372    }
373
374    pub fn xshr(&self, other: impl AsRef<ConstSlice>, stride: u32) -> Value {
375        let other = other.as_ref();
376        if other.has_undef() {
377            return Value::undef(self.len());
378        }
379        let shcnt = Self::shift_count(other, stride);
380        if shcnt >= self.len() {
381            return Value::undef(self.len());
382        }
383        self[shcnt..].concat(Value::undef(shcnt))
384    }
385
386    pub fn visit(&self, mut f: impl FnMut(ValueBit)) {
387        for net in self.iter() {
388            f(net)
389        }
390    }
391
392    pub fn visit_mut(&mut self, mut f: impl FnMut(&mut ValueBit)) {
393        for net in self.iter_mut() {
394            f(net)
395        }
396    }
397
398    pub fn copy_from_slice(&mut self, other: impl AsRef<ValueSlice>) {
399        self.0.copy_from_slice(&other.as_ref().0);
400    }
401}
402
403impl AsRef<ValueSlice> for ValueSlice {
404    fn as_ref(&self) -> &ValueSlice {
405        self
406    }
407}
408
409impl AsMut<ValueSlice> for ValueSlice {
410    fn as_mut(&mut self) -> &mut ValueSlice {
411        self
412    }
413}
414
415impl AsRef<ValueSlice> for Value {
416    fn as_ref(&self) -> &ValueSlice {
417        ValueSlice::wrap_ref(self.0.as_slice())
418    }
419}
420
421impl AsMut<ValueSlice> for Value {
422    fn as_mut(&mut self) -> &mut ValueSlice {
423        ValueSlice::wrap_mut(self.0.as_slice_mut())
424    }
425}
426
427impl AsRef<ValueSlice> for ValueBit {
428    fn as_ref(&self) -> &ValueSlice {
429        ValueSlice::wrap_ref(std::slice::from_ref(self))
430    }
431}
432
433impl AsMut<ValueSlice> for ValueBit {
434    fn as_mut(&mut self) -> &mut ValueSlice {
435        ValueSlice::wrap_mut(std::slice::from_mut(self))
436    }
437}
438
439impl Borrow<ValueSlice> for Value {
440    fn borrow(&self) -> &ValueSlice {
441        self
442    }
443}
444
445impl BorrowMut<ValueSlice> for Value {
446    fn borrow_mut(&mut self) -> &mut ValueSlice {
447        self
448    }
449}
450
451impl std::borrow::ToOwned for ValueSlice {
452    type Owned = Value;
453
454    fn to_owned(&self) -> Self::Owned {
455        Value::from_iter(self)
456    }
457}
458
459impl std::ops::Deref for Value {
460    type Target = ValueSlice;
461
462    fn deref(&self) -> &Self::Target {
463        self.as_ref()
464    }
465}
466
467impl std::ops::DerefMut for Value {
468    fn deref_mut(&mut self) -> &mut Self::Target {
469        self.as_mut()
470    }
471}
472
473impl<Idx, Wrap: ?Sized> Index<Idx> for ValueSlice
474where
475    Idx: SliceIndex<[ValueBit], Output = Wrap>,
476    Wrap: ValueIndexWrapper + 'static,
477{
478    type Output = Wrap::Output;
479
480    fn index(&self, index: Idx) -> &Self::Output {
481        self.0[index].wrap()
482    }
483}
484
485impl<Idx, Wrap: ?Sized> IndexMut<Idx> for ValueSlice
486where
487    Idx: SliceIndex<[ValueBit], Output = Wrap>,
488    Wrap: ValueIndexWrapper + 'static,
489{
490    fn index_mut(&mut self, index: Idx) -> &mut Self::Output {
491        self.0[index].wrap_mut()
492    }
493}
494
495pub trait ValueIndexWrapper {
496    type Output: ?Sized;
497
498    fn wrap(&self) -> &Self::Output;
499    fn wrap_mut(&mut self) -> &mut Self::Output;
500}
501
502impl ValueIndexWrapper for ValueBit {
503    type Output = ValueBit;
504
505    fn wrap(&self) -> &Self::Output {
506        self
507    }
508
509    fn wrap_mut(&mut self) -> &mut Self::Output {
510        self
511    }
512}
513
514impl ValueIndexWrapper for [ValueBit] {
515    type Output = ValueSlice;
516
517    fn wrap(&self) -> &Self::Output {
518        ValueSlice::wrap_ref(self)
519    }
520
521    fn wrap_mut(&mut self) -> &mut Self::Output {
522        ValueSlice::wrap_mut(self)
523    }
524}
525
526impl Default for Value {
527    fn default() -> Self {
528        Value::new()
529    }
530}
531
532impl Debug for Value {
533    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
534        write!(f, "Value::from_iter([")?;
535        for (index, net) in self.iter().enumerate() {
536            if index != 0 {
537                write!(f, ", ")?;
538            }
539            write!(f, "{net:?}")?;
540        }
541        write!(f, "])")?;
542        Ok(())
543    }
544}
545
546impl Display for Value {
547    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548        if self.is_empty() {
549            write!(f, "[]")
550        } else if self.len() == 1 {
551            write!(f, "{}", self[0])
552        } else {
553            write!(f, "[")?;
554            for net in self.iter().rev() {
555                write!(f, " {net}")?;
556            }
557            write!(f, " ]")
558        }
559    }
560}
561
562impl Extend<ValueBit> for Value {
563    fn extend<T: IntoIterator<Item = ValueBit>>(&mut self, iter: T) {
564        for net in iter {
565            self.push(net);
566        }
567    }
568}
569
570impl From<&ValueSlice> for Value {
571    fn from(value: &ValueSlice) -> Self {
572        value.to_owned()
573    }
574}
575
576impl From<&Value> for Value {
577    fn from(value: &Value) -> Self {
578        value.clone()
579    }
580}
581
582impl From<ValueBit> for Value {
583    fn from(net: ValueBit) -> Self {
584        Value(ValueRepr::Some(net))
585    }
586}
587
588impl From<&ValueBit> for Value {
589    fn from(net: &ValueBit) -> Self {
590        Value::from(*net)
591    }
592}
593
594impl From<ConstBit> for Value {
595    fn from(bit: ConstBit) -> Self {
596        Value(ValueRepr::Some(bit.into()))
597    }
598}
599
600impl From<&[ValueBit]> for Value {
601    fn from(nets: &[ValueBit]) -> Self {
602        Value::from_iter(nets.iter().cloned())
603    }
604}
605
606impl From<Vec<ValueBit>> for Value {
607    fn from(nets: Vec<ValueBit>) -> Self {
608        Value::from(&nets[..])
609    }
610}
611
612impl From<&ConstSlice> for Value {
613    fn from(value: &ConstSlice) -> Self {
614        Value::from_iter(value.iter().map(ValueBit::from))
615    }
616}
617
618impl From<&Const> for Value {
619    fn from(value: &Const) -> Self {
620        Value::from(value.as_slice())
621    }
622}
623
624impl From<Const> for Value {
625    fn from(value: Const) -> Self {
626        Value::from(value.as_slice())
627    }
628}
629
630impl From<Value> for Cow<'_, Value> {
631    fn from(value: Value) -> Self {
632        Cow::Owned(value)
633    }
634}
635
636impl From<ValueBit> for Cow<'_, Value> {
637    fn from(value: ValueBit) -> Self {
638        Cow::Owned(Value::from(value))
639    }
640}
641
642impl From<ConstBit> for Cow<'_, Value> {
643    fn from(value: ConstBit) -> Self {
644        Cow::Owned(Value::from(ValueBit::from(value)))
645    }
646}
647
648impl From<&Const> for Cow<'_, Value> {
649    fn from(value: &Const) -> Self {
650        Cow::Owned(Value::from(value))
651    }
652}
653
654impl From<Const> for Cow<'_, Value> {
655    fn from(value: Const) -> Self {
656        Cow::Owned(Value::from(value))
657    }
658}
659
660impl<'a> From<&'a Value> for Cow<'a, Value> {
661    fn from(value: &'a Value) -> Self {
662        Cow::Borrowed(value)
663    }
664}
665
666impl FromIterator<ValueBit> for Value {
667    fn from_iter<T: IntoIterator<Item = ValueBit>>(iter: T) -> Self {
668        let mut iter = iter.into_iter();
669        match iter.size_hint() {
670            (_, Some(0 | 1)) => {
671                let mut value = match iter.next() {
672                    None => Value::new(),
673                    Some(net) => Value::from(net),
674                };
675                for net in iter {
676                    value.push(net);
677                }
678                value
679            }
680            _ => Value(ValueRepr::Many(iter.collect())),
681        }
682    }
683}
684
685impl<'a> IntoIterator for &'a ValueSlice {
686    type Item = ValueBit;
687
688    type IntoIter = std::iter::Copied<std::slice::Iter<'a, ValueBit>>;
689
690    fn into_iter(self) -> Self::IntoIter {
691        self.0.iter().copied()
692    }
693}
694
695impl<'a> IntoIterator for &'a Value {
696    type Item = ValueBit;
697
698    type IntoIter = std::iter::Copied<std::slice::Iter<'a, ValueBit>>;
699
700    fn into_iter(self) -> Self::IntoIter {
701        self.as_slice().into_iter()
702    }
703}
704
705pub struct ValueIntoIter {
706    repr: ValueRepr,
707    index: usize,
708}
709
710impl Iterator for ValueIntoIter {
711    type Item = ValueBit;
712
713    fn next(&mut self) -> Option<Self::Item> {
714        let item = self.repr.as_slice().get(self.index).cloned();
715        if item.is_some() {
716            self.index += 1;
717        }
718        item
719    }
720}
721
722impl IntoIterator for Value {
723    type Item = ValueBit;
724    type IntoIter = ValueIntoIter;
725
726    fn into_iter(self) -> Self::IntoIter {
727        ValueIntoIter { repr: self.0, index: 0 }
728    }
729}
730
731/// A control net is a [`Net`] that can be negated.
732#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
733pub enum ControlNet {
734    Pos(ValueBit),
735    Neg(ValueBit),
736}
737
738impl ControlNet {
739    pub const UNDEF: ControlNet = ControlNet::Pos(ValueBit::UNDEF);
740    pub const ZERO: ControlNet = ControlNet::Pos(ValueBit::ZERO);
741    pub const ONE: ControlNet = ControlNet::Pos(ValueBit::ONE);
742
743    pub fn from_net_invert(net: ValueBit, invert: bool) -> Self {
744        match invert {
745            false => ControlNet::Pos(net),
746            true => ControlNet::Neg(net),
747        }
748    }
749
750    pub fn net(self) -> ValueBit {
751        match self {
752            Self::Pos(net) => net,
753            Self::Neg(net) => net,
754        }
755    }
756
757    pub fn is_positive(self) -> bool {
758        matches!(self, Self::Pos(_))
759    }
760
761    pub fn is_negative(self) -> bool {
762        matches!(self, Self::Neg(_))
763    }
764
765    pub fn is_active(self) -> Option<bool> {
766        match self {
767            Self::Pos(net) if net == ValueBit::ZERO => Some(false),
768            Self::Neg(net) if net == ValueBit::ONE => Some(false),
769            Self::Pos(net) if net == ValueBit::ONE => Some(true),
770            Self::Neg(net) if net == ValueBit::ZERO => Some(true),
771            _ => None,
772        }
773    }
774
775    pub fn is_always(self, active: bool) -> bool {
776        self.is_active() == Some(active)
777    }
778
779    pub fn is_const(self) -> bool {
780        self.net().as_const().is_some()
781    }
782
783    pub fn canonicalize(self) -> Self {
784        match self {
785            Self::Neg(net) if net == ValueBit::UNDEF => Self::Pos(net),
786            Self::Neg(net) if net == ValueBit::ZERO => Self::Pos(ValueBit::ONE),
787            Self::Neg(net) if net == ValueBit::ONE => Self::Pos(ValueBit::ZERO),
788            _ => self,
789        }
790    }
791
792    pub fn into_pos(self, design: &Design) -> ValueBit {
793        match self {
794            ControlNet::Pos(net) => net,
795            ControlNet::Neg(net) => {
796                if let Some(bit) = net.as_const() {
797                    ValueBit::from(!bit)
798                } else {
799                    design.add_not(net).unwrap_net()
800                }
801            }
802        }
803    }
804
805    pub fn into_neg(self, design: &Design) -> ValueBit {
806        match self {
807            ControlNet::Pos(net) => {
808                if let Some(bit) = net.as_const() {
809                    ValueBit::from(!bit)
810                } else {
811                    design.add_not(net).unwrap_net()
812                }
813            }
814            ControlNet::Neg(net) => net,
815        }
816    }
817
818    pub fn visit(self, f: impl FnMut(ValueBit)) {
819        match self {
820            ControlNet::Pos(net) => net.visit(f),
821            ControlNet::Neg(net) => net.visit(f),
822        }
823    }
824
825    pub fn visit_mut(&mut self, f: impl FnMut(&mut ValueBit)) {
826        match self {
827            ControlNet::Pos(net) => net.visit_mut(f),
828            ControlNet::Neg(net) => net.visit_mut(f),
829        }
830    }
831}
832
833impl std::ops::Not for ControlNet {
834    type Output = ControlNet;
835
836    fn not(self) -> Self::Output {
837        match self {
838            ControlNet::Pos(net) => ControlNet::Neg(net),
839            ControlNet::Neg(net) => ControlNet::Pos(net),
840        }
841        .canonicalize()
842    }
843}
844
845impl From<ValueBit> for ControlNet {
846    fn from(net: ValueBit) -> Self {
847        ControlNet::Pos(net)
848    }
849}
850
851impl Display for ControlNet {
852    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
853        match self {
854            ControlNet::Pos(net) => write!(f, "{net}"),
855            ControlNet::Neg(net) => write!(f, "!{net}"),
856        }
857    }
858}
859
860#[cfg(test)]
861mod test {
862    use crate::{ValueBit, ConstBit, Value};
863
864    #[test]
865    fn test_net() {
866        assert_eq!(ValueBit::from(ConstBit::Zero), ValueBit::ZERO);
867        assert_eq!(ValueBit::from(ConstBit::One), ValueBit::ONE);
868        assert_eq!(ValueBit::from(ConstBit::Undef), ValueBit::UNDEF);
869        assert_eq!(ValueBit::from_cell_index(3), ValueBit { index: 3 });
870    }
871
872    #[test]
873    fn test_from_bool() {
874        assert_eq!(ValueBit::from(false), ValueBit::ZERO);
875        assert_eq!(ValueBit::from(true), ValueBit::ONE);
876    }
877
878    #[test]
879    fn test_from_trit() {
880        assert_eq!(ValueBit::from(ConstBit::Zero), ValueBit::ZERO);
881        assert_eq!(ValueBit::from(ConstBit::One), ValueBit::ONE);
882        assert_eq!(ValueBit::from(ConstBit::Undef), ValueBit::UNDEF);
883    }
884
885    #[test]
886    fn test_net_debug() {
887        assert_eq!(format!("{:?}", ValueBit::ZERO), "Net::ZERO");
888        assert_eq!(format!("{:?}", ValueBit::ONE), "Net::ONE");
889        assert_eq!(format!("{:?}", ValueBit::UNDEF), "Net::UNDEF");
890        assert_eq!(format!("{:?}", ValueBit::from_cell_index(3)), "Net::from_cell(3)");
891    }
892
893    #[test]
894    fn test_value() {
895        let v01 = Value::from_iter([ValueBit::ONE, ValueBit::ZERO]);
896        assert_eq!(v01.into_iter().collect::<Vec<_>>(), vec![ValueBit::ONE, ValueBit::ZERO]);
897    }
898}