rust/src/test/run-pass/structs-enums/enum-null-pointer-opt.rs

65 lines
2.5 KiB
Rust
Raw Normal View History

// run-pass
2014-07-04 21:54:23 +00:00
use std::mem::size_of;
use std::num::NonZeroUsize;
use std::ptr::NonNull;
2014-12-05 19:52:38 +00:00
use std::rc::Rc;
use std::sync::Arc;
2014-07-04 21:54:23 +00:00
trait Trait { fn dummy(&self) { } }
trait Mirror { type Image; }
impl<T> Mirror for T { type Image = T; }
struct ParamTypeStruct<T>(T);
struct AssocTypeStruct<T>(<T as Mirror>::Image);
2014-07-04 21:54:23 +00:00
fn main() {
// Functions
assert_eq!(size_of::<fn(isize)>(), size_of::<Option<fn(isize)>>());
assert_eq!(size_of::<extern "C" fn(isize)>(), size_of::<Option<extern "C" fn(isize)>>());
2014-07-04 21:54:23 +00:00
// Slices - &str / &[T] / &mut [T]
assert_eq!(size_of::<&str>(), size_of::<Option<&str>>());
assert_eq!(size_of::<&[isize]>(), size_of::<Option<&[isize]>>());
assert_eq!(size_of::<&mut [isize]>(), size_of::<Option<&mut [isize]>>());
2014-07-04 21:54:23 +00:00
// Traits - Box<Trait> / &Trait / &mut Trait
assert_eq!(size_of::<Box<Trait>>(), size_of::<Option<Box<Trait>>>());
assert_eq!(size_of::<&Trait>(), size_of::<Option<&Trait>>());
assert_eq!(size_of::<&mut Trait>(), size_of::<Option<&mut Trait>>());
2014-10-02 05:10:09 +00:00
// Pointers - Box<T>
assert_eq!(size_of::<Box<isize>>(), size_of::<Option<Box<isize>>>());
2014-07-04 21:54:23 +00:00
// The optimization can't apply to raw pointers
assert!(size_of::<Option<*const isize>>() != size_of::<*const isize>());
assert!(Some(0 as *const isize).is_some()); // Can't collapse None to null
2014-12-05 19:41:28 +00:00
struct Foo {
_a: Box<isize>
2014-12-05 19:41:28 +00:00
}
struct Bar(Box<isize>);
2014-12-05 19:41:28 +00:00
// Should apply through structs
assert_eq!(size_of::<Foo>(), size_of::<Option<Foo>>());
assert_eq!(size_of::<Bar>(), size_of::<Option<Bar>>());
// and tuples
assert_eq!(size_of::<(u8, Box<isize>)>(), size_of::<Option<(u8, Box<isize>)>>());
2014-12-05 19:41:28 +00:00
// and fixed-size arrays
assert_eq!(size_of::<[Box<isize>; 1]>(), size_of::<Option<[Box<isize>; 1]>>());
2014-12-05 19:41:28 +00:00
2014-12-05 19:52:38 +00:00
// Should apply to NonZero
assert_eq!(size_of::<NonZeroUsize>(), size_of::<Option<NonZeroUsize>>());
assert_eq!(size_of::<NonNull<i8>>(), size_of::<Option<NonNull<i8>>>());
2014-12-05 19:52:38 +00:00
// Should apply to types that use NonZero internally
assert_eq!(size_of::<Vec<isize>>(), size_of::<Option<Vec<isize>>>());
assert_eq!(size_of::<Arc<isize>>(), size_of::<Option<Arc<isize>>>());
assert_eq!(size_of::<Rc<isize>>(), size_of::<Option<Rc<isize>>>());
2014-12-05 19:52:38 +00:00
// Should apply to types that have NonZero transitively
assert_eq!(size_of::<String>(), size_of::<Option<String>>());
// Should apply to types where the pointer is substituted
assert_eq!(size_of::<&u8>(), size_of::<Option<ParamTypeStruct<&u8>>>());
assert_eq!(size_of::<&u8>(), size_of::<Option<AssocTypeStruct<&u8>>>());
2014-07-04 21:54:23 +00:00
}