use byteable::io::{ReadValue, ReadableError, WriteValue};
use byteable::{Byteable, FromByteArray, IntoByteArray};
use std::io::Cursor;
#[derive(Clone, Copy, Debug, PartialEq, Byteable)]
struct Point3D {
x: f32,
y: f32,
z: f32,
}
#[derive(Debug, PartialEq, Byteable)]
#[byteable(io_only)]
struct Waypoint {
label: String,
position: Point3D,
altitude_m: f32,
}
fn main() -> Result<(), ReadableError> {
let origin = Point3D {
x: 1.0,
y: 2.5,
z: -0.5,
};
println!("Point3D::BYTE_SIZE = {}", Point3D::BYTE_SIZE);
let bytes: [u8; Point3D::BYTE_SIZE] = origin.into_byte_array();
println!("as bytes: {:02x?}", bytes);
assert_eq!(origin, Point3D::from_byte_array(bytes));
let mut buf = Cursor::new(Vec::<u8>::new());
buf.write_value(&origin)?;
buf.set_position(0);
let restored: Point3D = buf.read_value()?;
assert_eq!(origin, restored);
println!("Point3D round-trip via Cursor: ok\n");
let route = vec![
Waypoint {
label: "trailhead".into(),
position: Point3D {
x: 0.0,
y: 0.0,
z: 0.0,
},
altitude_m: 1200.0,
},
Waypoint {
label: "ridge".into(),
position: Point3D {
x: 2.1,
y: 3.4,
z: 0.0,
},
altitude_m: 1850.0,
},
Waypoint {
label: "summit".into(),
position: Point3D {
x: 4.2,
y: 4.2,
z: 0.0,
},
altitude_m: 2103.0,
},
];
let mut buf = Cursor::new(Vec::<u8>::new());
buf.write_value(&route)?;
println!(
"Serialized {} waypoints into {} bytes",
route.len(),
buf.position()
);
buf.set_position(0);
let decoded: Vec<Waypoint> = buf.read_value()?;
for wp in &decoded {
println!(
" {:10} pos=({:.1}, {:.1}) alt={:.0} m",
wp.label, wp.position.x, wp.position.y, wp.altitude_m
);
}
assert_eq!(route, decoded);
println!("All waypoints round-tripped successfully.");
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn main() {
super::main().unwrap();
}
}