From 42826cc78fbbbaf04a162f23863a96268bf0bfe0 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Wed, 6 May 2020 00:23:55 +0800 Subject: [PATCH] ref read_number --- src/main.rs | 43 ++++++++++++++++++++----------------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/src/main.rs b/src/main.rs index 18c62be..745c4bc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -40,7 +40,7 @@ fn match_instruction(ins_coll: &InsColl, cs: &mut dyn Iterator) -> Re match &ins.ins_type { InsType::Path(ins_coll) => return match_instruction(&ins_coll, cs), InsType::Node(ins) => { - let data = if ins.has_data() { Some(read_number(cs)) } else { None }; + let data = if ins.has_data() { Some(read_number(cs)?) } else { None }; println!("{:?} {}", ins, if let Some(n) = data { n.to_string() } else { "".to_owned() }); // TODO return Ok(Some(ins.new_instruction(data))); }, @@ -53,35 +53,32 @@ fn match_instruction(ins_coll: &InsColl, cs: &mut dyn Iterator) -> Re Ok(None) } -fn read_number(cs: &mut dyn Iterator) -> isize { - let mut is_positive = 1_isize; - if let Some(c) = cs.next() { - if c == '草' { - is_positive = 1; - } else if c == '泥' { - is_positive = -1; - } else { - // Syntax ERROR! +fn read_number(cs: &mut dyn Iterator) -> Result { + let is_positive = if let Some(c) = cs.next() { + if c == '草' { 1 } else if c == '泥' { -1 } else { + return Err(ParseError::ErrorSyntax("ERROR!!!! syntax error!".into())); } } else { - // Syntax ERROR! - } + return Err(ParseError::ErrorSyntax("ERROR!!!! syntax error!".into())); + }; let mut num = 0_isize; - while let Some(c) = cs.next() { - if c == '马' { - break; - } else { - num <<= 1; - num += if c == '草' { 0 } else { 1 }; + loop { + if let Some(c) = cs.next() { + if c == '马' { + break; + } else { + num <<= 1; + num += if c == '草' { 0 } else { 1 }; + } } } - is_positive * num + Ok(is_positive * num) } #[test] fn test_read_number() { - assert_eq!(read_number(&mut "草泥马".chars()), 1); - assert_eq!(read_number(&mut "草泥草草草草泥泥马".chars()), 67); - assert_eq!(read_number(&mut "草泥草泥泥马".chars()), 11); - assert_eq!(read_number(&mut "草泥草草草泥草泥马".chars()), 69); + assert_eq!(read_number(&mut "草泥马".chars()).unwrap(), 1); + assert_eq!(read_number(&mut "草泥草草草草泥泥马".chars()).unwrap(), 67); + assert_eq!(read_number(&mut "草泥草泥泥马".chars()).unwrap(), 11); + assert_eq!(read_number(&mut "草泥草草草泥草泥马".chars()).unwrap(), 69); }