1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-08 18:49:07 +01:00
CodeWars/6kyu/simple_substitution_cipher_helper/solution.rs
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

39 lines
999 B
Rust

pub struct Cipher {
decoded: Vec<u8>,
encoded: Vec<u8>,
}
impl Cipher {
pub fn new(map1: &str, map2: &str) -> Cipher {
Cipher {
decoded: map1.as_bytes().to_vec(),
encoded: map2.as_bytes().to_vec(),
}
}
pub fn encode(&self, string: &str) -> String {
String::from_utf8(
string
.bytes()
.map(|c| match self.decoded.iter().position(|x| x == &c) {
Some(i) => self.encoded[i],
None => c,
})
.collect::<Vec<u8>>(),
)
.unwrap()
}
pub fn decode(&self, string: &str) -> String {
String::from_utf8(
string
.bytes()
.map(|c| match self.encoded.iter().position(|x| x == &c) {
Some(i) => self.decoded[i],
None => c,
})
.collect::<Vec<u8>>(),
)
.unwrap()
}
}