simple_usage/
simple_usage.rs1use byteable::{BigEndian, Byteable, LittleEndian};
7
8#[derive(Byteable, Clone, Copy, PartialEq, Debug)]
10#[repr(C, packed)]
11struct SensorReading {
12 sensor_id: u8,
13 temperature: LittleEndian<u16>, humidity: LittleEndian<u16>, pressure: BigEndian<u32>, }
17
18#[derive(Byteable, Clone, Copy, PartialEq, Debug)]
20#[repr(C, packed)]
21struct RgbColor {
22 red: u8,
23 green: u8,
24 blue: u8,
25}
26
27fn main() {
28 println!("=== Simple Byteable Usage Example ===\n");
29
30 let reading = SensorReading {
32 sensor_id: 5,
33 temperature: LittleEndian::new(2547), humidity: LittleEndian::new(6523), pressure: BigEndian::new(101325), };
37
38 println!("1. Sensor Reading:");
39 println!(" Sensor ID: {}", reading.sensor_id);
40 println!(
41 " Temperature: {:.2}°C",
42 reading.temperature.get() as f32 / 100.0
43 );
44 println!(" Humidity: {:.2}%", reading.humidity.get() as f32 / 100.0);
45 println!(" Pressure: {} Pa", reading.pressure.get());
46
47 let bytes = reading.as_bytearray();
49 println!(" Byte representation: {:?}", bytes);
50 println!(" Size: {} bytes\n", bytes.len());
51
52 println!("2. Reconstructing from bytes:");
54 let reconstructed = SensorReading::from_bytearray(bytes);
55 println!(" Reconstructed: {:?}", reconstructed);
56 println!(" Matches original: {}\n", reconstructed == reading);
57
58 println!("3. RGB Color:");
60 let cyan = RgbColor {
61 red: 0,
62 green: 255,
63 blue: 255,
64 };
65
66 println!(" Color: RGB({}, {}, {})", cyan.red, cyan.green, cyan.blue);
67 let color_bytes = cyan.as_bytearray();
68 println!(" Bytes: {:?}", color_bytes);
69 println!(
70 " Hex representation: #{:02X}{:02X}{:02X}\n",
71 color_bytes[0], color_bytes[1], color_bytes[2]
72 );
73
74 println!("4. Working with arrays:");
76 let color_palette = [
77 RgbColor {
78 red: 255,
79 green: 0,
80 blue: 0,
81 }, RgbColor {
83 red: 0,
84 green: 255,
85 blue: 0,
86 }, RgbColor {
88 red: 0,
89 green: 0,
90 blue: 255,
91 }, ];
93
94 println!(" Color palette:");
95 for (i, color) in color_palette.iter().enumerate() {
96 let bytes = color.as_bytearray();
97 println!(
98 " Color {}: RGB({:3}, {:3}, {:3}) = {:?}",
99 i + 1,
100 color.red,
101 color.green,
102 color.blue,
103 bytes
104 );
105 }
106
107 let total_size = std::mem::size_of::<RgbColor>() * color_palette.len();
109 println!(" Total palette size: {} bytes", total_size);
110
111 println!("\n=== Example completed! ===");
112}