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
use crate::prelude::{CharacterParseError, ALPHABET};
use crate::utils::{BaseString, EncodedString, StringType, THRESHOLD};
use rayon::prelude::*;
#[cfg(feature = "python-integration")]
use pyo3_helper_macros::{py3_bind_pub, exclude};
#[cfg_attr(feature = "python-integration", py3_bind_pub(supported = {StringType, BaseString, EncodedString, Vec<usize>}))]
impl BaseString {
pub fn new(data: String) -> Self {
Self { data }
}
/// Encodes a string to a vector of indices based on the alphabet.
///
/// # Example
///
/// ```
/// # use ferric_crypto_lib::utils::{BaseString, EncodedString, StringType};
///
/// let t = BaseString::new("abc".to_string());
/// assert_eq!(t.encode().unwrap(), EncodedString::new(vec![0, 1, 2], StringType::Standard));
/// ```
pub fn encode(&self) -> Result<EncodedString, CharacterParseError> {
let data = self.data.to_lowercase();
let data_len = data.chars().count();
#[cfg(feature = "debug")]
{
// Log the input data and its length
dbg!(&data, data_len);
}
let encoded = if data_len > THRESHOLD {
data.par_chars()
.map(|x| {
#[cfg(feature = "debug")]
{
let position = crate::prelude::ALPHABET.chars().position(|y| y == x);
dbg!(&x, &position); // Log each character and its index (sequential branch)
position.ok_or(CharacterParseError::InvalidCharacter(x))
}
#[cfg(not(feature = "debug"))]
{
ALPHABET
.chars()
.position(|y| y == x)
.ok_or(CharacterParseError::InvalidCharacter(x))
}
})
.collect::<Result<Vec<_>, _>>()?
} else {
data.chars()
.map(|x| {
#[cfg(feature = "debug")]
{
let position = crate::prelude::ALPHABET.chars().position(|y| y == x);
dbg!(&x, &position); // Log each character and its index (sequential branch)
position.ok_or(CharacterParseError::InvalidCharacter(x))
}
#[cfg(not(feature = "debug"))]
{
ALPHABET
.chars()
.position(|y| y == x)
.ok_or(CharacterParseError::InvalidCharacter(x))
}
})
.collect::<Result<Vec<_>, _>>()?
};
#[cfg(feature = "debug")]
{
// Log the final encoded data
dbg!(&encoded);
}
// Return based on whether the lengths match
if data_len == encoded.len() {
Ok(EncodedString::new(encoded, StringType::Standard))
} else {
Err(CharacterParseError::UnknownStringType)
}
}
/// Encodes a string to a vector of indices based on the alphabet.
///
/// # Example
///
/// ```
/// # use ferric_crypto_lib::utils::{BaseString, EncodedString, StringType};
///
/// let t = BaseString::new("abc".to_string());
/// assert_eq!(t.encode_asym().unwrap(), EncodedString::new(vec![1, 2, 3], StringType::Assymetric));
/// ```
pub fn encode_asym(&self) -> Result<EncodedString, CharacterParseError> {
let data = self.data.to_lowercase();
let data_len = data.chars().count();
// Log the input data and its length
#[cfg(feature = "debug")]
dbg!(&data, data_len);
let encoded = if data_len > THRESHOLD {
data.par_chars()
.map(|x| {
let position = ALPHABET.chars().position(|y| y == x).map(|index| index + 1); // Add 1 to avoid zero
#[cfg(feature = "debug")]
dbg!(&x, &position); // Log each character and its index
position.ok_or(CharacterParseError::InvalidCharacter(x))
})
.collect::<Result<Vec<_>, _>>()?
} else {
data.chars()
.map(|x| {
let position = ALPHABET.chars().position(|y| y == x).map(|index| index + 1); // Add 1 to avoid zero
#[cfg(feature = "debug")]
dbg!(&x, &position); // Log each character and its index
position.ok_or(CharacterParseError::InvalidCharacter(x))
})
.collect::<Result<Vec<_>, _>>()?
};
// Log the final encoded data
#[cfg(feature = "debug")]
dbg!(&encoded);
Ok(EncodedString::new(encoded, StringType::Assymetric))
}
// include more encodings here, such as base64 and binary encodings
}
impl BaseString {
#[cfg_attr(feature = "python-integration", exclude)]
pub fn to_uppercase(self) -> Self {
let cpy = self.clone();
let cpy = cpy.data.to_uppercase();
Self { data: cpy }
}
#[cfg_attr(feature = "python-integration", exclude)]
pub fn to_lowercase(self) -> Self {
let cpy = self.clone();
let cpy = cpy.data.to_lowercase();
Self { data: cpy }
}
pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
self.data.chars()
}
pub fn par_chars(&self) -> rayon::str::Chars<'_> {
self.data.par_chars()
}
}
#[cfg_attr(feature = "python-integration", py3_bind_pub(supported = {StringType, BaseString, EncodedString, Vec<usize>}))]
impl EncodedString {
// represents the encoded string as a vector of usize
pub fn new(data: Vec<usize>, str_type: StringType) -> Self {
Self { data, str_type }
}
// error handling falls on the user not the lib in this case, user should know what has gone wrong and handle it
pub fn decode(&self) -> Result<BaseString, CharacterParseError> {
match self.str_type {
StringType::Standard => self.decode_std(),
StringType::Assymetric => self.decode_asym(),
_ => Err(CharacterParseError::UnknownStringType),
}
}
fn decode_std(&self) -> Result<BaseString, CharacterParseError> {
let decoded = if self.data.len() > THRESHOLD {
self.data
.par_iter()
.map(|&x| {
ALPHABET
.chars()
.nth(x)
.ok_or(CharacterParseError::InvalidIndex(x))
})
.collect::<Result<String, _>>()?
} else {
self.data
.iter()
.map(|&x| {
ALPHABET
.chars()
.nth(x)
.ok_or(CharacterParseError::InvalidIndex(x))
})
.collect::<Result<String, _>>()?
};
Ok(BaseString::new(decoded))
}
fn decode_asym(&self) -> Result<BaseString, CharacterParseError> {
let decoded = if self.data.len() > THRESHOLD {
self.data
.par_iter()
.map(|&x| {
ALPHABET
.chars()
.nth(x - 1)
.ok_or(CharacterParseError::InvalidIndex(x))
})
.collect::<Result<String, _>>()?
} else {
self.data
.iter()
.map(|&x| {
ALPHABET
.chars()
.nth(x - 1)
.ok_or(CharacterParseError::InvalidIndex(x))
})
.collect::<Result<String, _>>()?
};
Ok(BaseString::new(decoded))
}
/// # Example
///
/// ```
/// # use ferric_crypto_lib::utils::{EncodedString, StringType};
///
/// let t = EncodedString::new(vec![1, 2, 3], StringType::Standard);
/// assert_eq!(t.flatten(), "123".to_string());
/// ```
///
/// ```
/// # use ferric_crypto_lib::utils::{EncodedString, StringType};
///
/// let t = EncodedString::new(vec![1, 2, 3], StringType::Assymetric);
/// assert_eq!(t.flatten(), "10203".to_string());
/// ```
pub fn flatten(&self) -> String {
let data = self.data.clone();
let mut new_str = String::new();
if self.str_type == StringType::Standard {
for x in data {
new_str.push_str(&x.to_string());
}
} else {
// if we do not have a standard string, we treat it as a asymetric string
// if any number but the first number is less then 10, add a 0 to the start
for (i, x) in data.iter().enumerate() {
if i != 0 && *x < 10 {
new_str.push_str(&format!("0{}", x));
} else {
new_str.push_str(&x.to_string());
}
}
}
new_str
}
}
impl EncodedString {
pub fn iter(&self) -> impl Iterator<Item = &usize> {
self.data.iter()
}
pub fn par_iter(&self) -> rayon::slice::Iter<'_, usize> {
self.data.par_iter()
}
}
#[cfg(feature = "python-integration")]
mod python_integration {
use super::*;
use pyo3::prelude::*;
#[pymethods]
impl EncodedString {
pub fn __str__(&self) -> PyResult<String> {
Ok(format!("Encoded String: data = {:?}, type = {:?}", self.data, self.str_type))
}
}
#[pymethods]
impl BaseString {
pub fn __str__(&self) -> PyResult<String> {
Ok(format!("Base String: data = {:?}", self.data))
}
}
}