crypto_random_map/
aligned.rs

1//! doc me
2use convert_base::Convert;
3use rand::seq::SliceRandom;
4use std::{ops::Index, str};
5use std::collections::BTreeMap;
6
7/// SecretAligned
8#[derive(Debug)]
9pub struct SecretAligned {
10    order: u64,
11    set: String,
12    map: BTreeMap<u64, Vec<char>>,
13}
14
15impl SecretAligned {
16    /// doc me
17    pub fn new(codes: &str) -> Self {
18        let count = codes.chars().count();
19        let order = u64::pow(2, (count as f32).log2().floor() as u32) as usize;
20        let mut map = BTreeMap::new();
21        if order == count {
22            for i in 0..order {
23                map.insert(i as u64, vec![codes.chars().nth(i).unwrap()]);
24            }
25        }
26        else {
27            for i in 0..(count - order) {
28                map.insert(i as u64, vec![codes.chars().nth(i).unwrap(), codes.chars().nth(i + order).unwrap()]);
29            }
30            for i in (count - order)..order {
31                map.insert(i as u64, vec![codes.chars().nth(i).unwrap()]);
32            }
33        }
34        SecretAligned { set: codes.to_string(), order: order as u64, map }
35    }
36    /// doc me
37    pub fn encode(&self, v: &[u8]) -> Vec<char> {
38        let mut base = Convert::new(256, self.order);
39        let output = base.convert::<u8, u64>(&v.to_vec());
40        self.index_vec(output)
41    }
42    /// doc me
43    pub fn decode(&self, s: &str) -> Vec<u8> {
44        let c = s.chars().collect::<Vec<char>>();
45        let v = self.index_str(c);
46        let mut base = Convert::new(self.order, 256);
47        base.convert::<u64, u8>(&v.to_vec())
48    }
49}
50
51#[allow(unused_variables)]
52#[allow(unreachable_code)]
53impl Index<usize> for SecretAligned {
54    type Output = Option<char>;
55    fn index(&self, index: usize) -> &Self::Output {
56        unimplemented!()
57    }
58}
59
60#[allow(unreachable_code)]
61#[allow(unused_variables)]
62impl Index<char> for SecretAligned {
63    type Output = Option<usize>;
64    fn index(&self, index: char) -> &Self::Output {
65        unimplemented!();
66        &self.set.chars().position(|c| c == index)
67    }
68}
69
70impl SecretAligned {
71    fn index_vec(&self, index: Vec<u64>) -> Vec<char> {
72        // index.iter().map(|i| self.set.chars().nth(*i as usize).unwrap()).collect()
73        let mut v = vec![];
74        for i in index {
75            let r = self.map[&i].choose(&mut rand::thread_rng());
76            v.push(*r.unwrap())
77        }
78        return v;
79    }
80    fn index_str(&self, index: Vec<char>) -> Vec<u64> {
81        let mut dict = BTreeMap::new();
82        let mut count = 0;
83        for c in self.set.chars() {
84            dict.insert(c, count % self.order as usize);
85            count += 1
86        }
87        index.iter().map(|i| dict[&i] as u64).collect()
88    }
89}