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
#![warn(clippy::all, clippy::pedantic)]
#![warn(missing_docs)]
use std::{num::ParseIntError, str::FromStr};
use lazy_static::lazy_static;
use num::{
cast::{FromPrimitive, ToPrimitive},
traits::Pow,
BigInt, Integer, Signed, Zero,
};
use rand::{seq::SliceRandom, Rng};
use thiserror::Error;
pub const ROWS: usize = 40;
pub const COLUMNS: usize = 80;
pub const PAGE_LENGTH: usize = ROWS * COLUMNS;
pub const TITLE_LENGTH: usize = 25;
pub const BABEL_SET: [char; 29] = [
' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ',', '.',
];
pub const BASE64_SET: [char; 64] = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_',
];
lazy_static! {
pub static ref PAGE_MULT: BigInt = BigInt::from(30).pow(PAGE_LENGTH);
pub static ref TITLE_MULT: BigInt = BigInt::from(30).pow(TITLE_LENGTH);
}
type LibResult<T> = Result<T, LibError>;
impl FromStr for Address {
type Err = LibError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let ar = s.split(':').collect::<Vec<&str>>();
if ar.len() == 5 && ar[0..=3].iter().all(|g| g.chars().all(char::is_numeric)) {
let addr = Address {
hex: ar[4].to_owned(),
wall: ar[0].parse::<u8>()?,
shelf: ar[1].parse::<u8>()?,
volume: ar[2].parse::<u8>()?,
page: ar[3].parse::<u16>()?,
};
check_address(&addr)?;
return Ok(addr);
}
Err(LibError::BrokenAddress)
}
}
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum LibError {
#[error("Title has to be under {} chars!", TITLE_LENGTH)]
TitleLength,
#[error("Page has to be under {} chars!", PAGE_LENGTH)]
PageLength,
#[error("The address is broken!")]
BrokenAddress,
#[error("Search string contains characters that are out of the BABEL_SET!")]
SearchString,
}
impl From<ParseIntError> for LibError {
fn from(_: ParseIntError) -> Self {
LibError::BrokenAddress
}
}
#[derive(PartialEq, Eq, Debug)]
pub struct Address {
pub hex: String,
pub wall: u8,
pub shelf: u8,
pub volume: u8,
pub page: u16,
}
impl std::fmt::Display for Address {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}:{}:{}:{}:{}", self.wall, self.shelf, self.volume, self.page, self.hex)
}
}
pub fn search_text_in_library(search_str: &str) -> LibResult<Address> {
if !search_str.chars().all(|x| BABEL_SET.contains(&x)) {
return Err(LibError::SearchString);
}
if search_str.len() > PAGE_LENGTH {
return Err(LibError::PageLength);
}
let mut rng = rand::thread_rng();
let wall = rng.gen_range(1..=4);
let shelf = rng.gen_range(1..=5);
let volume = rng.gen_range(1..=32);
let page = rng.gen_range(1..=410);
let loc = BigInt::from(usize::from(wall) * 1_000_000 + usize::from(shelf) * 100_000 + usize::from(volume) * 1_000 + usize::from(page));
let value = pad_rand(search_str);
let hex = to_babel(from_babel(&value, &BABEL_SET) + (loc * &*PAGE_MULT), &BASE64_SET);
Ok(Address { hex, wall, shelf, volume, page })
}
pub fn search_page_by_title(search_str: &str) -> LibResult<Address> {
if !search_str.chars().all(|x| BABEL_SET.contains(&x)) {
return Err(LibError::SearchString);
}
if search_str.len() > TITLE_LENGTH {
return Err(LibError::TitleLength);
}
let mut rng = rand::thread_rng();
let wall = rng.gen_range(1..=4);
let shelf = rng.gen_range(1..=5);
let volume = rng.gen_range(1..=32);
let loc = BigInt::from(usize::from(wall) * 1_000_000 + usize::from(shelf) * 100_000 + usize::from(volume) * 1_000);
let hex = to_babel(from_babel(search_str, &BABEL_SET) + (loc * &*TITLE_MULT), &BASE64_SET);
Ok(Address {
hex,
wall,
shelf,
volume,
page: 1,
})
}
pub fn get_title_of_page(addr: &Address) -> LibResult<String> {
check_address(addr)?;
let loc = BigInt::from(usize::from(addr.wall) * 1_000_000 + usize::from(addr.shelf) * 100_000 + usize::from(addr.volume) * 1_000);
Ok(to_babel(from_babel(&addr.hex, &BASE64_SET) - (loc * &*TITLE_MULT), &BABEL_SET))
}
pub fn get_page(addr: &Address, format: bool) -> LibResult<String> {
check_address(addr)?;
let loc = BigInt::from(usize::from(addr.wall) * 1_000_000 + usize::from(addr.shelf) * 100_000 + usize::from(addr.volume) * 1_000 + usize::from(addr.page));
let mut babel_page = to_babel(from_babel(&addr.hex, &BASE64_SET) - (loc * &*PAGE_MULT), &BABEL_SET);
if format {
let mut ip_page = String::new();
for (i, a) in babel_page.chars().enumerate() {
ip_page.push(a);
if (i + 1) % COLUMNS == 0 {
ip_page.push('\n');
}
}
babel_page = ip_page;
};
Ok(babel_page)
}
fn from_babel(value: &str, set: &[char]) -> BigInt {
let mut result = BigInt::zero();
let base = BigInt::from_usize(set.len()).unwrap();
for bn in value.chars() {
result = &result * &base + &BigInt::from_usize(set.iter().position(|&b| bn == b).unwrap()).unwrap();
}
result
}
fn to_babel(mut value: BigInt, set: &[char]) -> String {
if value.is_negative() {
value = -value;
}
let base = BigInt::from_usize(set.len()).unwrap();
let mut arb = String::with_capacity(4096);
while !value.is_zero() {
let (new_val, rem) = value.div_mod_floor(&base);
arb.push(set[rem.to_usize().unwrap()]);
value = new_val;
}
arb.chars().rev().collect()
}
fn pad_rand(value: &str) -> String {
if value.len() >= PAGE_LENGTH {
return value.to_string();
}
let mut page = String::with_capacity(PAGE_LENGTH);
let mut rng = rand::thread_rng();
let before = rng.gen_range(0..(PAGE_LENGTH - value.len()));
for _ in 0..before {
page.push(*BABEL_SET.choose(&mut rng).unwrap());
}
page.push_str(value);
while page.len() < PAGE_LENGTH {
page.push(*BABEL_SET.choose(&mut rng).unwrap());
}
page
}
pub fn check_address(addr: &Address) -> LibResult<()> {
if let Address {
hex,
wall: 1..=4,
shelf: 1..=5,
volume: 1..=32,
page: 1..=410,
} = addr
{
if hex.chars().all(|x| BASE64_SET.contains(&x)) {
return Ok(());
}
}
Err(LibError::BrokenAddress)
}