Skip to content

Commit

Permalink
Refint hint feature
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Daniel Lehmann authored and Daniel Lehmann committed Dec 2, 2024
1 parent 680553d commit ce11b3a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
18 changes: 18 additions & 0 deletions .github/workflows/test-hint.yml
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ impl<T: Copy, const BITS: usize> UInt<T, BITS> {
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
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit ce11b3a

Please sign in to comment.