mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-08 18:49:07 +01:00
39 lines
999 B
Rust
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()
|
|
}
|
|
}
|