Skip to content

Commit

Permalink
feat: Implement Eq and PartialEq for EnumTable and EnumMap
Browse files Browse the repository at this point in the history
Positions of keys are always the same, because the underlying
array always has the same layout. Therefore, values can be
compared directly.

GH-13
  • Loading branch information
Pscheidl committed Feb 18, 2024
1 parent f4ff504 commit 953b66e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
30 changes: 29 additions & 1 deletion enum-collections/src/enummap.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
use std::ops::{Deref, Index, IndexMut};

use crate::Enumerated;

Expand Down Expand Up @@ -140,6 +140,23 @@ where
}
}

impl<K, V> PartialEq<Self> for EnumMap<K, V>
where
K: Enumerated,
V: Default + PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.values.deref().eq(other.values.deref())
}
}

impl<K, V> Eq for EnumMap<K, V>
where
K: Enumerated,
V: Default + Eq,
{
}

#[cfg(test)]
mod tests {
use crate::Enumerated;
Expand Down Expand Up @@ -195,4 +212,15 @@ mod tests {
let expected_output = "{A: Some(42), B: None}";
assert_eq!(expected_output, debug_output);
}

#[test]
fn eq() {
let mut first_map = EnumMap::<LetterDebugDerived, i32>::new();
first_map.insert(LetterDebugDerived::A, 42);
let mut second_map = EnumMap::<LetterDebugDerived, i32>::new();
second_map.insert(LetterDebugDerived::A, 42);
assert_eq!(first_map, second_map);
second_map.insert(LetterDebugDerived::B, 0);
debug_assert_ne!(first_map, second_map);
}
}
30 changes: 29 additions & 1 deletion enum-collections/src/enumtable.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
use std::ops::{Deref, Index, IndexMut};

use crate::Enumerated;

Expand Down Expand Up @@ -123,6 +123,23 @@ where
}
}

impl<K, V> PartialEq<Self> for EnumTable<K, V>
where
K: Enumerated,
V: Default + PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.values.deref().eq(other.values.deref())
}
}

impl<K, V> Eq for EnumTable<K, V>
where
K: Enumerated,
V: Default + Eq,
{
}

#[cfg(test)]
mod tests {
use super::EnumTable;
Expand Down Expand Up @@ -188,4 +205,15 @@ mod tests {
let expected_output = "{A: 42, B: 0}";
assert_eq!(expected_output, debug_output);
}

#[test]
fn eq() {
let mut first_table = EnumTable::<LetterDebugDerived, i32>::new();
first_table[LetterDebugDerived::A] = 42;
let mut second_table = EnumTable::<LetterDebugDerived, i32>::new();
second_table[LetterDebugDerived::A] = 42;
assert_eq!(first_table, second_table);
second_table[LetterDebugDerived::B] = 42;
debug_assert_ne!(first_table, second_table);
}
}

0 comments on commit 953b66e

Please sign in to comment.