Skip to content

Implement comparison #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 26, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 51 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#![doc = include_str!("../README.md")]

use core::mem::MaybeUninit;
use core::{error, fmt, slice};
use core::{cmp, error, fmt, slice};

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

impl error::Error for CapacityError {}

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

impl<T: PartialEq, const CAPACITY: usize, const OTHER_CAPACITY: usize>
PartialEq<Vec<T, OTHER_CAPACITY>> for Vec<T, CAPACITY>
{
fn eq(&self, other: &Vec<T, OTHER_CAPACITY>) -> bool {
if self.len() == other.len() { self.as_slice() == other.as_slice() } else { false }
}
}

impl<T: PartialOrd, const CAPACITY: usize, const OTHER_CAPACITY: usize>
PartialOrd<Vec<T, OTHER_CAPACITY>> for Vec<T, CAPACITY>
{
fn partial_cmp(&self, other: &Vec<T, OTHER_CAPACITY>) -> Option<cmp::Ordering> {
self.as_slice().partial_cmp(other.as_slice())
}
}

/// Immutable iterator over a [`Vec`].
///
/// Created by calling [`Vec::iter()`].
Expand Down Expand Up @@ -1485,6 +1502,39 @@ mod tests {
assert_eq!(new.as_slice(), elements);
}

#[test]
fn eq() {
let mut a = Vec::<i32, 5>::new();
a.extend_from_slice(&[1, 2, 3]).unwrap();

let mut b = Vec::<i32, 10>::new();
assert_ne!(a, b);

b.extend_from_slice(&[1, 2, 3]).unwrap();
assert_eq!(a, b);

b.clear();
b.extend_from_slice(&[9, 9, 9]).unwrap();
assert_ne!(a, b);
}

#[test]
fn cmp() {
let mut a = Vec::<i32, 5>::new();
a.extend_from_slice(&[1, 2, 3]).unwrap();

let mut b = Vec::<i32, 10>::new();
assert!(a >= b);

b.extend_from_slice(&[1, 2, 3]).unwrap();
assert!(a >= b);
assert!(a <= b);

b.clear();
b.extend_from_slice(&[9, 9]).unwrap();
assert!(a < b);
}

#[test]
fn going_out_of_scope_should_drop_all_allocated_elements() {
let s = Struct { i: 0 };
Expand Down