From ce11b3a2347000854604c274d5ffc8e126bc20ea Mon Sep 17 00:00:00 2001 From: Daniel Lehmann Date: Mon, 2 Dec 2024 11:24:43 -0800 Subject: [PATCH] Refint hint feature Most importantly, this now applies hint to `const fn value()`, which is probably the most common way to access it. Also adds integration tests for the feature. --- .github/workflows/test-hint.yml | 18 ++++++++++++++++++ Cargo.toml | 2 +- src/lib.rs | 16 ++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/test-hint.yml diff --git a/.github/workflows/test-hint.yml b/.github/workflows/test-hint.yml new file mode 100644 index 0000000..0ee8731 --- /dev/null +++ b/.github/workflows/test-hint.yml @@ -0,0 +1,18 @@ +name: test release +run-name: ${{ github.actor }}'s patch +on: [push] +jobs: + build-and-test: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: '14' + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + - uses: actions-rs/cargo@v1 + with: + command: test + args: --no-default-features --features hint \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 68d0183..96c397d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ borsh = ["dep:borsh"] schemars = ["dep:schemars", "std"] # Provide a soundness promixe to the compiler that the unerlying value is always within range -# This optimizes e.g. indexing range checks when passed in an API +# This optimizes e.g. indexing range checks when passed in an API. hint = [] [dependencies] diff --git a/src/lib.rs b/src/lib.rs index 300b8ca..c3fb502 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -129,6 +129,7 @@ impl UInt { pub const BITS: usize = BITS; /// Returns the type as a fundamental data type + #[cfg(not(feature = "hint"))] #[inline] pub const fn value(self) -> T { self.value @@ -271,6 +272,21 @@ macro_rules! uint_impl { } } + /// Returns the type as a fundamental data type + #[cfg(feature = "hint")] + #[inline] + pub const fn value(self) -> $type { + // The hint feature requires the type to be const-comparable, + // which isn't possible in the generic version above. So we have + // an entirely different function if this feature is enabled. + // It only works for primitive types, which should be ok in practice + // (but is technically an API change) + unsafe { + core::hint::assert_unchecked(self.value <= Self::MAX.value); + } + self.value + } + #[deprecated(note = "Use one of the specific functions like extract_u32")] pub const fn extract(value: $type, start_bit: usize) -> Self { assert!(start_bit + BITS <= $type::BITS as usize);