Skip to content

Commit 29b89c3

Browse files
committed
Add default impls of to/from_ne_bytes
1 parent 001dd32 commit 29b89c3

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/ops/bytes.rs

+15-3
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,16 @@ pub trait ToBytes {
9999
/// # #[cfg(not(has_int_to_from_bytes))]
100100
/// # fn main() {}
101101
/// ```
102-
fn to_ne_bytes(&self) -> Self::Bytes;
102+
fn to_ne_bytes(&self) -> Self::Bytes {
103+
#[cfg(target_endian = "big")]
104+
let bytes = self.to_be_bytes();
105+
#[cfg(target_endian = "little")]
106+
let bytes = self.to_le_bytes();
107+
bytes
108+
}
103109
}
104110

105-
pub trait FromBytes {
111+
pub trait FromBytes: Sized {
106112
type Bytes: NumBytes;
107113

108114
/// Create a number from its representation as a byte array in big endian.
@@ -156,7 +162,13 @@ pub trait FromBytes {
156162
/// # #[cfg(not(has_int_to_from_bytes))]
157163
/// # fn main() {}
158164
/// ```
159-
fn from_ne_bytes(bytes: &Self::Bytes) -> Self;
165+
fn from_ne_bytes(bytes: &Self::Bytes) -> Self {
166+
#[cfg(target_endian = "big")]
167+
let this = Self::from_be_bytes(bytes);
168+
#[cfg(target_endian = "little")]
169+
let this = Self::from_le_bytes(bytes);
170+
this
171+
}
160172
}
161173

162174
macro_rules! float_to_from_bytes_impl {

0 commit comments

Comments
 (0)