Merge pull request #226 from bbqsrc/master

Add PartialOrd and Ord to Vec and String
This commit is contained in:
Emil Fresk 2021-08-05 09:20:14 +02:00 committed by GitHub
commit d1b53baaba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 77 additions and 2 deletions

View File

@ -1,4 +1,4 @@
use core::{fmt, fmt::Write, hash, ops, str};
use core::{cmp::Ordering, fmt, fmt::Write, hash, ops, str};
use hash32;
@ -439,6 +439,20 @@ impl<const N: usize> PartialEq<String<N>> for &str {
impl<const N: usize> Eq for String<N> {}
impl<const N1: usize, const N2: usize> PartialOrd<String<N2>> for String<N1> {
#[inline]
fn partial_cmp(&self, other: &String<N2>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
}
impl<const N: usize> Ord for String<N> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
macro_rules! impl_from_num {
($num:ty, $size:expr) => {
impl<const N: usize> From<$num> for String<N> {
@ -480,6 +494,22 @@ mod tests {
assert_eq!(s2, "abcd efgh");
}
#[test]
fn cmp() {
let s1: String<4> = String::from("abcd");
let s2: String<4> = String::from("zzzz");
assert!(s1 < s2);
}
#[test]
fn cmp_heterogenous_size() {
let s1: String<4> = String::from("abcd");
let s2: String<8> = String::from("zzzz");
assert!(s1 < s2);
}
#[test]
fn debug() {
use core::fmt::Write;

View File

@ -1,4 +1,4 @@
use core::{fmt, hash, iter::FromIterator, mem::MaybeUninit, ops, ptr, slice};
use core::{cmp::Ordering, fmt, hash, iter::FromIterator, mem::MaybeUninit, ops, ptr, slice};
use hash32;
/// A fixed capacity [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html)
@ -764,6 +764,25 @@ where
// Implements Eq if underlying data is Eq
impl<T, const N: usize> Eq for Vec<T, N> where T: Eq {}
impl<T, const N1: usize, const N2: usize> PartialOrd<Vec<T, N2>> for Vec<T, N1>
where
T: PartialOrd,
{
fn partial_cmp(&self, other: &Vec<T, N2>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
}
impl<T, const N: usize> Ord for Vec<T, N>
where
T: Ord,
{
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
impl<T, const N: usize> ops::Deref for Vec<T, N> {
type Target = [T];
@ -888,6 +907,32 @@ mod tests {
assert_eq!(xs, ys);
}
#[test]
fn cmp() {
let mut xs: Vec<i32, 4> = Vec::new();
let mut ys: Vec<i32, 4> = Vec::new();
assert_eq!(xs, ys);
xs.push(1).unwrap();
ys.push(2).unwrap();
assert!(xs < ys);
}
#[test]
fn cmp_heterogenous_size() {
let mut xs: Vec<i32, 4> = Vec::new();
let mut ys: Vec<i32, 8> = Vec::new();
assert_eq!(xs, ys);
xs.push(1).unwrap();
ys.push(2).unwrap();
assert!(xs < ys);
}
#[test]
fn full() {
let mut v: Vec<i32, 4> = Vec::new();