Skip to content

Commit 820337e

Browse files
authored
Merge pull request RustPython#2460 from pca006132/range-opt
Optimize builtins/range
2 parents f31eb9f + 3a6d4b7 commit 820337e

1 file changed

Lines changed: 29 additions & 15 deletions

File tree

vm/src/builtins/range.rs

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -78,28 +78,36 @@ impl PyRange {
7878
pub fn get(&self, index: &BigInt) -> Option<BigInt> {
7979
let start = self.start.borrow_value();
8080
let step = self.step.borrow_value();
81-
let index = index.clone();
81+
let stop = self.stop.borrow_value();
8282
if self.is_empty() {
8383
return None;
8484
}
8585

86-
let length = self.length();
87-
88-
let index = if index.is_negative() {
89-
let new_index: BigInt = &length + &index;
90-
if new_index.is_negative() {
86+
if index.is_negative() {
87+
let length = self.length();
88+
let index: BigInt = &length + index;
89+
if index.is_negative() {
9190
return None;
9291
}
93-
length + index
92+
93+
Some(if step.is_one() {
94+
start + index
95+
} else {
96+
start + step * index
97+
})
9498
} else {
95-
if length <= index {
96-
return None;
97-
}
98-
index
99-
};
99+
let index = if step.is_one() {
100+
start + index
101+
} else {
102+
start + step * index
103+
};
100104

101-
let result = start + step * index;
102-
Some(result)
105+
if (step.is_positive() && stop > &index) || (step.is_negative() && stop < &index) {
106+
Some(index)
107+
} else {
108+
None
109+
}
110+
}
103111
}
104112

105113
#[inline]
@@ -109,7 +117,13 @@ impl PyRange {
109117
let step = self.step.borrow_value();
110118

111119
match step.sign() {
112-
Sign::Plus if start < stop => (stop - start - 1usize) / step + 1,
120+
Sign::Plus if start < stop => {
121+
if step.is_one() {
122+
stop - start
123+
} else {
124+
(stop - start - 1usize) / step + 1
125+
}
126+
}
113127
Sign::Minus if start > stop => (start - stop - 1usize) / (-step) + 1,
114128
Sign::Plus | Sign::Minus => BigInt::zero(),
115129
Sign::NoSign => unreachable!(),

0 commit comments

Comments
 (0)