@@ -364,3 +364,77 @@ fn const_maybe_uninit() {
364364
365365 assert_eq ! ( FIELD_BY_FIELD , Foo { x: 1 , y: 2 } ) ;
366366}
367+
368+ #[ test]
369+ #[ cfg( not( bootstrap) ) ]
370+ fn offset_of ( ) {
371+ #[ repr( C ) ]
372+ struct Foo {
373+ x : u8 ,
374+ y : u16 ,
375+ z : Bar ,
376+ }
377+
378+ #[ repr( C ) ]
379+ struct Bar ( u8 , u8 ) ;
380+
381+ assert_eq ! ( offset_of!( Foo , x) , 0 ) ;
382+ assert_eq ! ( offset_of!( Foo , y) , 2 ) ;
383+ assert_eq ! ( offset_of!( Foo , z. 0 ) , 4 ) ;
384+ assert_eq ! ( offset_of!( Foo , z. 1 ) , 5 ) ;
385+
386+ // Layout of tuples is unstable
387+ assert ! ( offset_of!( ( u8 , u16 ) , 0 ) <= size_of:: <( u8 , u16 ) >( ) - 1 ) ;
388+ assert ! ( offset_of!( ( u8 , u16 ) , 1 ) <= size_of:: <( u8 , u16 ) >( ) - 2 ) ;
389+ }
390+
391+ #[ test]
392+ #[ cfg( not( bootstrap) ) ]
393+ fn const_offset_of ( ) {
394+ #[ repr( C ) ]
395+ struct Foo {
396+ x : u8 ,
397+ y : u16 ,
398+ }
399+
400+ const X_OFFSET : usize = offset_of ! ( Foo , x) ;
401+ const Y_OFFSET : usize = offset_of ! ( Foo , y) ;
402+
403+ assert_eq ! ( X_OFFSET , 0 ) ;
404+ assert_eq ! ( Y_OFFSET , 2 ) ;
405+ }
406+
407+ #[ test]
408+ #[ cfg( not( bootstrap) ) ]
409+ fn offset_of_without_const_promotion ( ) {
410+ #[ repr( C ) ]
411+ struct Foo < SuppressConstPromotion > {
412+ x : u8 ,
413+ y : u16 ,
414+ _scp : SuppressConstPromotion ,
415+ }
416+
417+ // Normally, offset_of is always const promoted.
418+ // The generic parameter prevents this from happening.
419+ // This is needed to test the codegen impl of offset_of
420+ fn inner < SuppressConstPromotion > ( ) {
421+ assert_eq ! ( offset_of!( Foo <SuppressConstPromotion >, x) , 0 ) ;
422+ assert_eq ! ( offset_of!( Foo <SuppressConstPromotion >, y) , 2 ) ;
423+ }
424+
425+ inner :: < ( ) > ( ) ;
426+ }
427+
428+ #[ test]
429+ #[ cfg( not( bootstrap) ) ]
430+ fn offset_of_dst ( ) {
431+ #[ repr( C ) ]
432+ struct Foo {
433+ x : u8 ,
434+ y : u16 ,
435+ slice : [ u8 ] ,
436+ }
437+
438+ assert_eq ! ( offset_of!( Foo , x) , 0 ) ;
439+ assert_eq ! ( offset_of!( Foo , y) , 2 ) ;
440+ }
0 commit comments