Skip to content

Commit b57864a

Browse files
Merge pull request #2 from codedstructure/integer_division
added integer division
2 parents 501e509 + a81fee8 commit b57864a

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
- Added: integer division with `//`.
11+
1012
- Added: support for text style and colour classes in `<tspan>` elements.
1113

1214
- Fixed: position and attribute expansion for non-empty graphics elements,

src/expr/expression.rs

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,8 @@ enum Token {
325325
Mul,
326326
/// A literal '/' for division
327327
Div,
328+
/// A literal '//' for integer division
329+
IntDiv,
328330
/// A literal '%' for mod operation
329331
Mod,
330332
/// Internal-only token used for separating otherwise
@@ -426,7 +428,14 @@ fn tokenize(input: &str) -> Result<Vec<Token>> {
426428
'+' => Token::Add,
427429
'-' if !in_elref_id => Token::Sub, // '-' is valid in an ElRef::Id
428430
'*' => Token::Mul,
429-
'/' => Token::Div,
431+
'/' => {
432+
if buffer.is_empty() && tokens.last() == Some(&Token::Div) {
433+
tokens.pop();
434+
Token::IntDiv
435+
} else {
436+
Token::Div
437+
}
438+
}
430439
'%' => Token::Mod,
431440
',' => Token::Comma,
432441
' ' | '\t' => Token::Whitespace,
@@ -724,6 +733,10 @@ fn factor(eval_state: &mut EvalState) -> Result<ExprValue> {
724733
eval_state.advance();
725734
e /= primary(eval_state)?.one_number()?;
726735
}
736+
Some(Token::IntDiv) => {
737+
eval_state.advance();
738+
e = e.div_euclid(primary(eval_state)?.one_number()?);
739+
}
727740
Some(Token::Mod) => {
728741
eval_state.advance();
729742
// note euclid remainder rather than '%' operator
@@ -1060,6 +1073,8 @@ mod tests {
10601073
("6 - 9", -3.),
10611074
("-4 * 5", -20.),
10621075
("60 / 12", 5.),
1076+
("11 // 4", 2.),
1077+
("-11 // 4", -3.), // ensure -a // b is rounds down
10631078
("63 % 4", 3.),
10641079
("-1 % 4", 3.), // ensure -a % b is non-negative
10651080
("-4 * 4", -16.),
@@ -1673,8 +1688,8 @@ mod tests {
16731688
let ctx = TestContext::new();
16741689
for (expr, expected) in [
16751690
(
1676-
"{{10, 20 + 3, 2+3 , eq(123, 123), 5/2}}",
1677-
"10, 23, 5, 1, 2.5",
1691+
"{{10, 20 + 3, 2+3 , eq(123, 123), 5/2, 3//2}}",
1692+
"10, 23, 5, 1, 2.5, 1",
16781693
),
16791694
("{{3, 2, swap(1, 2)}}", "3, 2, 2, 1"),
16801695
("{{p2r(10, 0)}}", "10, 0"),

0 commit comments

Comments
 (0)