From 0e5a0e1da54f385c1ac623bb7cfe6cf19fcde8f8 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Mon, 27 Aug 2012 17:15:54 -0700 Subject: [PATCH] libcore: Implement equality and ordering on vectors --- src/libcore/vec.rs | 75 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index 01d4cf61067a..bd3634c29abc 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -1,5 +1,6 @@ //! Vectors +import cmp::{Eq, Ord}; import option::{Some, None}; import ptr::addr_of; import libc::size_t; @@ -1374,6 +1375,80 @@ pure fn as_mut_buf(s: &[mut T], } } +// Equality + +pure fn eq(a: &[T], b: &[T]) -> bool { + let (a_len, b_len) = (a.len(), b.len()); + if a_len != b_len { return false; } + + let mut i = 0; + while i < a_len { + if a[i] != b[i] { return false; } + i += 1; + } + + return true; +} + +impl &[T]: Eq { + #[inline(always)] + pure fn eq(&&other: &[T]) -> bool { + eq(self, other) + } +} + +impl ~[T]: Eq { + #[inline(always)] + pure fn eq(&&other: ~[T]) -> bool { + eq(self, other) + } +} + +impl @[T]: Eq { + #[inline(always)] + pure fn eq(&&other: @[T]) -> bool { + eq(self, other) + } +} + +// Lexicographical comparison + +pure fn lt(a: &[T], b: &[T]) -> bool { + let (a_len, b_len) = (a.len(), b.len()); + let mut end = uint::min(a_len, b_len); + + let mut i = 0; + while i < end { + let (c_a, c_b) = (&a[i], &b[i]); + if *c_a < *c_b { return true; } + if *c_a > *c_b { return false; } + i += 1; + } + + return a_len < b_len; +} + +impl &[T]: Ord { + #[inline(always)] + pure fn lt(&&other: &[T]) -> bool { + lt(self, other) + } +} + +impl ~[T]: Ord { + #[inline(always)] + pure fn lt(&&other: ~[T]) -> bool { + lt(self, other) + } +} + +impl @[T]: Ord { + #[inline(always)] + pure fn lt(&&other: @[T]) -> bool { + lt(self, other) + } +} + #[cfg(notest)] impl ~[T]: add<&[const T],~[T]> { #[inline(always)]