Skip to content

Commit 711a585

Browse files
committed
use an hashmap to avoid duplicating code
1 parent 6eb57fb commit 711a585

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

parser/src/command/shortcut.rs

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@
1010
1111
use crate::error::Error;
1212
use crate::token::{Token, Tokenizer};
13+
use std::collections::HashMap;
1314
use std::fmt;
1415

15-
#[derive(PartialEq, Eq, Debug)]
16+
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
1617
pub enum ShortcutCommand {
1718
Ready,
1819
Author,
@@ -35,28 +36,26 @@ impl fmt::Display for ParseError {
3536

3637
impl ShortcutCommand {
3738
pub fn parse<'a>(input: &mut Tokenizer<'a>) -> Result<Option<Self>, Error<'a>> {
39+
let mut shortcuts = HashMap::new();
40+
shortcuts.insert("ready", ShortcutCommand::Ready);
41+
shortcuts.insert("author", ShortcutCommand::Author);
42+
3843
let mut toks = input.clone();
39-
if let Some(Token::Word("ready")) = toks.peek_token()? {
40-
toks.next_token()?;
41-
if let Some(Token::Dot) | Some(Token::EndOfLine) = toks.peek_token()? {
42-
toks.next_token()?;
43-
*input = toks;
44-
return Ok(Some(ShortcutCommand::Ready));
45-
} else {
46-
return Err(toks.error(ParseError::ExpectedEnd));
47-
}
48-
} else if let Some(Token::Word("author")) = toks.peek_token()? {
44+
if let Some(Token::Word(word)) = toks.peek_token()? {
4945
toks.next_token()?;
5046
if let Some(Token::Dot) | Some(Token::EndOfLine) = toks.peek_token()? {
47+
if !shortcuts.contains_key(word) {
48+
return Ok(None);
49+
}
5150
toks.next_token()?;
5251
*input = toks;
53-
return Ok(Some(ShortcutCommand::Author));
52+
let command = shortcuts.get(word).unwrap();
53+
return Ok(Some(*command));
5454
} else {
5555
return Err(toks.error(ParseError::ExpectedEnd));
5656
}
57-
} else {
58-
return Ok(None);
5957
}
58+
Ok(None)
6059
}
6160
}
6261

0 commit comments

Comments
 (0)