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
//!A Rust implementation of The Library of Babel
#![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;

/// Number of rows in a page
pub const ROWS: usize = 40;
/// Number of columns in a page
pub const COLUMNS: usize = 80;
/// Total length of a page
pub const PAGE_LENGTH: usize = ROWS * COLUMNS;
/// Max length of a book title
pub const TITLE_LENGTH: usize = 25;
/// BABEL set of chars
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', ',', '.',
];
/// BASE64 set of chars
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! {
    // Create a huge multiplier
    // When this number is multiplied onto [`loc`] it simulates randomness but in a predictable and reversable way.
    /// Page multiplier
    pub static ref PAGE_MULT: BigInt = BigInt::from(30).pow(PAGE_LENGTH);
    /// Title multiplier
    pub static ref TITLE_MULT: BigInt = BigInt::from(30).pow(TITLE_LENGTH);
}

/// Library of Babel error type
type LibResult<T> = Result<T, LibError>;

impl FromStr for Address {
    type Err = LibError;

    /// Parse [`str`] address from [`str`] to [`Address`]
    /// # Errors
    /// This fn() returns Error if the [`Address`] is wrong
    /// # Panics
    /// This fn() panics if you put in bigger numbers than they can hold
    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)
    }
}

/// Enum of errors that this crate can return
#[derive(Error, Debug)]
#[non_exhaustive] // Maybe we will add more of them
pub enum LibError {
    /// The length of a title is not correct
    #[error("Title has to be under {} chars!", TITLE_LENGTH)]
    TitleLength,
    /// The length of a page is not correct
    #[error("Page has to be under {} chars!", PAGE_LENGTH)]
    PageLength,
    /// The [`Address`] is outside of allowed constraints
    #[error("The address is broken!")]
    BrokenAddress,
    /// Search [`str`] contains characters that are out of the [`BABEL_SET`]
    #[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)]
/// Struct containing [`Address`] to a page in a book on a shelf in the wall in the hex room
pub struct Address {
    /// Hex room
    pub hex: String,
    /// Wall
    pub wall: u8,
    /// Shelf
    pub shelf: u8,
    /// Volume/Book
    pub volume: u8,
    /// Page
    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)
    }
}

/// Search specific text in the library and return a page
/// # Errors
/// Returns [`LibError`] if search string contains chars outside of [`BABEL_SET`] or it's length is more than [`PAGE_LENGTH`]
pub fn search_text_in_library(search_str: &str) -> LibResult<Address> {
    // Make sure the input is made only out of chars from the correct set
    if !search_str.chars().all(|x| BABEL_SET.contains(&x)) {
        return Err(LibError::SearchString);
    }

    // Make sure input is correct page length
    if search_str.len() > PAGE_LENGTH {
        return Err(LibError::PageLength);
    }

    let mut rng = rand::thread_rng();

    // Randomly generate the location within hex that this page will be located
    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);

    // Combine the location into a single unique (per hex) number
    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);

    // Finally find the hexagon room address based on the desired page
    // contents and our randomly decided upon location
    let hex = to_babel(from_babel(&value, &BABEL_SET) + (loc * &*PAGE_MULT), &BASE64_SET);

    Ok(Address { hex, wall, shelf, volume, page })
}

/// Search page by a title in the library and return a [`Address`] to the book pointing to first page
/// # Errors
/// Returns [`LibError`] if search string contains chars outside of [`BABEL_SET`] or it's length is more than [`TITLE_LENGTH`]
pub fn search_page_by_title(search_str: &str) -> LibResult<Address> {
    // Make sure the input is made only out of chars from the correct set
    if !search_str.chars().all(|x| BABEL_SET.contains(&x)) {
        return Err(LibError::SearchString);
    }

    // Make sure input is correct length
    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);
    // the string made up of all of the location numbers
    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); // change to base 36 and add loc_int, then make string

    Ok(Address {
        hex,
        wall,
        shelf,
        volume,
        page: 1,
    })
}

/// Get a title of the page at an [`Address`] in the library
/// # Errors
/// Returns [`LibError`] if [`Address`] is outside of allowed constraints
pub fn get_title_of_page(addr: &Address) -> LibResult<String> {
    // Make sure the `Address` is correct
    check_address(addr)?;

    // Create the location identifier and huge multiplier in the exact same way
    // as was done in the [`search`] function
    let loc = BigInt::from(usize::from(addr.wall) * 1_000_000 + usize::from(addr.shelf) * 100_000 + usize::from(addr.volume) * 1_000);

    // Find the title of the page contents based on the hexagon room address and supplied location
    Ok(to_babel(from_babel(&addr.hex, &BASE64_SET) - (loc * &*TITLE_MULT), &BABEL_SET))
}

/// Get a page at an [`Address`] in the library
/// # Errors
/// Returns [`LibError`] if [`Address`] is outside of allowed constraints
pub fn get_page(addr: &Address, format: bool) -> LibResult<String> {
    // Make sure the `Address` is correct
    check_address(addr)?;

    // Create the location identifier and huge multiplier in the exact same way
    // as was done in the [`search`] function
    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));

    // Find the page contents based on the hexagon room address and supplied location
    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)
}

/// Convert from the Bable character set to decimal [`BigInt`]
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
}

/// Convert from decimal [`BigInt`] to the Babel character set
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()
}

/// Return a string randomly padded with Babel characters
/// # Panics
// Theoretically should not be possible!
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
}

/// Check if all values in the [`Address`] are within allowed constraints
/// # Errors
/// Returns [`LibError`] if the [`Address`] is outside of allowed constraints
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)
}