'check pointer size at compile time

I found similar question Compile-time generic type size check, but it not received any answer.

The problem is in cooperation with other programming language via FFI + unsafe, I want to be sure that mem::size_of::<*mut T>() have suitable size. I found such static_assert macro in Internet:

macro_rules! static_assert {
    (type $t:ty; ) => (
        type __StaticAssert = $t;
    );

    (type $t:ty; $e:expr $(, $ee:expr)*) => (
        static_assert!(type ($t, [i8; 0 - ((false == ($e)) as usize)]); $($ee),*);
    );

    ($e:expr $(, $ee:expr)*) => (
        static_assert!(type [i8; 0 - ((false == ($e)) as usize)]; $($ee),*);
    );
}

static_assert!(2 == 2);

it works, but if I use mem::size_of::<*const f64>() inside macro all fails, because of: calls in constants are limited to struct and enum constructors, any idea how to calculate size_of *const f64 at compile time?



Solution 1:[1]

For pointers there is a configuration flag that you can check. You could do this to force a compile-time error:

#[cfg(not(target_pointer_width = "64"))]
compile_error!("Your pointers are too small. Please try again with a more expensive computer.");

In general there is the "transmute trick": to assert the size of something at compile-time, transmute it to something which is known to have the correct size in a dead function. For instance:

#[allow(dead_code)]
fn _assert_pointers_are_64bits() {
    unsafe {
        ::std::mem::transmute::<*const f64, [u8; 8]>(panic!());
    }
}

These tricks will have to do until size_of is made into a const fn.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Colonel Thirty Two