Skip to content

Commit d75a8d2

Browse files
committed
Replace runtime size check with compile time check
Add a macro `const_assert` that uses some const declaration trickery to trigger a compile time error if a boolean expression is false. Replace runtime checks using `debug_assert_eq!` with the newly defined `const_assert!` macro.
1 parent 8525a4e commit d75a8d2

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

src/consensus/encode.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ macro_rules! decoder_fn {
242242
($name:ident, $val_type:ty, $readfn:ident, $byte_len: expr) => {
243243
#[inline]
244244
fn $name(&mut self) -> Result<$val_type, Error> {
245-
debug_assert_eq!(::core::mem::size_of::<$val_type>(), $byte_len); // size_of isn't a constfn in 1.22
245+
const_assert!(::core::mem::size_of::<$val_type>() == $byte_len);
246246
let mut val = [0; $byte_len];
247247
self.read_exact(&mut val[..]).map_err(Error::Io)?;
248248
Ok(endian::$readfn(&val))

src/internal_macros.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -593,3 +593,12 @@ macro_rules! write_err {
593593
}
594594
}
595595
}
596+
597+
/// Asserts a boolean expression at compile time.
598+
macro_rules! const_assert {
599+
($x:expr) => {
600+
{
601+
const _: [(); 0 - !$x as usize] = [];
602+
}
603+
};
604+
}

src/util/endian.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ macro_rules! define_be_to_array {
2828
($name: ident, $type: ty, $byte_len: expr) => {
2929
#[inline]
3030
pub fn $name(val: $type) -> [u8; $byte_len] {
31-
debug_assert_eq!(::core::mem::size_of::<$type>(), $byte_len); // size_of isn't a constfn in 1.22
31+
const_assert!(::core::mem::size_of::<$type>() == $byte_len);
3232
let mut res = [0; $byte_len];
3333
for i in 0..$byte_len {
3434
res[i] = ((val >> ($byte_len - i - 1)*8) & 0xff) as u8;
@@ -41,7 +41,7 @@ macro_rules! define_le_to_array {
4141
($name: ident, $type: ty, $byte_len: expr) => {
4242
#[inline]
4343
pub fn $name(val: $type) -> [u8; $byte_len] {
44-
debug_assert_eq!(::core::mem::size_of::<$type>(), $byte_len); // size_of isn't a constfn in 1.22
44+
const_assert!(::core::mem::size_of::<$type>() == $byte_len);
4545
let mut res = [0; $byte_len];
4646
for i in 0..$byte_len {
4747
res[i] = ((val >> i*8) & 0xff) as u8;

0 commit comments

Comments
 (0)