simple_usage/
simple_usage.rs

1//! Simple example demonstrating basic usage of the `Byteable` derive macro.
2//!
3//! This example shows the most straightforward use case: converting structs
4//! to and from byte arrays for serialization.
5
6use byteable::{BigEndian, Byteable, ByteableRegular, LittleEndian};
7
8/// A simple sensor reading structure
9#[derive(Byteable, Clone, Copy, Debug)]
10#[repr(C, packed)]
11struct SensorReadingRaw {
12    sensor_id: u8,
13    temperature: LittleEndian<u16>, // Temperature in 0.01°C units
14    humidity: LittleEndian<u16>,    // Humidity in 0.01% units
15    pressure: BigEndian<u32>,       // Pressure in Pascals
16}
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
19struct SensorReading {
20    sensor_id: u8,
21    temperature: u16, // Temperature in 0.01°C units
22    humidity: u16,    // Humidity in 0.01% units
23    pressure: u32,    // Pressure in Pascals
24}
25
26impl ByteableRegular for SensorReading {
27    type Raw = SensorReadingRaw;
28
29    fn to_raw(self) -> Self::Raw {
30        Self::Raw {
31            sensor_id: self.sensor_id,
32            temperature: LittleEndian::new(self.temperature),
33            humidity: LittleEndian::new(self.humidity),
34            pressure: BigEndian::new(self.pressure),
35        }
36    }
37
38    fn from_raw(raw: Self::Raw) -> Self {
39        Self {
40            sensor_id: raw.sensor_id,
41            temperature: raw.temperature.get(),
42            humidity: raw.humidity.get(),
43            pressure: raw.pressure.get(),
44        }
45    }
46}
47
48/// A compact RGB color structure
49#[derive(Byteable, Clone, Copy, PartialEq, Debug)]
50#[repr(C, packed)]
51struct RgbColorRaw {
52    red: u8,
53    green: u8,
54    blue: u8,
55}
56
57#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
58#[repr(C, packed)]
59struct RgbColor {
60    red: u8,
61    green: u8,
62    blue: u8,
63}
64
65impl ByteableRegular for RgbColor {
66    type Raw = RgbColorRaw;
67
68    fn to_raw(self) -> Self::Raw {
69        Self::Raw {
70            red: self.red,
71            green: self.green,
72            blue: self.blue,
73        }
74    }
75
76    fn from_raw(raw: Self::Raw) -> Self {
77        Self {
78            red: raw.red,
79            green: raw.green,
80            blue: raw.blue,
81        }
82    }
83}
84
85fn main() {
86    println!("=== Simple Byteable Usage Example ===\n");
87
88    // Example 1: Create a sensor reading
89    let reading = SensorReading {
90        sensor_id: 5,
91        temperature: 2547, // 25.47°C
92        humidity: 6523,    // 65.23%
93        pressure: 101325,  // Standard atmospheric pressure
94    };
95
96    println!("1. Sensor Reading:");
97    println!("   Sensor ID: {}", reading.sensor_id);
98    println!(
99        "   Temperature: {:.2}°C",
100        reading.temperature as f32 / 100.0
101    );
102    println!("   Humidity: {:.2}%", reading.humidity as f32 / 100.0);
103    println!("   Pressure: {} Pa", reading.pressure);
104
105    // Convert to bytes
106    let bytes = reading.as_bytearray();
107    println!("   Byte representation: {:?}", bytes);
108    println!("   Size: {} bytes\n", bytes.len());
109
110    // Example 2: Reconstruct from bytes
111    println!("2. Reconstructing from bytes:");
112    let reconstructed = SensorReading::from_bytearray(bytes);
113    println!("   Reconstructed: {:?}", reconstructed);
114    println!("   Matches original: {}\n", reconstructed == reading);
115
116    // Example 3: Working with colors
117    println!("3. RGB Color:");
118    let cyan = RgbColor {
119        red: 0,
120        green: 255,
121        blue: 255,
122    };
123
124    println!("   Color: RGB({}, {}, {})", cyan.red, cyan.green, cyan.blue);
125    let color_bytes = cyan.as_bytearray();
126    println!("   Bytes: {:?}", color_bytes);
127    println!(
128        "   Hex representation: #{:02X}{:02X}{:02X}\n",
129        color_bytes[0], color_bytes[1], color_bytes[2]
130    );
131
132    // Example 4: Array of byteable structs
133    println!("4. Working with arrays:");
134    let color_palette = [
135        RgbColor {
136            red: 255,
137            green: 0,
138            blue: 0,
139        }, // Red
140        RgbColor {
141            red: 0,
142            green: 255,
143            blue: 0,
144        }, // Green
145        RgbColor {
146            red: 0,
147            green: 0,
148            blue: 255,
149        }, // Blue
150    ];
151
152    println!("   Color palette:");
153    for (i, color) in color_palette.iter().enumerate() {
154        let bytes = color.as_bytearray();
155        println!(
156            "   Color {}: RGB({:3}, {:3}, {:3}) = {:?}",
157            i + 1,
158            color.red,
159            color.green,
160            color.blue,
161            bytes
162        );
163    }
164
165    // Convert entire palette to bytes
166    let total_size = RgbColor::binary_size() * color_palette.len();
167    println!("   Total palette size: {} bytes", total_size);
168
169    println!("\n=== Example completed! ===");
170}