fractus/cipher/
replacer.rs1use std::collections::HashMap;
2use colored::*;
3use std::borrow::Borrow;
4use std::fmt;
5
6pub struct Replacer {
7 pub tokens: Vec<String>,
8 pub map: HashMap<String, String>,
9}
10
11
12impl fmt::Display for Replacer {
13 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
14 for c in &self.tokens {
15 if let Some(color) = self.map.get(c) {
16 write!(f, "{}", color.red())?;
17 } else {
18 write!(f, "{}", c)?;
19 }
20 }
21 Ok(())
22 }
23}
24
25impl Replacer {
26 pub fn new() -> Self {
27 Self {
28 tokens: vec![],
29 map: HashMap::new(),
30 }
31 }
32 pub fn tokens(&mut self, v: impl Borrow<str>) {
33 let v = v.borrow();
34
35 for c in v.chars() {
36 self.tokens.push(c.to_string());
37 }
38 }
39 pub fn replace(&mut self, lhs: impl Borrow<str>, rhs: impl Borrow<str>) {
40 let lhs = lhs.borrow();
41 let rhs = rhs.borrow();
42
43 self.map.insert(lhs.to_string(), rhs.to_string());
44 }
45 pub fn caesar(&mut self, alphabet: String, key: i32) {
46 for i in 0..alphabet.len() {
47 let l = alphabet.len() as i32;
48 let a: usize = ((key % l) + l).try_into().unwrap();
49 let new_i: usize = (i + a) % alphabet.len();
50 self.map.insert(alphabet.chars().nth(i).unwrap().to_string(), alphabet.chars().nth(new_i).unwrap().to_string());
51 }
52 }
53 pub fn result(&self) -> String {
54 let mut s = String::new();
55 for c in &self.tokens {
56 if self.map.contains_key(c) {
57 s.push_str(&self.map[c]);
58 }
59 else {
60 s.push_str(c);
61 }
62 }
63 s
64 }
65
66 pub fn count(&self) -> Vec<(String, usize)> {
67 let mut m = HashMap::new();
68 for s in &self.tokens {
69 *m.entry(s.clone()).or_insert(0) += 1;
70 }
71
72 let mut v: Vec<(String, usize)> = m.into_iter().collect();
73 v.sort_by(|a, b| b.1.cmp(&a.1));
74 v
75 }
76}