///|
/// Create the default two-form rule with index zero for n=1 and one otherwise.
/// Example: `@plural.PluralRule::default_germanic()`.
pub fn PluralRule::default_germanic() -> PluralRule {
{ nplurals: 2, expr: Binary(NotEq, VarN, Literal(1)), source: "(n != 1)", }
}
///|
/// Compile a Plural-Forms value. Raises PluralError for invalid assignments, counts outside 1..64 or expression errors.
/// Example: `@plural.PluralRule::parse("nplurals=2; plural=n!=1;")`.
pub fn PluralRule::parse(header_value : String) -> PluralRule raise PluralError {
fn bad(reason : String) -> PluralError {
MalformedPluralHeader(raw=header_value, reason~)
}
guard header_value.split_once(";") is Some((count, tail)) else {
raise bad("expected nplurals and plural assignments")
}
guard count.split_once("=") is Some((key, raw)) && key.trim() == "nplurals" else {
raise bad("expected nplurals assignment")
}
let digits = raw.trim()
let mut nplurals = 0
for c in digits {
if c < '0' || c > '9' {
raise InvalidNplurals(value=digits.to_owned())
}
nplurals = nplurals * 10 + c.to_int() - 48
if nplurals > 64 {
raise InvalidNplurals(value=digits.to_owned())
}
}
if nplurals == 0 {
raise InvalidNplurals(value=digits.to_owned())
}
guard tail.split_once("=") is Some((key, value)) && key.trim() == "plural" else {
raise bad("expected plural assignment")
}
let source = match value.split_once(";") {
Some((expr, rest)) => {
if !rest.trim().is_empty() {
raise bad("unexpected field after plural expression")
}
expr.trim().to_owned()
}
None => value.trim().to_owned()
}
{ nplurals, source, expr: parse_expr(source), }
}