1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 19:19:07 +01:00
CodeWars/6kyu/simple_substitution_cipher_helper/solution.rs

40 lines
999 B
Rust
Raw Normal View History

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()
}
}