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 {
|
match &ins.ins_type {
|
||||||
InsType::Path(ins_coll) => return match_instruction(&ins_coll, cs),
|
InsType::Path(ins_coll) => return match_instruction(&ins_coll, cs),
|
||||||
InsType::Node(ins) => {
|
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
|
println!("{:?} {}", ins, if let Some(n) = data { n.to_string() } else { "".to_owned() }); // TODO
|
||||||
return Ok(Some(ins.new_instruction(data)));
|
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)
|
Ok(None)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_number(cs: &mut dyn Iterator<Item=char>) -> isize {
|
fn read_number(cs: &mut dyn Iterator<Item=char>) -> Result<isize, ParseError> {
|
||||||
let mut is_positive = 1_isize;
|
let is_positive = if let Some(c) = cs.next() {
|
||||||
if let Some(c) = cs.next() {
|
if c == '草' { 1 } else if c == '泥' { -1 } else {
|
||||||
if c == '草' {
|
return Err(ParseError::ErrorSyntax("ERROR!!!! syntax error!".into()));
|
||||||
is_positive = 1;
|
|
||||||
} else if c == '泥' {
|
|
||||||
is_positive = -1;
|
|
||||||
} else {
|
|
||||||
// Syntax ERROR!
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Syntax ERROR!
|
return Err(ParseError::ErrorSyntax("ERROR!!!! syntax error!".into()));
|
||||||
}
|
};
|
||||||
let mut num = 0_isize;
|
let mut num = 0_isize;
|
||||||
while let Some(c) = cs.next() {
|
loop {
|
||||||
if c == '马' {
|
if let Some(c) = cs.next() {
|
||||||
break;
|
if c == '马' {
|
||||||
} else {
|
break;
|
||||||
num <<= 1;
|
} else {
|
||||||
num += if c == '草' { 0 } else { 1 };
|
num <<= 1;
|
||||||
|
num += if c == '草' { 0 } else { 1 };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
is_positive * num
|
Ok(is_positive * num)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_read_number() {
|
fn test_read_number() {
|
||||||
assert_eq!(read_number(&mut "草泥马".chars()), 1);
|
assert_eq!(read_number(&mut "草泥马".chars()).unwrap(), 1);
|
||||||
assert_eq!(read_number(&mut "草泥草草草草泥泥马".chars()), 67);
|
assert_eq!(read_number(&mut "草泥草草草草泥泥马".chars()).unwrap(), 67);
|
||||||
assert_eq!(read_number(&mut "草泥草泥泥马".chars()), 11);
|
assert_eq!(read_number(&mut "草泥草泥泥马".chars()).unwrap(), 11);
|
||||||
assert_eq!(read_number(&mut "草泥草草草泥草泥马".chars()), 69);
|
assert_eq!(read_number(&mut "草泥草草草泥草泥马".chars()).unwrap(), 69);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user