Skip to content

Commit 44c5554

Browse files
committed
Add explanation why Add::add() is called directly instead of + in the Enumerate implementation
1 parent 708e9bf commit 44c5554

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

library/core/src/iter/adapters/enumerate.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,10 @@ where
6969
default fn next(&mut self) -> Option<Self::Item> {
7070
let a = self.iter.next()?;
7171
let i = self.count;
72-
// Possible undefined overflow.
72+
// Possible undefined overflow. By directly calling the trait method instead of using the
73+
// `+=` operator the decision about overflow checking is delayed to the crate that does code
74+
// generation, even if overflow checks are disabled for the current crate. This is
75+
// especially useful because overflow checks are usually disabled for the standard library.
7376
AddAssign::add_assign(&mut self.count, 1);
7477
Some((i, a))
7578
}
@@ -82,6 +85,7 @@ where
8285
// SAFETY: the caller must uphold the contract for
8386
// `Iterator::__iterator_get_unchecked`.
8487
let value = unsafe { try_get_unchecked(&mut self.iter, idx) };
88+
// See comment in `next()` for the reason why `Add::add()` is used here instead of `+`.
8589
(Add::add(self.count, idx), value)
8690
}
8791

@@ -123,7 +127,8 @@ where
123127
intrinsics::assume(self.count < self.len);
124128
}
125129
let i = self.count;
126-
// Possible undefined overflow.
130+
// See comment in `next()` of the default implementation for the reason why
131+
// `AddAssign::add_assign()` is used here instead of `+=`.
127132
AddAssign::add_assign(&mut self.count, 1);
128133
Some((i, a))
129134
}
@@ -136,6 +141,7 @@ where
136141
// SAFETY: the caller must uphold the contract for
137142
// `Iterator::__iterator_get_unchecked`.
138143
let value = unsafe { try_get_unchecked(&mut self.iter, idx) };
144+
// See comment in `next()` for the reason why `Add::add()` is used here instead of `+`.
139145
let idx = Add::add(self.count, idx);
140146
// SAFETY: There must be fewer than `self.len` items because of `TrustedLen`'s API contract
141147
unsafe {

0 commit comments

Comments
 (0)