Skip to content

Commit f7641fc

Browse files
Implement comparison (#38)
* Implement comparison * Derive Debug
1 parent 2bc8ed1 commit f7641fc

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

src/lib.rs

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
#![doc = include_str!("../README.md")]
44

55
use core::mem::MaybeUninit;
6-
use core::{error, fmt, slice};
6+
use core::{cmp, error, fmt, slice};
77

88
/// Error for when the vector is full or the requested operation would need more space than the capacity.
99
///
@@ -20,6 +20,7 @@ impl fmt::Display for CapacityError {
2020

2121
impl error::Error for CapacityError {}
2222

23+
#[derive(Debug)]
2324
/// A stack-allocated vector with fixed capacity and dynamic length.
2425
pub struct Vec<T, const CAPACITY: usize> {
2526
data: [MaybeUninit<T>; CAPACITY],
@@ -714,6 +715,22 @@ impl<T: Clone, const CAPACITY: usize> Clone for Vec<T, CAPACITY> {
714715
}
715716
}
716717

718+
impl<T: PartialEq, const CAPACITY: usize, const OTHER_CAPACITY: usize>
719+
PartialEq<Vec<T, OTHER_CAPACITY>> for Vec<T, CAPACITY>
720+
{
721+
fn eq(&self, other: &Vec<T, OTHER_CAPACITY>) -> bool {
722+
self.len() == other.len() && self.as_slice() == other.as_slice()
723+
}
724+
}
725+
726+
impl<T: PartialOrd, const CAPACITY: usize, const OTHER_CAPACITY: usize>
727+
PartialOrd<Vec<T, OTHER_CAPACITY>> for Vec<T, CAPACITY>
728+
{
729+
fn partial_cmp(&self, other: &Vec<T, OTHER_CAPACITY>) -> Option<cmp::Ordering> {
730+
self.as_slice().partial_cmp(other.as_slice())
731+
}
732+
}
733+
717734
/// Immutable iterator over a [`Vec`].
718735
///
719736
/// Created by calling [`Vec::iter()`].
@@ -1485,6 +1502,43 @@ mod tests {
14851502
assert_eq!(new.as_slice(), elements);
14861503
}
14871504

1505+
#[test]
1506+
fn eq() {
1507+
let mut a = Vec::<i32, 5>::new();
1508+
a.extend_from_slice(&[1, 2, 3]).unwrap();
1509+
1510+
let mut b = Vec::<i32, 10>::new();
1511+
assert_ne!(a, b);
1512+
1513+
b.extend_from_slice(&[1, 2, 3]).unwrap();
1514+
assert_eq!(a, b);
1515+
1516+
b.clear();
1517+
b.extend_from_slice(&[9, 9, 9]).unwrap();
1518+
assert_ne!(a, b);
1519+
}
1520+
1521+
#[test]
1522+
fn cmp() {
1523+
let mut a = Vec::<i32, 5>::new();
1524+
a.extend_from_slice(&[1, 2, 3]).unwrap();
1525+
1526+
let mut b = Vec::<i32, 10>::new();
1527+
assert!(a >= b);
1528+
1529+
b.extend_from_slice(&[1, 2, 3]).unwrap();
1530+
assert!(a >= b);
1531+
assert!(a <= b);
1532+
1533+
b.clear();
1534+
b.extend_from_slice(&[9, 9]).unwrap();
1535+
assert!(a < b);
1536+
1537+
b.clear();
1538+
b.extend_from_slice(&[1, 2]).unwrap();
1539+
assert!(a > b);
1540+
}
1541+
14881542
#[test]
14891543
fn going_out_of_scope_should_drop_all_allocated_elements() {
14901544
let s = Struct { i: 0 };

0 commit comments

Comments
 (0)