liberty-db 0.1.4

`liberty` data structre
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
use crate::types;
use crate::types::*;
use crate::units;
use super::Port;
use strum_macros::Display;
use std::fmt::Display;
use std::ops::{Deref,DerefMut};
pub trait LogicLike: std::fmt::Display + std::fmt::Debug{
    fn inverse(&self) -> Self;
    fn variant_eq(&self, other: &Self) -> bool;
}

/// ``` text
/// High:          _______
///               /|
///              / |
///             /  |
/// Low: ______/   |
///     |<-  ->|<->|
///      settle transition
/// ```
#[derive(Default)]
#[derive(Debug, Clone, Copy)]
// #[derive(PartialEq, Eq)]
pub struct ChangePattern{
    pub settle_down_time: units::Time,
    pub transition_time: units::Time,
}

impl std::hash::Hash for ChangePattern {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        float_hash(state, self.settle_down_time.value);
        float_hash(state, self.transition_time.value);
    }
}
impl PartialEq for ChangePattern {
    fn eq(&self, other: &Self) -> bool {
        float_eq(self.settle_down_time.value,other.settle_down_time.value) && 
        float_eq(self.transition_time.value,other.transition_time.value)
    }
}
impl Eq for ChangePattern {
}
impl std::fmt::Display for ChangePattern {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use units::Unit;
        write!(f, "({:.10E}{}|{:.10E}{})", 
                self.settle_down_time.get::<units::time::nanosecond>(),units::time::nanosecond::abbreviation(),
                self.transition_time.get::<units::time::nanosecond>(),units::time::nanosecond::abbreviation())
    }
}

impl ChangePattern {
    #[inline]
    /// new ChangePattern
    pub fn new(
        settle_down_time: units::Time,
        transition_time: units::Time,
    )->Self{
        Self{
            settle_down_time,
            transition_time,
        }
    }
    #[inline]
    pub fn combine(a: &Option<Self>, b: &Option<Self>) -> Option<Self>{
        match (a,b) {
            (None, None) => None,
            (None, Some(b)) => Some(*b),
            (Some(a), None) => Some(*a),
            // FIXME: 
            (Some(a), Some(b)) => Some(*a),
        }
    }
}

#[derive(Debug, Clone, Copy)]
#[derive(Hash, PartialEq, Eq)]
#[derive(
    strum_macros::Display, 
    strum_macros::EnumString,
    strum_macros::EnumIter,
)]
pub enum StaticState {
    /// High
    #[strum(serialize = "h", serialize = "H", serialize = "1")]
    High,
    /// Low
    #[strum(serialize = "l", serialize = "L", serialize = "0")]
    Low,
}

impl LogicLike for StaticState {
    #[inline]
    fn inverse(&self) -> Self{
        match self{
            Self::Low  => Self::High,
            Self::High => Self::Low,
        }
    }
    #[inline]
    fn variant_eq(&self, other: &Self) -> bool{
        match (self,other) {
            (StaticState::High, StaticState::High) => true,
            (StaticState::Low, StaticState::Low) => true,
            _ => false,
        }
    }
}

#[derive(Debug, Clone, Copy)]
#[derive(Hash, PartialEq, Eq)]
#[derive(
    // strum_macros::Display, 
    strum_macros::EnumString,
    strum_macros::EnumIter,
)]
pub enum DynamicState {
    /// Fall
    #[strum(serialize = "f", serialize = "F")]
    Fall(Option<ChangePattern>),
    /// Rise
    #[strum(serialize = "r", serialize = "R")]
    Rise(Option<ChangePattern>),
}
impl Display for DynamicState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DynamicState::Fall(c) => match c {
                Some(c) => write!(f,"F{}",c),
                None => write!(f,"F"),
            },
            DynamicState::Rise(c) => match c {
                Some(c) =>  write!(f,"R{}",c),
                None => write!(f,"R"),
            },
        }
    }
}
impl LogicLike for DynamicState {
    #[inline]
    fn inverse(&self) -> Self{
        match self{
            Self::Fall(c)  => Self::Rise(*c),
            Self::Rise(c)  => Self::Fall(*c),
        }
    }
    #[inline]
    fn variant_eq(&self, other: &Self) -> bool{
        match (self,other) {
            (DynamicState::Fall(_), DynamicState::Fall(_)) => true,
            (DynamicState::Rise(_), DynamicState::Rise(_)) => true,
            _ => false,
        }
    }
}
/// LogicState
#[derive(Default)]
#[derive(Debug, Clone, Copy, PartialEq)]
#[derive(Display)]
pub enum IllegalType {
    #[default]
    None,
    HighImpedanceInput,
    NoIdea,
    RiseFallAtStatic,
}
impl IllegalType {
    #[inline]
    pub fn combine(a: &Option<Self>, b: &Option<Self>)->Self{
        match (a,b) {
            (None, None) => Self::None,
            (None, Some(b_t)) => *b_t,
            (Some(a_t), None) => *a_t,
            (Some(a_t), Some(b_t)) => {
                match (a_t,b_t) {
                    (Self::None, Self::None) => Self::None,
                    (Self::None, b_vaild) => *b_vaild,
                    (a_vaild, Self::None) => *a_vaild,
                    // FIXME:
                    (a_vaild, b_vaild) => *a_vaild,
                }
            },
        }
    }
}
#[derive(Debug, Clone, Copy)]
#[derive(
    strum_macros::Display, 
    strum_macros::EnumString,
    strum_macros::EnumIter,
)]
#[derive(derivative::Derivative)]
#[derivative(PartialEq, Hash, Eq)]
pub enum UninitState {
    /// Unknown
    #[strum(serialize = "x", serialize = "X")]
    Unknown(
        #[derivative(Hash="ignore")]
        #[derivative(PartialEq="ignore")]
        IllegalType,
    ),
    /// HighImpedance
    #[strum(serialize = "z", serialize = "Z")]
    HighImpedance,
}
impl Default for UninitState {
    fn default() -> Self {
        Self::Unknown(IllegalType::default())
    }
}
impl LogicLike for UninitState {
    #[inline]
    fn inverse(&self) -> Self{
        *self
    }
    #[inline]
    fn variant_eq(&self, other: &Self) -> bool{
        match (self,other) {
            (UninitState::Unknown(_), UninitState::Unknown(_)) => true,
            (UninitState::HighImpedance, UninitState::HighImpedance) => true,
            _ => false,
        }
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Hash)]
pub enum CommonState {
    Dynamic(DynamicState),
    Static(StaticState),
}
impl CommonState {
    pub fn to_logice_state(&self) -> LogicState{
        match self {
            CommonState::Dynamic(s) => LogicState::Dynamic(*s),
            CommonState::Static(s) => LogicState::Static(*s),
        }
    }
}
/// LogicState
#[derive(Debug, Clone, Copy)]
#[derive(Hash, PartialEq, Eq)]
pub enum LogicState {
    Uninit(UninitState),
    Dynamic(DynamicState),
    Static(StaticState),
}
impl std::fmt::Display for LogicState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LogicState::Uninit(s) => s.fmt(f),
            LogicState::Dynamic(s) => s.fmt(f),
            LogicState::Static(s) => s.fmt(f),
        }
    }
}

impl Default for LogicState {
    fn default() -> Self {
        return Self::Uninit(UninitState::default());
    }
}

impl LogicLike for LogicState {
    #[inline]
    fn inverse(&self) -> Self{
        match self{
            Self::Uninit(s) => Self::Uninit(s.inverse()),
            Self::Dynamic(s) => Self::Dynamic(s.inverse()),
            Self::Static(s) => Self::Static(s.inverse()),
        }
    }
    #[inline]
    fn variant_eq(&self, other: &Self) -> bool{
        match (self,other) {
            (Self::Uninit(a), Self::Uninit(b)) => a.variant_eq(b),
            (Self::Dynamic(a), Self::Dynamic(b)) => a.variant_eq(b),
            (Self::Static(a), Self::Static(b)) => a.variant_eq(b),
            _ => false,
        }
    }
}
impl LogicState {
    const LIST: [Self;6] = [
        Self::Uninit(UninitState::Unknown(IllegalType::None)),
        Self::Uninit(UninitState::HighImpedance),
        Self::Dynamic(DynamicState::Fall(None)),
        Self::Dynamic(DynamicState::Rise(None)),
        Self::Static(StaticState::Low),
        Self::Static(StaticState::High),
    ];
    // pub fn iter() -> std::slice::Iter<'_, LogicState>{
    //     Self::LIST.iter()
    // }
    pub fn iter() -> impl Iterator<Item = Self> {
        Self::LIST.iter().copied()
    }
    #[inline]
    pub fn get_change_pattern(&self) -> Option<ChangePattern>{
        match self {
            LogicState::Dynamic(s) => match s {
                DynamicState::Fall(c) => *c,
                DynamicState::Rise(c) => *c,
            },
            _ => None,
        }
    }
    pub fn set_change_pattern(&self,c: &Option<ChangePattern>) -> Self{
        match self {
            LogicState::Dynamic(s) => match s {
                DynamicState::Fall(_) => Self::Dynamic(DynamicState::Fall(*c)),
                DynamicState::Rise(_) => Self::Dynamic(DynamicState::Rise(*c)),
            },
            _ => *self,
        }
    }
    pub fn get_illegal_type(&self) -> Option<IllegalType>{
        match self {
            Self::Uninit(uninit) => match uninit {
                UninitState::Unknown(t) => Some(*t),
                _ => None,
            },
            _ => None,
        }
    }
    pub fn set_illegal_type(&self,t: &Option<IllegalType>) -> Self{
        match (self,t) {
            (Self::Uninit(uninit), Some(t)) => match uninit {
                UninitState::Unknown(_) => Self::Uninit(UninitState::Unknown(*t)),
                _ => *self,
            },
            (Self::Uninit(uninit), None) => match uninit {
                UninitState::Unknown(_) => Self::Uninit(UninitState::Unknown(IllegalType::default())),
                _ => *self,
            },
            _ => *self,
        }
    }
    /// get_bgn state
    /// 
    /// R -> 0, F -> 1, otherwise not change
    pub fn get_bgn(&self) -> Self{
        match self{
            LogicState::Dynamic(s) => match s {
                DynamicState::Fall(_) => Self::Static(StaticState::High),
                DynamicState::Rise(_) => Self::Static(StaticState::Low),
            },
            _ => *self,
        }
    }
    /// get_end state
    /// 
    /// R -> 1, F -> 1, otherwise not change
    pub fn get_end(&self) -> Self{
        match self{
            LogicState::Dynamic(s) => match s {
                DynamicState::Fall(_) => Self::Static(StaticState::Low),
                DynamicState::Rise(_) => Self::Static(StaticState::High),
            },
            _ => *self,
        }
    }
    
    /// | BGN(self) | END  | Combined|
    /// | :-------: | :--: | :-----: |
    /// | 1         | 0    | F       |
    /// | 1         | 1    | 1       |
    /// | 1         | X    | X       |
    /// | X         | 1    | 1       |
    /// | 1         | Z    | Z       |
    /// | Z         | 1    | 1       |
    /// | Any       | F/R  | Illegal |
    /// | F/R       | Any  | Illegal |
    pub fn combine_bgn_end(bgn: &Self, end: &Self) -> Self{
        match (bgn,end) {
            (_, Self::Dynamic(_)) => Self::Uninit(UninitState::Unknown(IllegalType::RiseFallAtStatic)),
            (Self::Dynamic(_), _) => Self::Uninit(UninitState::Unknown(IllegalType::RiseFallAtStatic)),
            (Self::Uninit(_), Self::Uninit(_)) => *end,
            (Self::Uninit(_), Self::Static(_)) => *end,
            (Self::Static(_), Self::Uninit(_)) => *end,
            (Self::Static(bgn), Self::Static(end)) => match (bgn,end) {
                (StaticState::High, StaticState::High) => Self::Static(StaticState::High),
                (StaticState::High, StaticState::Low) => Self::Dynamic(DynamicState::Fall(None)),
                (StaticState::Low, StaticState::High) => Self::Dynamic(DynamicState::Rise(None)),
                (StaticState::Low, StaticState::Low) => Self::Static(StaticState::Low),
            },
        }
    }
}

/// LogicVector
#[derive(Default)]
#[derive(Debug, Clone)]
#[derive(Hash, PartialEq, Eq)]
pub struct LogicVector {
    value: Vec<LogicState>,
}

impl DerefMut for LogicVector {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}
impl Deref for LogicVector {
    type Target = Vec<LogicState>;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl LogicVector {
    #[inline]
    pub fn new(value: Vec<LogicState>) -> Self{
        Self { value }
    }
}
// impl PartialEq for LogicVector {
//     #[inline]
//     fn eq(&self, other: &Self) -> bool {
//         self.to_string() == other.to_string()
//     }
// }
// impl std::cmp::Eq for LogicVector {
// }
// impl std::hash::Hash for LogicVector {
//     #[inline]
//     fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
//         for 
//     }
// }

impl std::fmt::Display for LogicVector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.iter().fold(
            Ok(()),
            |result, state| {
                match state.get_change_pattern() {
                    Some(c) => result.and_then(|_| write!(f, "{}{}", state,c)),
                    None => result.and_then(|_| write!(f, "{}", state)),
                }
            }
        )
    }
}

impl LogicLike for LogicVector {
    #[inline]
    fn inverse(&self)->Self{
        let mut inversed = Self::new(Vec::with_capacity(self.len()));
        for (idx,v_state) in self.iter().enumerate() {

            inversed[idx]=v_state.inverse();
        }
        inversed
    }

    fn variant_eq(&self, other: &Self) -> bool {
        if self.len()!=other.len(){
            return false;
        }
        for (idx, a) in self.iter().enumerate(){
            if !a.variant_eq(&other[idx]){
                return false;
            }
        }
        return true;
    }
}

/// LogicOperation
#[derive(Debug, Clone, Copy, PartialEq)]
#[derive(strum_macros::Display, strum_macros::EnumString)]
pub enum LogicOperation {
    /// And
    #[strum(serialize = "*",serialize = "&")]
    And,
    /// Or
    #[strum(serialize = "+",serialize = "|")]
    Or,
    /// Xor
    #[strum(serialize = "^")]
    Xor,
}

impl LogicOperation {
    /// compute two logic state with logic operation
    /// 
    /// e.g. `High` `or` `Low` = `High`
    pub fn compute(&self,
        a: &LogicState,
        b: &LogicState,
    ) -> LogicState{
        let compute_dynamic_logic = || -> LogicState {
            let bgn_state = self.compute(&a.get_bgn(), &b.get_bgn());
            let end_state = self.compute(&a.get_end(), &b.get_end());
            let a_pattern = a.get_change_pattern();
            let b_pattern = b.get_change_pattern();
            LogicState::combine_bgn_end(&bgn_state, &end_state)
                        .set_change_pattern(&ChangePattern::combine(&a_pattern, &b_pattern))
        };
        let combine_illegal = || -> LogicState {
            let a_illegal = a.get_illegal_type();
            let b_illegal = b.get_illegal_type();
            LogicState::Uninit(UninitState::Unknown(IllegalType::combine(&a_illegal, &b_illegal)))
        };
        match (self,a,b) {
            (_, _, LogicState::Dynamic(_)) => compute_dynamic_logic(),
            (_, LogicState::Dynamic(_), _) => compute_dynamic_logic(),
            (_, LogicState::Uninit(_a), LogicState::Uninit(_b)) => combine_illegal(),
            (LogicOperation::And, LogicState::Uninit(_a), LogicState::Static(_b)) => match (_a,_b) {
                (UninitState::Unknown(_), StaticState::High) => *a,
                (UninitState::Unknown(_), StaticState::Low) => LogicState::Static(StaticState::Low),
                (UninitState::HighImpedance, StaticState::High) => LogicState::Uninit(UninitState::Unknown(IllegalType::HighImpedanceInput)),
                (UninitState::HighImpedance, StaticState::Low) => LogicState::Static(StaticState::Low),
            }
            (LogicOperation::And, LogicState::Static(_a), LogicState::Uninit(_b)) => match (_a,_b) {
                (StaticState::High, UninitState::Unknown(_)) => *b,
                (StaticState::High, UninitState::HighImpedance) => LogicState::Uninit(UninitState::Unknown(IllegalType::HighImpedanceInput)),
                (StaticState::Low, UninitState::Unknown(_)) => LogicState::Static(StaticState::Low),
                (StaticState::Low, UninitState::HighImpedance) => LogicState::Static(StaticState::Low),
            },
            (LogicOperation::And, LogicState::Static(_a), LogicState::Static(_b)) => match (_a,_b) {
                (StaticState::High, StaticState::High) => LogicState::Static(StaticState::High),
                (StaticState::High, StaticState::Low) => LogicState::Static(StaticState::Low),
                (StaticState::Low, StaticState::High) => LogicState::Static(StaticState::Low),
                (StaticState::Low, StaticState::Low) => LogicState::Static(StaticState::Low),
            },
            (LogicOperation::Or, LogicState::Uninit(_a), LogicState::Static(_b)) => match (_a,_b) {
                (UninitState::Unknown(_), StaticState::High) => LogicState::Static(StaticState::High),
                (UninitState::Unknown(_), StaticState::Low) => *a,
                (UninitState::HighImpedance, StaticState::High) => LogicState::Static(StaticState::High),
                (UninitState::HighImpedance, StaticState::Low) => LogicState::Uninit(UninitState::Unknown(IllegalType::HighImpedanceInput)),
            },
            (LogicOperation::Or, LogicState::Static(_a), LogicState::Uninit(_b)) => match (_a,_b) {
                (StaticState::High, UninitState::Unknown(_)) => LogicState::Static(StaticState::High),
                (StaticState::High, UninitState::HighImpedance) => LogicState::Static(StaticState::High),
                (StaticState::Low, UninitState::Unknown(_)) => *b,
                (StaticState::Low, UninitState::HighImpedance) => LogicState::Uninit(UninitState::Unknown(IllegalType::HighImpedanceInput)),
            },
            (LogicOperation::Or, LogicState::Static(_a), LogicState::Static(_b)) => match (_a,_b) {
                (StaticState::High, StaticState::High) => LogicState::Static(StaticState::High),
                (StaticState::High, StaticState::Low) => LogicState::Static(StaticState::High),
                (StaticState::Low, StaticState::High) => LogicState::Static(StaticState::High),
                (StaticState::Low, StaticState::Low) => LogicState::Static(StaticState::Low),
            },
            (LogicOperation::Xor, LogicState::Uninit(_a), LogicState::Static(_b)) => match (_a,_b) {
                (UninitState::Unknown(_), StaticState::High) => *a,
                (UninitState::Unknown(_), StaticState::Low) => *a,
                (UninitState::HighImpedance, StaticState::High) => LogicState::Uninit(UninitState::Unknown(IllegalType::HighImpedanceInput)),
                (UninitState::HighImpedance, StaticState::Low) => LogicState::Uninit(UninitState::Unknown(IllegalType::HighImpedanceInput)),
            },
            (LogicOperation::Xor, LogicState::Static(_a), LogicState::Uninit(_b)) => match (_a,_b) {
                (StaticState::High, UninitState::Unknown(_)) => *b,
                (StaticState::High, UninitState::HighImpedance) => LogicState::Uninit(UninitState::Unknown(IllegalType::HighImpedanceInput)),
                (StaticState::Low, UninitState::Unknown(_)) => *b,
                (StaticState::Low, UninitState::HighImpedance) => LogicState::Uninit(UninitState::Unknown(IllegalType::HighImpedanceInput)),
            },
            (LogicOperation::Xor, LogicState::Static(_a), LogicState::Static(_b)) => match (_a,_b) {
                (StaticState::High, StaticState::High) => LogicState::Static(StaticState::Low),
                (StaticState::High, StaticState::Low) => LogicState::Static(StaticState::High),
                (StaticState::Low, StaticState::High) => LogicState::Static(StaticState::High),
                (StaticState::Low, StaticState::Low) => LogicState::Static(StaticState::Low),
            },
        }
    }

    pub fn compute_table(&self,
        a:  &LogicStateTable,
        b: &LogicStateTable,
    ) -> LogicStateTable {
        let mut combine = b.clone();
        let mut vec_b_len: usize = 0;
        for (vec_b,_) in b.table.iter(){
            vec_b_len=vec_b.len();
            break;
        }
        let mut vec_combine_len = vec_b_len;
        let vec_combine_to_b = |vec_combine: &LogicVector|->LogicVector{
            LogicVector::new(vec_combine[..vec_b_len].to_vec())
        };
        let mut idx_map_combine_to_a: HashMap<usize,usize> = HashMap::new();
        for (portid_a,idx_a) in a.portid_idx_map.iter(){
            match combine.portid_idx_map.get(portid_a) {
                Some(idx_combine) => {
                    let _=idx_map_combine_to_a.insert(*idx_combine, *idx_a);
                },
                None => {
                    let _ = combine.portid_idx_map.insert(portid_a.clone(), vec_combine_len);
                    vec_combine_len += 1;
                    let _=idx_map_combine_to_a.insert(vec_combine_len-1, *idx_a);
                    let mut new_table:HashMap<LogicVector,LogicState> = HashMap::default();
                    for state in LogicState::iter(){
                        for (vec,_) in combine.table.iter(){
                            let mut new_key = vec.clone();
                            new_key.push(state);
                            let _ = new_table.insert(new_key, LogicState::default());
                        }
                    }
                    combine.table=new_table;
                },
            }
        }
        let mut count_vec: Vec<_> = idx_map_combine_to_a
                                            .iter()
                                            .collect();
        count_vec.sort_by(|a, b| a.1.cmp(&b.1));
        let vec_combine_to_a = |vec_combine: &LogicVector|->LogicVector{
            let mut vec = LogicVector::new(
                vec![LogicState::default();count_vec.len()]);
            for (&idx_combine,&idx_a)  in count_vec.iter() {
                vec[idx_a] = vec_combine[idx_combine];
            }
            vec
        };
        let mut new_combine = LogicStateTable{ 
            table: HashMap::default(), 
            portid_idx_map: combine.portid_idx_map,
        };
        for (vec_in,_) in combine.table.iter() {
            let state_a  = a.table.get(&vec_combine_to_a(vec_in));
            let state_b = b.table.get(&vec_combine_to_b(vec_in));
            match (state_a,state_b) {
                (Some(a), Some(b)) => {
                    let _ = new_combine.table.insert(vec_in.clone(), self.compute(a, b));
                },
                _ => {
                    error!("Can Not Find Here");
                    panic!();
                    let _ = new_combine.table.insert(vec_in.clone(), LogicState::default());
                },
            }
        }
        new_combine
    }
}


#[derive(Clone,Debug)]
#[derive(PartialEq)]
pub struct LogicStateTable{
    pub table: HashMap<LogicVector, LogicState>,
    pub portid_idx_map: HashMap<Port, usize>,
}

impl LogicStateTable {
    #[inline]
    pub fn new(
        table: HashMap<LogicVector, LogicState>,
        portid_idx_map: HashMap<Port, usize>,
    ) -> Self{
        Self {
            table,
            portid_idx_map,
        }
    }
    pub fn search(
        &self, 
        want_port_state_pair: Vec<(Port,LogicState)>, 
        want_out_state_if_not_none: Option<LogicState>,
    ) -> Self{
        let mut sub = Self{
            table:HashMap::new(),
            portid_idx_map:self.portid_idx_map.clone(),
        };
        let mut idx_state_pair = Vec::new();
        for (port_idx,state_want) in want_port_state_pair.iter(){
            match self.portid_idx_map.get(port_idx) {
                Some(idx) => idx_state_pair.push((*idx, state_want)),
                None => {
                    error!("Can Not Find {}, auto skip it.",port_idx);
                },
            }
        }
        'outer: for (k_vec,v_state) in self.table.iter() {
            match want_out_state_if_not_none {
                Some(want_out_state) => if !want_out_state.variant_eq(v_state){
                    continue 'outer;
                },
                _ => (),
            }
            for (port_idx,state_want) in idx_state_pair.iter(){
                let state_got = k_vec[*port_idx];
                if !state_want.variant_eq(&state_got) {
                    continue 'outer;
                }
            }
            let _=sub.table.insert(k_vec.clone(), *v_state);
        }
        sub
    }
}
impl std::fmt::Display for LogicStateTable {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f,"{self:?}")
    }
}
impl LogicLike for LogicStateTable {
    #[inline]
    fn inverse(&self)->Self{
        let mut inversed = Self{
            table:HashMap::new(),
            portid_idx_map:self.portid_idx_map.clone(),
        };
        for (k_vec,v_state) in self.table.iter() {
            let _=inversed.table.insert(k_vec.clone(), v_state.inverse());
        }
        inversed
    }

    fn variant_eq(&self, other: &Self) -> bool {
        todo!()
    }
}