feat: copyrat

This commit is contained in:
graelo 2020-05-24 21:02:11 +02:00
parent 0d45a2872a
commit 37f22b67af
11 changed files with 840 additions and 728 deletions

View file

@ -1,4 +1,4 @@
use std::collections::HashMap;
use crate::error;
const ALPHABETS: [(&'static str, &'static str); 22] = [
("numeric", "1234567890"),
@ -25,17 +25,17 @@ const ALPHABETS: [(&'static str, &'static str); 22] = [
("colemak-right-hand", "neioluymjhk"),
];
pub struct Alphabet<'a> {
letters: &'a str,
}
// pub struct Alphabet<'a> {
// letters: &'a str,
// }
impl<'a> Alphabet<'a> {
fn new(letters: &'a str) -> Alphabet {
Alphabet { letters }
}
/// Type-safe string alphabet (newtype).
#[derive(Debug)]
pub struct Alphabet(pub String);
impl Alphabet {
pub fn hints(&self, matches: usize) -> Vec<String> {
let letters: Vec<String> = self.letters.chars().map(|s| s.to_string()).collect();
let letters: Vec<String> = self.0.chars().map(|s| s.to_string()).collect();
let mut expansion = letters.clone();
let mut expanded: Vec<String> = Vec::new();
@ -64,14 +64,22 @@ impl<'a> Alphabet<'a> {
}
}
pub fn get_alphabet(alphabet_name: &str) -> Alphabet {
let alphabets: HashMap<&str, &str> = ALPHABETS.iter().cloned().collect();
// pub fn get_alphabet(alphabet_name: &str) -> Alphabet {
// let alphabets: HashMap<&str, &str> = ALPHABETS.iter().cloned().collect();
alphabets
.get(alphabet_name)
.expect(format!("Unknown alphabet: {}", alphabet_name).as_str()); // FIXME
// alphabets
// .get(alphabet_name)
// .expect(format!("Unknown alphabet: {}", alphabet_name).as_str());
Alphabet::new(alphabets[alphabet_name])
// Alphabet::new(alphabets[alphabet_name])
// }
pub fn parse_alphabet(src: &str) -> Result<Alphabet, error::ParseError> {
let alphabet = ALPHABETS.iter().find(|&(name, _letters)| name == &src);
match alphabet {
Some((_name, letters)) => Ok(Alphabet(letters.to_string())),
None => Err(error::ParseError::UnknownAlphabet),
}
}
#[cfg(test)]
@ -80,28 +88,28 @@ mod tests {
#[test]
fn simple_matches() {
let alphabet = Alphabet::new("abcd");
let alphabet = Alphabet("abcd".to_string());
let hints = alphabet.hints(3);
assert_eq!(hints, ["a", "b", "c"]);
}
#[test]
fn composed_matches() {
let alphabet = Alphabet::new("abcd");
let alphabet = Alphabet("abcd".to_string());
let hints = alphabet.hints(6);
assert_eq!(hints, ["a", "b", "c", "da", "db", "dc"]);
}
#[test]
fn composed_matches_multiple() {
let alphabet = Alphabet::new("abcd");
let alphabet = Alphabet("abcd".to_string());
let hints = alphabet.hints(8);
assert_eq!(hints, ["a", "b", "ca", "cb", "da", "db", "dc", "dd"]);
}
#[test]
fn composed_matches_max() {
let alphabet = Alphabet::new("ab");
let alphabet = Alphabet("ab".to_string());
let hints = alphabet.hints(8);
assert_eq!(hints, ["aa", "ab", "ba", "bb"]);
}