Don't convert octal if its not valid character

Signed-off-by: Hanif Bin Ariffin <hanif.ariffin.4326@gmail.com>
This commit is contained in:
Hanif Bin Ariffin 2021-08-01 12:32:35 +08:00
parent 3fa56eabce
commit d813e00588
2 changed files with 9 additions and 4 deletions

View file

@ -13,8 +13,9 @@ fn parse_octal(input: &str) -> IResult<&str, char> {
preceded(tag("\\"), recognize(many_m_n(1, 3, one_of("01234567")))), preceded(tag("\\"), recognize(many_m_n(1, 3, one_of("01234567")))),
|out: &str| { |out: &str| {
u32::from_str_radix(out, 8) u32::from_str_radix(out, 8)
.map(|u| char::from_u32(u).unwrap()) .map(|u| char::from_u32(u))
.ok() .ok()
.flatten()
}, },
)(input) )(input)
} }

View file

@ -22,6 +22,7 @@ pub enum BadSequence {
MultipleCharRepeatInSet2, MultipleCharRepeatInSet2,
CharRepeatInSet1, CharRepeatInSet1,
InvalidRepeatCount(String), InvalidRepeatCount(String),
EmptySet2WhenNotTruncatingSet1,
} }
impl Display for BadSequence { impl Display for BadSequence {
@ -42,6 +43,9 @@ impl Display for BadSequence {
BadSequence::InvalidRepeatCount(count) => { BadSequence::InvalidRepeatCount(count) => {
writeln!(f, "invalid repeat count '{}' in [c*n] construct", count) writeln!(f, "invalid repeat count '{}' in [c*n] construct", count)
} }
BadSequence::EmptySet2WhenNotTruncatingSet1 => {
writeln!(f, "when not truncating set1, string2 must be non-empty")
}
} }
} }
} }
@ -434,7 +438,7 @@ pub struct TranslateOperationStandard {
} }
impl TranslateOperationStandard { impl TranslateOperationStandard {
fn new(set1: Vec<char>, set2: Vec<char>) -> Result<TranslateOperationStandard, String> { fn new(set1: Vec<char>, set2: Vec<char>) -> Result<TranslateOperationStandard, BadSequence> {
if let Some(fallback) = set2.last().copied() { if let Some(fallback) = set2.last().copied() {
Ok(TranslateOperationStandard { Ok(TranslateOperationStandard {
translation_map: set1 translation_map: set1
@ -447,7 +451,7 @@ impl TranslateOperationStandard {
translation_map: HashMap::new(), translation_map: HashMap::new(),
}) })
} else { } else {
Err("when not truncating set1, string2 must be non-empty".to_string()) Err(BadSequence::EmptySet2WhenNotTruncatingSet1)
} }
} }
} }
@ -473,7 +477,7 @@ impl TranslateOperation {
set1: Vec<char>, set1: Vec<char>,
set2: Vec<char>, set2: Vec<char>,
complement: bool, complement: bool,
) -> Result<TranslateOperation, String> { ) -> Result<TranslateOperation, BadSequence> {
if complement { if complement {
Ok(TranslateOperation::Complement( Ok(TranslateOperation::Complement(
TranslateOperationComplement::new(set1, set2), TranslateOperationComplement::new(set1, set2),