ref read_number
This commit is contained in:
43
src/main.rs
43
src/main.rs
@@ -40,7 +40,7 @@ fn match_instruction(ins_coll: &InsColl, cs: &mut dyn Iterator<Item=char>) -> 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<Item=char>) -> Re
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn read_number(cs: &mut dyn Iterator<Item=char>) -> 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<Item=char>) -> Result<isize, ParseError> {
|
||||
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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user