Skip to content

Commit b43c511

Browse files
committed
fix range len() for negative and non-divisible steps
1 parent 7941480 commit b43c511

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

vm/src/obj/objrange.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use super::super::pyobject::{
44
use super::super::vm::VirtualMachine;
55
use super::objint;
66
use super::objtype;
7-
use num_bigint::{BigInt, ToBigInt};
7+
use num_bigint::{BigInt, ToBigInt, Sign};
88
use num_traits::{One, Signed, ToPrimitive, Zero};
99

1010
#[derive(Debug, Clone)]
@@ -19,10 +19,13 @@ pub struct RangeType {
1919
impl RangeType {
2020
#[inline]
2121
pub fn len(&self) -> usize {
22-
((self.end.clone() - self.start.clone()) / self.step.clone())
23-
.abs()
24-
.to_usize()
25-
.unwrap()
22+
match self.step.sign() {
23+
Sign::Plus if self.start < self.end =>
24+
((&self.end - &self.start - 1usize) / &self.step).to_usize().unwrap() + 1,
25+
Sign::Minus if self.start > self.end =>
26+
((&self.start - &self.end - 1usize) / (-&self.step)).to_usize().unwrap() + 1,
27+
_ => 0,
28+
}
2629
}
2730

2831
#[inline]

0 commit comments

Comments
 (0)