From 4f7c8cb965c046edbc9cb6a88d06e42f75358201 Mon Sep 17 00:00:00 2001 From: Behrad Deylami Date: Fri, 22 Sep 2023 15:30:17 +0300 Subject: [PATCH] feat: Enhance Bound Enum with Utility Methods and Refactor Storable Trait (#142) ### Description: This PR introduces utility methods to the `Bound` enum, enhancing its functionality and usability. These methods are used to refactor the `Storable` trait, making it cleaner and more maintainable. #### Use-Case: I am developing a library aimed at simplifying the use of stable memory structures. For example, consider a `TaskTimerEntry` struct defined as: ```rust pub struct TaskTimerEntry { pub time: NanoTimeStamp, pub task: T, } ``` To make this struct bounded, I can now easily specify: ```rust const BOUND: Bound = Bound::Bounded { is_fixed_size: false, max_size: 8 + T::BOUND.max_size(), }; ``` #### Key Changes: Introduced `max_size` and `is_fixed_size` methods to `Bound` enum. #### Impact on `Storable` Trait: The utility methods have been integrated into the `Storable` trait, enhancing its readability and maintainability without altering its core functionality. #### Types of Changes: - [x] New feature (non-breaking change which adds functionality) - [ ] Bugfix (non-breaking change which fixes an issue) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] Documentation Update (if none of the other choices apply) --- src/storable.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/storable.rs b/src/storable.rs index edbd3f12..228b20be 100644 --- a/src/storable.rs +++ b/src/storable.rs @@ -70,6 +70,26 @@ pub enum Bound { }, } +impl Bound { + /// Returns the maximum size of the type if bounded, panics if unbounded. + pub const fn max_size(&self) -> u32 { + if let Bound::Bounded { max_size, .. } = self { + *max_size + } else { + panic!("Cannot get max size of unbounded type."); + } + } + + /// Returns true if the type is fixed in size, false otherwise. + pub const fn is_fixed_size(&self) -> bool { + if let Bound::Bounded { is_fixed_size, .. } = self { + *is_fixed_size + } else { + false + } + } +} + /// Variable-size, but limited in capacity byte array. #[derive(Eq, Copy, Clone)] pub struct Blob {