Skip to content

Commit

Permalink
Merge pull request #7166 from svcxc/rocdec-traits
Browse files Browse the repository at this point in the history
Implement Default/PartialOrd/Ord for RocDec
  • Loading branch information
ayazhafiz authored Oct 14, 2024
2 parents 01aa260 + b7ec1f1 commit f8a6d89
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
14 changes: 13 additions & 1 deletion crates/roc_std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ impl<T, E> Drop for RocResult<T, E> {
}
}

#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Default)]
#[repr(C, align(16))]
pub struct RocDec([u8; 16]);

Expand Down Expand Up @@ -477,6 +477,18 @@ impl fmt::Display for RocDec {
}
}

impl PartialOrd for RocDec {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}

impl Ord for RocDec {
fn cmp(&self, other: &Self) -> Ordering {
self.as_i128().cmp(&other.as_i128())
}
}

#[repr(C, align(16))]
#[derive(Clone, Copy, Eq, Default)]
pub struct I128([u8; 16]);
Expand Down
29 changes: 29 additions & 0 deletions crates/roc_std/tests/test_roc_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,35 @@ mod test_roc_std {
assert_eq!(format!("{example}"), "3.141592653589793238");
}

#[test]
fn roc_dec_sort() {
let neg_one_point_five = RocDec::from_str("-1.5").unwrap();

let mut sorted_by_ord = [
neg_one_point_five,
RocDec::from(35),
RocDec::from(-10057),
RocDec::from(0),
];

sorted_by_ord.sort();

let manually_sorted = [
RocDec::from(-10057),
neg_one_point_five,
RocDec::from(0),
RocDec::from(35),
];

assert_eq!(sorted_by_ord, manually_sorted);
}

#[test]
fn roc_dec_default() {
// check if derived Default still returns zero if the implementation ever changes
assert_eq!(RocDec::from(0), RocDec::default());
}

#[test]
fn safe_send_no_copy() {
let x = RocStr::from("This is a long string but still unique. Yay!!!");
Expand Down

0 comments on commit f8a6d89

Please sign in to comment.