alchemy/examples/convert_u16.rs
Jason Travis Smith eec868b406 Rust no longer requires extern crate calls as of the 2018 update.
Update all the examples to work with the spellbook Array class as well.
2019-01-20 20:38:42 -05:00

134 lines
3.1 KiB
Rust

use weave::Error;
use spellbook::components::Array;
use alchemy::{Converter, Endianess, PlatformEndian, Transmutable};
use alchemy::platform_to_network_order;
fn use_converter()
{
let num: u16;
let mut buffer: Array<u8>;
// Initialize the variables.
num = 32832u16;
buffer = Array::new();
println!("Converting the value {} into and out of an array of bytes.", num);
println!("Buffer starts as: {}", stringify_array(buffer.as_slice()));
// Convert the short point number into an array of bytes.
buffer = PlatformEndian::u16_to_bytes(num);
println!("Buffer contains: {}", stringify_array(buffer.as_slice()));
// Convert the array of bytes into a short number.
match PlatformEndian::bytes_to_u16(buffer.as_slice())
{
Ok(final_num) =>
{
println!("The buffer converts back to: {}", final_num);
}
Err(error) =>
{
println!("{}\n{}", error, error.get_description());
}
}
}
pub fn use_transmutable()
{
let num: u16;
let endianess: Endianess;
let mut buffer: Array<u8>;
// Initialize the variables.
num = 32832u16;
buffer = Array::new();
endianess = Endianess::Platform;
println!("Converting the value {} into and out of an array of bytes.", num);
println!("Buffer starts as: {}", stringify_array(buffer.as_slice()));
// Convert the short point number into an array of bytes.
buffer = num.as_endian_bytes(endianess);
println!("Buffer contains: {}", stringify_array(buffer.as_slice()));
// Convert the array of bytes into a short number.
match u16::from_endian_bytes(buffer.as_slice(), endianess)
{
Ok(final_num) =>
{
println!("The buffer converts back to: {}", final_num);
}
Err(error) =>
{
println!("{}\n{}", error, error.get_description());
}
}
}
/// This just help pretty up the printing of an array of bytes.
fn stringify_array(buffer: &[u8]) -> String
{
let mut result: String;
let mut count: usize;
// Create a new string that starts with just
// the array opening bracket.
result = String::new();
result.push_str("[");
// Loop through the buffer keeping track
// of our place in it.
count = 0usize;
for byte in buffer
{
// Handle priting the last value differently.
if count >= buffer.len() - 1
{
result.push_str(byte.to_string().as_str());
}
else
{
result.push_str(byte.to_string().as_str());
result.push_str(", ");
}
// Mark that we are going to look at
// the next byte in the array.
count += 1;
}
// Add the array closing bracket and
// return the new String.
result.push_str("]");
result
}
pub fn main()
{
println!("Using converter:");
use_converter();
println!("");
println!("Using transmutable:");
use_transmutable();
println!("");
match platform_to_network_order(32832u16)
{
Ok(val) => { println!("This turns into a network value of: {}", val); }
Err(error) => { println!("{}\n{}", error, error.get_description()); }
}
}