Created
July 16, 2019 20:06
-
-
Save rust-play/7fab0e97ade27bb16b3192d3c927dc99 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code)] | |
use std::mem::size_of; | |
impl S1 { | |
pub fn as_bytes(&self) -> &[u8] { | |
let ptr = self as *const Self as *const u8; | |
let len = std::mem::size_of::<Self>(); | |
unsafe { std::slice::from_raw_parts(ptr, len) } | |
} | |
} | |
impl S2 { | |
pub fn as_bytes(&self) -> &[u8] { | |
let ptr = self as *const Self as *const u8; | |
let len = std::mem::size_of::<Self>(); | |
unsafe { std::slice::from_raw_parts(ptr, len) } | |
} | |
} | |
impl S3 { | |
pub fn as_bytes(&self) -> &[u8] { | |
let ptr = self as *const Self as *const u8; | |
let len = std::mem::size_of::<Self>(); | |
unsafe { std::slice::from_raw_parts(ptr, len) } | |
} | |
} | |
impl S4 { | |
pub fn as_bytes(&self) -> &[u8] { | |
let ptr = self as *const Self as *const u8; | |
let len = std::mem::size_of::<Self>(); | |
unsafe { std::slice::from_raw_parts(ptr, len) } | |
} | |
} | |
#[repr(C, align(4))] | |
#[derive(Debug, Clone, Copy)] | |
struct S1 { | |
a: u8, | |
b: u16, | |
} | |
#[repr(align(4))] | |
#[derive(Debug, Clone, Copy)] | |
struct S2 { | |
a: u8, | |
b: u16, | |
} | |
#[repr(packed(4))] | |
#[derive(Debug, Clone, Copy)] | |
struct S3 { | |
a: u8, | |
b: u16, | |
} | |
#[repr(C, packed(4))] | |
#[derive(Debug, Clone, Copy)] | |
struct S4 { | |
a: u8, | |
b: u16, | |
} | |
fn main() { | |
let s1 = S1 { a: 255, b: 65535 }; | |
println!("#[repr(C, align(4))] Data: {:?} Size: {} Bytes: {:?}", s1, size_of::<S1>(), s1.as_bytes()); | |
let s2 = S2 { a: 255, b: 65535 }; | |
println!("#[repr(align(4))] Data: {:?} Size: {} Bytes: {:?}", s2, size_of::<S2>(), s2.as_bytes()); | |
let s3 = S3 { a: 255, b: 65535 }; | |
println!("#[repr(packed(4))] Data: {:?} Size: {} Bytes: {:?}", s3, size_of::<S3>(), s3.as_bytes()); | |
let s4 = S4 { a: 255, b: 65535 }; | |
println!("#[repr(C,packed(4))] Data: {:?} Size: {} Bytes: {:?}", s4, size_of::<S4>(), s4.as_bytes()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment