Skip to content

Commit 0e5a0e1

Browse files
committed
libcore: Implement equality and ordering on vectors
1 parent 88e0476 commit 0e5a0e1

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

src/libcore/vec.rs

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Vectors
22
3+
import cmp::{Eq, Ord};
34
import option::{Some, None};
45
import ptr::addr_of;
56
import libc::size_t;
@@ -1374,6 +1375,80 @@ pure fn as_mut_buf<T,U>(s: &[mut T],
13741375
}
13751376
}
13761377

1378+
// Equality
1379+
1380+
pure fn eq<T: Eq>(a: &[T], b: &[T]) -> bool {
1381+
let (a_len, b_len) = (a.len(), b.len());
1382+
if a_len != b_len { return false; }
1383+
1384+
let mut i = 0;
1385+
while i < a_len {
1386+
if a[i] != b[i] { return false; }
1387+
i += 1;
1388+
}
1389+
1390+
return true;
1391+
}
1392+
1393+
impl<T: Eq> &[T]: Eq {
1394+
#[inline(always)]
1395+
pure fn eq(&&other: &[T]) -> bool {
1396+
eq(self, other)
1397+
}
1398+
}
1399+
1400+
impl<T: Eq> ~[T]: Eq {
1401+
#[inline(always)]
1402+
pure fn eq(&&other: ~[T]) -> bool {
1403+
eq(self, other)
1404+
}
1405+
}
1406+
1407+
impl<T: Eq> @[T]: Eq {
1408+
#[inline(always)]
1409+
pure fn eq(&&other: @[T]) -> bool {
1410+
eq(self, other)
1411+
}
1412+
}
1413+
1414+
// Lexicographical comparison
1415+
1416+
pure fn lt<T: Ord>(a: &[T], b: &[T]) -> bool {
1417+
let (a_len, b_len) = (a.len(), b.len());
1418+
let mut end = uint::min(a_len, b_len);
1419+
1420+
let mut i = 0;
1421+
while i < end {
1422+
let (c_a, c_b) = (&a[i], &b[i]);
1423+
if *c_a < *c_b { return true; }
1424+
if *c_a > *c_b { return false; }
1425+
i += 1;
1426+
}
1427+
1428+
return a_len < b_len;
1429+
}
1430+
1431+
impl<T: Ord> &[T]: Ord {
1432+
#[inline(always)]
1433+
pure fn lt(&&other: &[T]) -> bool {
1434+
lt(self, other)
1435+
}
1436+
}
1437+
1438+
impl<T: Ord> ~[T]: Ord {
1439+
#[inline(always)]
1440+
pure fn lt(&&other: ~[T]) -> bool {
1441+
lt(self, other)
1442+
}
1443+
}
1444+
1445+
impl<T: Ord> @[T]: Ord {
1446+
#[inline(always)]
1447+
pure fn lt(&&other: @[T]) -> bool {
1448+
lt(self, other)
1449+
}
1450+
}
1451+
13771452
#[cfg(notest)]
13781453
impl<T: copy> ~[T]: add<&[const T],~[T]> {
13791454
#[inline(always)]

0 commit comments

Comments
 (0)