Wednesday 13 May 2015

Rust: network byte order

Languages on different architectures might serialize the 32-bit unsigned int 15 as the byte sequences 00 00 00 0F (big-endian) or 0F 00 00 00 (little-endian) but network protocols generally prefer the former.

pub fn to_network_byte_order(n: u32) -> u32 {
  n.to_be()
}

pub fn from_network_byte_order(n: u32) -> u32 {
  u32::from_be(n)
}

#[cfg(test)]
mod test {
  use super::*;

  #[test]
  fn test_to_network_byte_order() {
    let expected: u32 = 0xFFAABBCC;
    let nbo = to_network_byte_order(expected);
    if cfg!(target_endian = "big") {
      assert_eq!(expected, nbo);
    } else {
      assert_eq!(expected.swap_bytes(), nbo);
    }
    let actual = from_network_byte_order(nbo);
    assert_eq!(expected, actual);
  }
}

u32 is a 32-bit unsigned integer; i32 is the signed version.

This post is just a code snippet written by someone getting started. No promises are made about code quality. Version: rustc 1.0.0-beta.4 (850151a75 2015-04-30) (built 2015-04-30)

No comments:

Post a Comment

All comments are moderated