Skip to content

Commit

Permalink
Add converting codepoints to characters
Browse files Browse the repository at this point in the history
  • Loading branch information
mat-1 committed Jan 15, 2024
1 parent bb43194 commit 5c48b97
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
14 changes: 14 additions & 0 deletions core/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,20 @@ fn evaluate_as<I: Interrupt>(
}
return Err(FendError::ExpectedAString);
}
"char" | "character" => {
let a = evaluate(a, scope, attrs, context, int)?;
if let Value::Num(v) = a {
let n = v.try_as_usize(int)?;
let ch = n
.try_into()
.ok()
.and_then(std::char::from_u32)
.ok_or(FendError::InvalidCodepoint(n))?;

Check warning on line 555 in core/src/ast.rs

View check run for this annotation

Codecov / codecov/patch

core/src/ast.rs#L548-L555

Added lines #L548 - L555 were not covered by tests

return Ok(Value::String(ch.to_string().into()));
}
return Err(FendError::ExpectedANumber);

Check warning on line 559 in core/src/ast.rs

View check run for this annotation

Codecov / codecov/patch

core/src/ast.rs#L557-L559

Added lines #L557 - L559 were not covered by tests
}
_ => (),
}
}
Expand Down
4 changes: 4 additions & 0 deletions core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ pub(crate) enum FendError {
ExpectedACharacter,
StringCannotBeLonger,
StringCannotBeEmpty,
InvalidCodepoint(usize),
ExpectedADigit(char),
ExpectedChar(char, char),
ExpectedDigitSeparator(char),
Expand Down Expand Up @@ -160,6 +161,9 @@ impl fmt::Display for FendError {
Self::ExpectedARealNumber => write!(f, "expected a real number"),
Self::StringCannotBeLonger => write!(f, "string cannot be longer than one codepoint"),
Self::StringCannotBeEmpty => write!(f, "string cannot be empty"),
Self::InvalidCodepoint(codepoint) => {
write!(f, "invalid codepoint: U+{codepoint:04x}")

Check warning on line 165 in core/src/error.rs

View check run for this annotation

Codecov / codecov/patch

core/src/error.rs#L164-L165

Added lines #L164 - L165 were not covered by tests
}
Self::UnableToGetCurrentDate => write!(f, "unable to get the current date"),
Self::NegativeNumbersNotAllowed => write!(f, "negative numbers are not allowed"),
Self::ProbabilityDistributionsNotAllowed => {
Expand Down

0 comments on commit 5c48b97

Please sign in to comment.