Adds the ability to convert a value to the platform or network order.
This handles doing the configure check to see what the platform endianess is for converting byte orders.
This commit is contained in:
@ -4,6 +4,7 @@ use std::ptr::copy_nonoverlapping;
|
||||
use ::byte_sized::ByteSized;
|
||||
use ::byte_sized::{U16_BYTES, U32_BYTES, U64_BYTES};
|
||||
use ::converter::Converter;
|
||||
use ::transmutable::Transmutable;
|
||||
|
||||
|
||||
|
||||
@ -30,6 +31,8 @@ pub type PlatformEndian = LittleEndian;
|
||||
/// common endian style for networking.
|
||||
pub type NetworkEndian = BigEndian;
|
||||
|
||||
|
||||
|
||||
/// Handles serialization where the most
|
||||
/// significant byte is stored at the lowest address.
|
||||
pub enum BigEndian
|
||||
@ -276,6 +279,52 @@ impl Converter for BigEndian
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// Turns a Network order value to a Platform order value.
|
||||
pub fn network_to_platform_order<T>(val: T) -> T
|
||||
where T: Transmutable
|
||||
{
|
||||
let buffer: Vec<u8>;
|
||||
|
||||
// Determine what endianess the Platform is using.
|
||||
if cfg!(target_endian="big")
|
||||
{
|
||||
// Network endianess is Big endian, so they are the same.
|
||||
// Just return the value.
|
||||
val
|
||||
}
|
||||
else
|
||||
{
|
||||
// Convert the value from Big endian to Little endian.
|
||||
buffer = val.to_bytes(Endianess::Network);
|
||||
T::from_bytes(buffer.as_slice(), Endianess::Platform)
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns a Platform order value to a Network order value.
|
||||
pub fn platform_to_network_order<T>(val: T) -> T
|
||||
where T: Transmutable
|
||||
{
|
||||
let buffer: Vec<u8>;
|
||||
|
||||
// Determine what endianess the Platform is using.
|
||||
if cfg!(target_endian="big")
|
||||
{
|
||||
// Network endianess is Big endian, so they are the same.
|
||||
// Just return the value.
|
||||
val
|
||||
}
|
||||
else
|
||||
{
|
||||
// Convert the value from Little endian to Big endian.
|
||||
buffer = val.to_bytes(Endianess::Platform);
|
||||
T::from_bytes(buffer.as_slice(), Endianess::Network)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
impl Converter for LittleEndian
|
||||
{
|
||||
fn bytes_to_u16(buffer: &[u8]) -> u16
|
||||
|
Reference in New Issue
Block a user