From 9531aa12778593cfec0a20832f50f0860c2fa4e1 Mon Sep 17 00:00:00 2001 From: Qishen Zhang Date: Sun, 24 May 2020 15:40:33 -0500 Subject: [PATCH] Add serde derive for wrappers and create a new wrapper that combines two wrappers. --- src/hashable.rs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/hashable.rs b/src/hashable.rs index 2b0279e013..4db7927c85 100644 --- a/src/hashable.rs +++ b/src/hashable.rs @@ -91,10 +91,29 @@ impl Abomonation for UnsignedWrapper { } } +/// A wrapper for people who don't have time to write nested wrapper. +/// Wrap up an item of some type that implements `Ord` and `Hashable` traits. +pub type OrdHashableWrapper = OrdWrapper>; + +impl OrdHashableWrapper { + /// A simple method to avoid writing `a = item.into()` then `b = a.into()`. + pub fn new(item: T) -> Self { + let hashable_item: HashableWrapper = item.into(); + OrdWrapper { item: hashable_item } + } +} + +impl From for OrdHashableWrapper { + #[inline] + fn from(item: T) -> Self { + let hashable_wrapper: HashableWrapper = item.into(); + OrdWrapper { item: hashable_wrapper } + } +} /// A wrapper around hashable types that ensures an implementation of `Ord` that compares /// hash values first. -#[derive(Clone, Eq, PartialEq, Debug, Default)] +#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)] pub struct OrdWrapper { /// The item, so you can grab it. pub item: T @@ -106,6 +125,7 @@ impl PartialOrd for OrdWrapper { (self.item.hashed(), &self.item).partial_cmp(&(other.item.hashed(), &other.item)) } } + impl Ord for OrdWrapper { #[inline] fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { @@ -125,7 +145,7 @@ impl Deref for OrdWrapper { /// Wrapper to stash hash value with the actual value. -#[derive(Clone, Default, Ord, PartialOrd, Eq, PartialEq, Debug, Copy)] +#[derive(Clone, Default, Ord, PartialOrd, Eq, PartialEq, Debug, Copy, Serialize, Deserialize)] pub struct HashableWrapper { hash: T::Output, /// The item, for reference. @@ -155,7 +175,7 @@ impl From for HashableWrapper { } /// A wrapper around an unsigned integer, providing `hashed` as the value itself. -#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Default, Debug, Copy)] +#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Default, Debug, Copy, Serialize, Deserialize)] pub struct UnsignedWrapper { /// The item. pub item: T,