chiark / gitweb /
Implement Add, via BitXor on the underlying type.
authorSimon Tatham <anakin@pobox.com>
Thu, 10 Apr 2025 11:37:10 +0000 (12:37 +0100)
committerSimon Tatham <anakin@pobox.com>
Thu, 10 Apr 2025 11:37:10 +0000 (12:37 +0100)
src/finitenimber.rs
src/lib.rs

index 1ffd3a4909a5c7b3e3608adab043408290d660c3..9b544f6d0fcbcd24d1a7211c039be3e72841d091 100644 (file)
@@ -1,7 +1,32 @@
-pub trait FiniteNimberBaseInteger : std::ops::BitXor + Sized {
-    type Owned;
+use std::fmt::Debug;
+
+pub trait FiniteNimberBase : std::ops::BitXor<Output=Self> + Clone + Eq + Debug + Sized {
+    type Owned: FiniteNimberBase;
+
+    fn to_owned(self) -> Self::Owned;
+}
+
+impl FiniteNimberBase for u64 {
+    type Owned = Self;
+
+    fn to_owned(self) -> Self::Owned {self}
 }
 
-pub struct FiniteNimber<T: FiniteNimberBaseInteger> {
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct FiniteNimber<T: FiniteNimberBase> {
     n: T,
 }
+
+impl<T: FiniteNimberBase> FiniteNimber<T> {
+    pub fn new(n: T) -> Self {
+        Self { n }
+    }
+}
+
+impl<T: FiniteNimberBase> std::ops::Add<FiniteNimber<T>> for FiniteNimber<T> {
+    type Output = FiniteNimber<T::Owned>;
+
+    fn add(self, other: Self) -> Self::Output {
+        Self::Output::new((self.n ^ other.n).to_owned())
+    }
+}
index bc692dc1f8f71faa90e5998ce3e2ef53bd98e965..dcc764dd3227b51ffd7fe7b0cb314d8c8660d6ad 100644 (file)
@@ -1,3 +1,15 @@
 mod finitenimber;
 
 pub use finitenimber::FiniteNimber;
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn addition() {
+        let a = FiniteNimber::new(0b1100u64);
+        let b = FiniteNimber::new(0b1010u64);
+        assert_eq!(a + b, FiniteNimber::new(0b0110u64));
+    }
+}