parser: parse AlphaLower/Upper numbers

This commit is contained in:
Noah Hellman 2023-01-23 21:41:04 +01:00
parent 35beb18dad
commit a661a2febb

View file

@ -267,7 +267,26 @@ impl OrderedListNumbering {
fn parse_number(self, n: &str) -> u32 {
match self {
Self::Decimal => n.parse().unwrap(),
Self::AlphaLower | Self::AlphaUpper => 1,
Self::AlphaLower | Self::AlphaUpper => {
let d0 = u32::from(if matches!(self, Self::AlphaLower) {
b'a'
} else {
b'A'
});
let weights = (1..=n.len()).scan(1, |a, _| {
let prev = *a;
*a *= 26;
Some(prev)
});
n.as_bytes()
.iter()
.rev()
.copied()
.map(u32::from)
.zip(weights)
.map(|(d, w)| w * (d - d0 + 1))
.sum()
}
Self::RomanLower => 1,
Self::RomanUpper => 1,
}
@ -1102,4 +1121,12 @@ mod test {
}),
);
}
#[test]
fn numbering_alpha() {
assert_eq!(AlphaLower.parse_number("a"), 1);
assert_eq!(AlphaUpper.parse_number("B"), 2);
assert_eq!(AlphaUpper.parse_number("Z"), 26);
assert_eq!(AlphaLower.parse_number("aa"), 27);
}
}