| Crates.io | cast_checks |
| lib.rs | cast_checks |
| version | 0.1.6 |
| created_at | 2023-03-24 15:23:20.477751+00 |
| updated_at | 2025-04-20 22:40:14.96635+00 |
| description | A procedural macro to check for invalid casts |
| homepage | |
| repository | https://github.com/trailofbits/cast_checks |
| max_upload_size | |
| id | 819365 |
| size | 24,533 |
cast_checksA procedural macro to check for invalid casts
Like -C overflow-checks, cast_checks is enabled only for debug builds by default. To enable cast_checks for release builds, set the crate-level release feature.
cast_checks::enable essentially rewrites each expression of the form:
expr as T
to an expression involving try_into:
<_ as TryInto::< T >>::try_into( expr ).expect("invalid cast")
So when an invalid cast occurs, a message like the following results:
thread 'checked_truncation' panicked at 'invalid cast: TryFromIntError(())', cast_checks/tests/basic.rs:30:13
We say "essentially rewrites" because the actual generated code is slightly more complex. It uses Nikolai Vazquez's impls' trick to determine whether an appropriate TryInto implementation exists.
You must use cast_checks::enable as an outer attribute. Example:
#[cast_checks::enable]
fn as_u16(x: u64) -> u16 {
x as u16
}
We recommend enabling Rust features custom_inner_attributes and proc_macro_hygiene.
If you enable the custom_inner_attributes and proc_macro_hygiene features, you can use cast_checks::enable as an inner attribute. Example:
#![feature(custom_inner_attributes, proc_macro_hygiene)]
mod m {
#![cast_checks::enable]
/* items */
}
CAST_CHECKS_LOGIf you are concerned that some casts are not being checked, try setting CAST_CHECKS_LOG and passing the procmacro2_semver_exempt config flag when compiling, e.g.:
CAST_CHECKS_LOG=1 RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build
This will cause cast_checks to dump to standard output:
Example:
cast_checks rewriting `x as u16` at src/lib.rs:3:0
cast_checks not descending into `mod c ;` at src/lib.rs:3:0
Note that CAST_CHECKS_LOG requires --cfg procmacro2_semver_exempt to be passed to rustc.