Sha256: 29be34618a99698b543abf2ea4cea0ac14d0b937e39f880ee6e45f071ec0dc6d

Contents?: true

Size: 1.01 KB

Versions: 29

Compression:

Stored size: 1.01 KB

Contents

extern crate rand;
use rand::Rng;

pub fn encode_random(s: &str) -> (String, String) {
    let mut r = rand::thread_rng();
    let mut key = String::new();
    for _ in 0..100 {
        key.push(char::from('a' as u8 + r.gen_range(0, 26)));
    }
    let encoded = encode(&key, s);
    (key, encoded.unwrap())
}

pub fn encode(key: &str, s: &str) -> Option<String> {
    shift(key, s, 1)
}

pub fn decode(key: &str, s: &str) -> Option<String> {
    shift(key, s, -1)
}

fn shift(key: &str, s: &str, dir: i8) -> Option<String> {
    if key.is_empty() {
        return None;
    }
    let mut o = String::new();
    let mut i = 0;
    let mut key_arr = Vec::new();
    for c in key.chars() {
        if !c.is_ascii_lowercase() {
            return None;
        }
        key_arr.push(c);
    }
    for c in s.chars() {
        let shift = key_arr[i % key_arr.len()] as i8 - 'a' as i8;
        let n = ((c as i8 - 'a' as i8 + dir * shift) % 26 + 26) % 26;
        o.push(char::from('a' as u8 + n as u8));
        i += 1;
    }
    Some(o)
}

Version data entries

29 entries across 29 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.179 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.178 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.177 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.176 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.175 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.174 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.173 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.172 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.171 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.170 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.169 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.167 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.166 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.165 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.164 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.163 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.162 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.161 tracks/rust/exercises/simple-cipher/example.rs
trackler-2.2.1.160 tracks/rust/exercises/simple-cipher/example.rs