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
use once_cell::sync::Lazy;
use regex::Regex;
use crate::{
common::{BitArray, Result},
Exceptions,
};
static ONE: Lazy<Regex> = Lazy::new(|| Regex::new("1").unwrap());
static ZERO: Lazy<Regex> = Lazy::new(|| Regex::new("0").unwrap());
static SPACE: Lazy<Regex> = Lazy::new(|| Regex::new(" ").unwrap());
pub fn buildBitArrayFromString(data: &str) -> Result<BitArray> {
let dotsAndXs = ZERO
.replace_all(&ONE.replace_all(data, "X"), ".")
.to_string();
let mut binary = BitArray::with_size(SPACE.replace_all(&dotsAndXs, "").chars().count());
let mut counter = 0;
for i in 0..dotsAndXs.chars().count() {
if i % 9 == 0 {
if dotsAndXs.chars().nth(i).ok_or(Exceptions::PARSE)? != ' ' {
return Err(Exceptions::illegal_state_with("space expected"));
}
continue;
}
let currentChar = dotsAndXs.chars().nth(i).ok_or(Exceptions::PARSE)?;
if currentChar == 'X' || currentChar == 'x' {
binary.set(counter);
}
counter += 1;
}
Ok(binary)
}
pub fn buildBitArrayFromStringWithoutSpaces(data: &str) -> Result<BitArray> {
let mut sb = String::new();
let dotsAndXs = ZERO
.replace_all(&ONE.replace_all(data, "X"), ".")
.to_string();
let mut current = 0;
let dotsAndXs_length = dotsAndXs.chars().count();
while current < dotsAndXs_length {
sb.push(' ');
let mut i = 0;
while i < 8 && current < dotsAndXs_length {
sb.push(dotsAndXs.chars().nth(current).ok_or(Exceptions::PARSE)?);
current += 1;
i += 1;
}
}
buildBitArrayFromString(&sb)
}
#[cfg(test)]
mod BinaryUtilTest {
#[test]
fn testBuildBitArrayFromString() {
let data = " ..X..X.. ..XXX... XXXXXXXX ........";
check(data);
let data = " XXX..X..";
check(data);
let data = " XX";
check(data);
let data = " ....XX.. ..XX";
check(data);
let data = " ....XX.. ..XX..XX ....X.X. ........";
check(data);
}
fn check(data: &str) {
let binary = super::buildBitArrayFromString(data).expect("check");
assert_eq!(data, binary.to_string());
}
#[test]
fn testBuildBitArrayFromStringWithoutSpaces() {
let data = " ..X..X.. ..XXX... XXXXXXXX ........";
checkWithoutSpaces(data);
let data = " XXX..X..";
checkWithoutSpaces(data);
let data = " XX";
checkWithoutSpaces(data);
let data = " ....XX.. ..XX";
checkWithoutSpaces(data);
let data = " ....XX.. ..XX..XX ....X.X. ........";
checkWithoutSpaces(data);
}
fn checkWithoutSpaces(data: &str) {
let dataWithoutSpaces = super::SPACE.replace_all(data, "");
let binary =
super::buildBitArrayFromStringWithoutSpaces(&dataWithoutSpaces).expect("success");
assert_eq!(data, binary.to_string());
}
}