Skip to content

Commit

Permalink
Merge pull request #154 from artichoke/lopopolo/const-assert-u32-usiz…
Browse files Browse the repository at this point in the history
…e-bits

Refactor u32 to usize cast assertions
  • Loading branch information
lopopolo authored Apr 8, 2022
2 parents aff644c + ca6d997 commit 8e57ab5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
12 changes: 3 additions & 9 deletions src/convert.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use core::convert::TryFrom;
use core::mem::size_of;
use core::num::{NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize};

use crate::{Symbol, SymbolOverflowError};
Expand Down Expand Up @@ -185,9 +184,8 @@ impl From<Symbol> for u64 {
impl From<Symbol> for usize {
#[inline]
fn from(sym: Symbol) -> Self {
// This conversion relies on `size_of::<usize>() >= size_of::<u32>()`,
// which is ensured with a const assertion.
const _: () = [()][!(size_of::<usize>() >= size_of::<u32>()) as usize];
// Ensure this cast is lossless.
const_assert!(usize::BITS >= u32::BITS);

sym.id() as usize
}
Expand Down Expand Up @@ -217,11 +215,7 @@ impl From<&Symbol> for u64 {
impl From<&Symbol> for usize {
#[inline]
fn from(sym: &Symbol) -> Self {
// This conversion relies on `size_of::<usize>() >= size_of::<u32>()`,
// which is ensured with a const assertion.
const _: () = [()][!(size_of::<usize>() >= size_of::<u32>()) as usize];

sym.id() as usize
(*sym).into()
}
}

Expand Down
16 changes: 11 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,19 @@
mod readme {}

use core::fmt;
use core::mem::size_of;
use core::num::TryFromIntError;
use std::error;

macro_rules! const_assert {
($x:expr $(,)?) => {
#[allow(unknown_lints, clippy::eq_op)]
const _: [(); 0 - !{
const ASSERT: bool = $x;
ASSERT
} as usize] = [];
};
}

#[cfg(feature = "bytes")]
#[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
pub mod bytes;
Expand All @@ -132,10 +141,7 @@ pub use crate::str::*;

// To prevent overflows when indexing into the backing `Vec`, `intaglio`
// requires `usize` to be at least as big as `u32`.
//
// This const-evaluated expression will fail to compile if this invariant does
// not hold.
const _: () = [()][!(size_of::<usize>() >= size_of::<u32>()) as usize];
const_assert!(usize::BITS >= u32::BITS);

/// Default capacity for a new [`SymbolTable`] created with
/// [`SymbolTable::new`].
Expand Down

0 comments on commit 8e57ab5

Please sign in to comment.