Skip to content

Commit ad02510

Browse files
committed
libcore: Implement a memory-safe "each_val" for data in aliasable, mutable locations
1 parent 0c2e6fd commit ad02510

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

src/libcore/core.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ pub use vec::{ConstVector, CopyableVector, ImmutableVector};
1717
pub use vec::{ImmutableEqVector, ImmutableCopyableVector};
1818
pub use vec::{MutableVector, MutableCopyableVector};
1919
pub use iter::{BaseIter, ExtendedIter, EqIter, CopyableIter};
20-
pub use iter::{CopyableOrderedIter, Times};
20+
pub use iter::{CopyableOrderedIter, CopyableNonstrictIter, Times};
2121
pub use num::Num;
2222
pub use ptr::Ptr;
2323
pub use to_str::ToStr;

src/libcore/iter.rs

+7
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,13 @@ pub trait CopyableOrderedIter<A:Copy Ord> {
4646
pure fn max() -> A;
4747
}
4848

49+
pub trait CopyableNonstrictIter<A:Copy> {
50+
// Like "each", but copies out the value. If the receiver is mutated while
51+
// iterating over it, the semantics must not be memory-unsafe but are
52+
// otherwise undefined.
53+
pure fn each_val(&const self, f: &fn(A) -> bool);
54+
}
55+
4956
// A trait for sequences that can be by imperatively pushing elements
5057
// onto them.
5158
pub trait Buildable<A> {

src/libcore/vec.rs

+31
Original file line numberDiff line numberDiff line change
@@ -2020,6 +2020,37 @@ impl<A: Copy Ord> &[A]: iter::CopyableOrderedIter<A> {
20202020
pure fn min() -> A { iter::min(&self) }
20212021
pure fn max() -> A { iter::max(&self) }
20222022
}
2023+
2024+
impl<A:Copy> &[A] : iter::CopyableNonstrictIter<A> {
2025+
pure fn each_val(&const self, f: fn(A) -> bool) {
2026+
let mut i = 0;
2027+
while i < self.len() {
2028+
if !f(copy self[i]) { break; }
2029+
i += 1;
2030+
}
2031+
}
2032+
}
2033+
2034+
impl<A:Copy> ~[A] : iter::CopyableNonstrictIter<A> {
2035+
pure fn each_val(&const self, f: fn(A) -> bool) {
2036+
let mut i = 0;
2037+
while i < self.len() {
2038+
if !f(copy self[i]) { break; }
2039+
i += 1;
2040+
}
2041+
}
2042+
}
2043+
2044+
impl<A:Copy> @[A] : iter::CopyableNonstrictIter<A> {
2045+
pure fn each_val(&const self, f: fn(A) -> bool) {
2046+
let mut i = 0;
2047+
while i < self.len() {
2048+
if !f(copy self[i]) { break; }
2049+
i += 1;
2050+
}
2051+
}
2052+
}
2053+
20232054
// ___________________________________________________________________________
20242055

20252056
#[cfg(test)]

0 commit comments

Comments
 (0)