Implement as_ne_bytes for floats and integers
This commit is contained in:
parent
a3bc0e752f
commit
3c582db8cb
4 changed files with 128 additions and 0 deletions
|
@ -2054,6 +2054,41 @@ assert_eq!(
|
|||
}
|
||||
}
|
||||
|
||||
doc_comment! {
|
||||
concat!("
|
||||
Return the memory representation of this integer as a byte array in
|
||||
native byte order.
|
||||
|
||||
[`to_ne_bytes`] should be preferred over this whenever possible.
|
||||
|
||||
[`to_ne_bytes`]: #method.to_ne_bytes
|
||||
",
|
||||
|
||||
"
|
||||
# Examples
|
||||
|
||||
```
|
||||
#![feature(num_as_ne_bytes)]
|
||||
let num = ", $swap_op, stringify!($SelfT), ";
|
||||
let bytes = num.as_ne_bytes();
|
||||
assert_eq!(
|
||||
bytes,
|
||||
if cfg!(target_endian = \"big\") {
|
||||
&", $be_bytes, "
|
||||
} else {
|
||||
&", $le_bytes, "
|
||||
}
|
||||
);
|
||||
```"),
|
||||
#[unstable(feature = "num_as_ne_bytes", issue = "76976")]
|
||||
#[inline]
|
||||
pub fn as_ne_bytes(&self) -> &[u8; mem::size_of::<Self>()] {
|
||||
// SAFETY: integers are plain old datatypes so we can always transmute them to
|
||||
// arrays of bytes
|
||||
unsafe { &*(self as *const Self as *const _) }
|
||||
}
|
||||
}
|
||||
|
||||
doc_comment! {
|
||||
concat!("Create an integer value from its representation as a byte array in
|
||||
big endian.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue