Skip to content

Commit

Permalink
Merge pull request #9 from artichoke/lopopolo/const-size-eq
Browse files Browse the repository at this point in the history
Add const assertion that two types have the same size
  • Loading branch information
lopopolo authored Apr 14, 2022
2 parents 479002c + faaf9c2 commit 8cdc9a9
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "qed"
version = "1.0.0"
version = "1.1.0"
authors = ["Ryan Lopopolo <[email protected]>"]
license = "MIT"
edition = "2021"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Add this to your `Cargo.toml`:

```toml
[dependencies]
qed = "1.0.0"
qed = "1.1.0"
```

Then make compile time assertions like:
Expand Down
38 changes: 37 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
//! ```
#![no_std]
#![doc(html_root_url = "https://docs.rs/qed/1.0.0")]
#![doc(html_root_url = "https://docs.rs/qed/1.1.0")]

// Ensure code blocks in README.md compile
#[cfg(all(doctest, any(target_pointer_width = "32", target_pointer_width = "64")))]
Expand Down Expand Up @@ -218,6 +218,32 @@ macro_rules! lossless_cast_u32_to_usize {
}};
}

/// Asserts that two types have the same size at compile time.
///
/// See also [`const_assert!`].
///
/// # Examples
///
/// ```
/// qed::const_assert_size_eq!(u8, i8);
/// qed::const_assert_size_eq!([u32; 4], i128);
/// qed::const_assert_size_eq!(&[u8], &str);
/// ```
///
/// The following fails to compile because the types have different sizes:
///
/// ```compile_fail
/// qed::const_assert_size_eq!(u8, u64);
/// ```
#[macro_export]
macro_rules! const_assert_size_eq {
($left:ty, $right:ty $(,)?) => {
const _: () = {
let _ = ::core::mem::transmute::<$left, $right>;
};
};
}

#[cfg(test)]
mod tests {
use core::num::NonZeroU8;
Expand Down Expand Up @@ -278,4 +304,14 @@ mod tests {
const N: usize = crate::lossless_cast_u32_to_usize!(29_u32);
assert_eq!(N, 29_usize);
}

#[test]
fn size_eq_reference_transmute_no_warnings() {
crate::const_assert_size_eq!(&[u8], &str);
}

#[test]
fn size_eq_pointer_transmute_no_warnings() {
crate::const_assert_size_eq!(*mut u8, *const u8);
}
}

0 comments on commit 8cdc9a9

Please sign in to comment.