Skip to content

Commit

Permalink
Impl PartialOrd for cell builder
Browse files Browse the repository at this point in the history
  • Loading branch information
Rexagon committed Aug 15, 2023
1 parent df2f4ff commit 1c4e3bd
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/cell/builder.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::cmp::Ordering;
use std::mem::MaybeUninit;
use std::rc::Rc;
use std::sync::Arc;
Expand Down Expand Up @@ -196,6 +197,37 @@ impl PartialEq for CellBuilder {
}
}

impl Ord for CellBuilder {
fn cmp(&self, other: &Self) -> Ordering {
match (self.bit_len, self.references.len()).cmp(&(other.bit_len, other.references.len())) {
Ordering::Equal => {}
ord => return ord,
}

// TODO: compare subslices of len {(bits + 7) / 8} ?
match self.data.cmp(&other.data) {
Ordering::Equal => {}
ord => return ord,
}

for (a, b) in self.references().iter().zip(other.references().iter()) {
match a.repr_hash().cmp(b.repr_hash()) {
Ordering::Equal => {}
ord => return ord,
}
}

Ordering::Equal
}
}

impl PartialOrd for CellBuilder {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}

impl std::fmt::Debug for CellBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
#[repr(transparent)]
Expand Down Expand Up @@ -1155,6 +1187,39 @@ mod tests {
assert_ne!(cell1.as_ref(), cell3.as_ref());
}

#[test]
fn compare_builders() {
let mut a = CellBuilder::new();
a.store_u32(0xdeafbeaf).unwrap();

let mut b = CellBuilder::new();
b.store_u32(0xdeafbeaf).unwrap();

assert_eq!(a, b);

b.store_u8(1).unwrap();
assert!(a < b);
a.store_u8(2).unwrap();
assert!(a > b);

a.rewind(8).unwrap();
a.store_u8(1).unwrap();
assert_eq!(a, b);

let child_a = a.clone().build().unwrap();
a.store_reference(child_a.clone()).unwrap();
assert!(a > b);

let child_b = b.clone().build().unwrap();
b.store_reference(child_b).unwrap();
assert_eq!(a, b);

let child_b2 = b.clone().build().unwrap();
a.store_reference(child_a).unwrap();
b.store_reference(child_b2).unwrap();
assert_ne!(a, b);
}

#[test]
fn rewind_builder() {
let mut builder = CellBuilder::new();
Expand Down

0 comments on commit 1c4e3bd

Please sign in to comment.