diff --git a/Cargo.toml b/Cargo.toml index cc2c89b..4ab5e68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "alchemy" version = "0.1.0" -authors = ["Jason Travis Smith "] +authors = ["Jason Travis Smith "] description = "Handles converting values to and from a binary format." license = "" repository = "https://gitlab.com/CyberMages/alchemy.git" diff --git a/src/endian.rs b/src/endian.rs index 5e6cc4b..234bcfc 100644 --- a/src/endian.rs +++ b/src/endian.rs @@ -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(val: T) -> T + where T: Transmutable +{ + let buffer: Vec; + + // 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(val: T) -> T + where T: Transmutable +{ + let buffer: Vec; + + // 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 diff --git a/src/lib.rs b/src/lib.rs index be32931..5de11c6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,4 +32,5 @@ pub use ::byte_sized::get_byte_size_of_string; pub use ::converter::Converter; pub use ::endian::{BigEndian, LittleEndian, PlatformEndian, NetworkEndian}; pub use ::endian::Endianess; +pub use ::endian::{network_to_platform_order, platform_to_network_order}; pub use ::transmutable::Transmutable;