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
use crate::biodivine_std::traits::State;
use std::collections::HashMap;
use std::fmt::{Display, Error, Formatter};
use std::hash::Hash;
pub fn build_index_map<T, F, R>(keys: &[T], transform_index: F) -> HashMap<T, R>
where
F: Fn(&T, usize) -> R,
T: Clone + Hash + PartialEq + Eq,
{
let mut result = HashMap::new();
for (i, item) in keys.iter().enumerate() {
result.insert(item.clone(), transform_index(item, i));
}
result
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct IdState(usize);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct IdStateRange {
next: usize,
remaining: usize,
}
impl State for IdState {}
impl From<usize> for IdState {
fn from(val: usize) -> Self {
IdState(val)
}
}
impl From<IdState> for usize {
fn from(state: IdState) -> Self {
state.0
}
}
impl Display for IdState {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "State({})", self.0)
}
}
impl IdState {
pub fn get_bit(self, bit: usize) -> bool {
(self.0 >> bit) & 1 == 1
}
pub fn flip_bit(self, bit: usize) -> IdState {
IdState(self.0 ^ (1 << bit))
}
}
impl IdStateRange {
pub fn new(state_count: usize) -> IdStateRange {
IdStateRange {
next: 0,
remaining: state_count,
}
}
}
impl Iterator for IdStateRange {
type Item = IdState;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining == 0 {
None
} else {
let result = self.next;
self.remaining -= 1;
self.next += 1;
Some(IdState::from(result))
}
}
}
#[cfg(test)]
mod tests {
use crate::biodivine_std::structs::{IdState, IdStateRange};
#[test]
fn id_state_test() {
let state = IdState::from(0b10110);
assert!(!state.get_bit(0));
assert!(state.get_bit(1));
assert!(state.get_bit(2));
assert!(!state.get_bit(3));
assert!(state.get_bit(4));
let flipped = state.flip_bit(3);
assert_eq!(0b11110 as usize, flipped.into());
}
#[test]
fn test_state_range_iterator() {
let mut iter = IdStateRange::new(6);
assert_eq!(Some(IdState::from(0)), iter.next());
assert_eq!(Some(IdState::from(1)), iter.next());
assert_eq!(Some(IdState::from(2)), iter.next());
assert_eq!(Some(IdState::from(3)), iter.next());
assert_eq!(Some(IdState::from(4)), iter.next());
assert_eq!(Some(IdState::from(5)), iter.next());
assert_eq!(None, iter.next());
assert_eq!(None, iter.next());
}
}