ara-com 0.1.0

Core traits and async abstractions for Adaptive AUTOSAR communication in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Standard-type impls for `AraSerialize` / `AraDeserialize`.
//!
//! These impls live in `ara-com` (where the traits are defined) so that the
//! orphan rule is satisfied.  Transport backends such as `ara-com-someip`
//! re-export these impls and add **only** backend-specific helpers on top.

use crate::error::AraComError;
use crate::transport::{AraDeserialize, AraSerialize};

// ---------------------------------------------------------------------------
// Helper macro — big-endian integer types
// ---------------------------------------------------------------------------

macro_rules! impl_int {
    ($t:ty) => {
        impl AraSerialize for $t {
            fn ara_serialize(&self, buf: &mut Vec<u8>) -> Result<(), AraComError> {
                buf.extend_from_slice(&self.to_be_bytes());
                Ok(())
            }

            fn serialized_size(&self) -> usize {
                std::mem::size_of::<$t>()
            }
        }

        impl AraDeserialize for $t {
            fn ara_deserialize(buf: &[u8]) -> Result<Self, AraComError> {
                const N: usize = std::mem::size_of::<$t>();
                if buf.len() < N {
                    return Err(AraComError::Deserialization {
                        message: format!(
                            "need {} bytes for {}, got {}",
                            N,
                            stringify!($t),
                            buf.len()
                        ),
                    });
                }
                let arr: [u8; N] = buf[..N].try_into().unwrap();
                Ok(<$t>::from_be_bytes(arr))
            }
        }
    };
}

impl_int!(u8);
impl_int!(u16);
impl_int!(u32);
impl_int!(u64);
impl_int!(i8);
impl_int!(i16);
impl_int!(i32);
impl_int!(i64);

// ---------------------------------------------------------------------------
// f32
// ---------------------------------------------------------------------------

impl AraSerialize for f32 {
    fn ara_serialize(&self, buf: &mut Vec<u8>) -> Result<(), AraComError> {
        buf.extend_from_slice(&self.to_bits().to_be_bytes());
        Ok(())
    }

    fn serialized_size(&self) -> usize {
        4
    }
}

impl AraDeserialize for f32 {
    fn ara_deserialize(buf: &[u8]) -> Result<Self, AraComError> {
        if buf.len() < 4 {
            return Err(AraComError::Deserialization {
                message: format!("need 4 bytes for f32, got {}", buf.len()),
            });
        }
        let arr: [u8; 4] = buf[..4].try_into().unwrap();
        Ok(f32::from_bits(u32::from_be_bytes(arr)))
    }
}

// ---------------------------------------------------------------------------
// f64
// ---------------------------------------------------------------------------

impl AraSerialize for f64 {
    fn ara_serialize(&self, buf: &mut Vec<u8>) -> Result<(), AraComError> {
        buf.extend_from_slice(&self.to_bits().to_be_bytes());
        Ok(())
    }

    fn serialized_size(&self) -> usize {
        8
    }
}

impl AraDeserialize for f64 {
    fn ara_deserialize(buf: &[u8]) -> Result<Self, AraComError> {
        if buf.len() < 8 {
            return Err(AraComError::Deserialization {
                message: format!("need 8 bytes for f64, got {}", buf.len()),
            });
        }
        let arr: [u8; 8] = buf[..8].try_into().unwrap();
        Ok(f64::from_bits(u64::from_be_bytes(arr)))
    }
}

// ---------------------------------------------------------------------------
// bool — 0x00 = false, 0x01 = true
// ---------------------------------------------------------------------------

impl AraSerialize for bool {
    fn ara_serialize(&self, buf: &mut Vec<u8>) -> Result<(), AraComError> {
        buf.push(if *self { 0x01 } else { 0x00 });
        Ok(())
    }

    fn serialized_size(&self) -> usize {
        1
    }
}

impl AraDeserialize for bool {
    fn ara_deserialize(buf: &[u8]) -> Result<Self, AraComError> {
        if buf.is_empty() {
            return Err(AraComError::Deserialization {
                message: "need 1 byte for bool, got 0".to_string(),
            });
        }
        match buf[0] {
            0x00 => Ok(false),
            0x01 => Ok(true),
            v => Err(AraComError::Deserialization {
                message: format!("invalid bool byte: 0x{v:02X}"),
            }),
        }
    }
}

// ---------------------------------------------------------------------------
// String — SOME/IP wire format:
//   4-byte big-endian total byte length (including BOM + NUL) +
//   UTF-8 BOM (0xEF 0xBB 0xBF) + UTF-8 bytes + NUL (0x00)
//
// Special case: empty string serializes as 4 zero bytes only (vsomeip compat).
// ---------------------------------------------------------------------------

const UTF8_BOM: [u8; 3] = [0xEF, 0xBB, 0xBF];

impl AraSerialize for String {
    fn ara_serialize(&self, buf: &mut Vec<u8>) -> Result<(), AraComError> {
        if self.is_empty() {
            buf.extend_from_slice(&0u32.to_be_bytes());
            return Ok(());
        }
        let bytes = self.as_bytes();
        // total length = 3 (BOM) + string bytes + 1 (NUL)
        let total_len = (3 + bytes.len() + 1) as u32;
        buf.extend_from_slice(&total_len.to_be_bytes());
        buf.extend_from_slice(&UTF8_BOM);
        buf.extend_from_slice(bytes);
        buf.push(0x00);
        Ok(())
    }

    fn serialized_size(&self) -> usize {
        if self.is_empty() {
            4
        } else {
            4 + 3 + self.len() + 1
        }
    }
}

impl AraDeserialize for String {
    fn ara_deserialize(buf: &[u8]) -> Result<Self, AraComError> {
        if buf.len() < 4 {
            return Err(AraComError::Deserialization {
                message: format!("need 4-byte length prefix for String, got {}", buf.len()),
            });
        }
        let len = u32::from_be_bytes(buf[..4].try_into().unwrap()) as usize;
        if len == 0 {
            return Ok(String::new());
        }
        if buf.len() < 4 + len {
            return Err(AraComError::Deserialization {
                message: format!(
                    "String payload truncated: need {} bytes, got {}",
                    len,
                    buf.len() - 4
                ),
            });
        }
        let payload = &buf[4..4 + len];
        // Skip UTF-8 BOM if present
        let content = if payload.starts_with(&UTF8_BOM) {
            &payload[3..]
        } else {
            payload
        };
        // Strip trailing NUL if present
        let content = if content.last() == Some(&0x00) {
            &content[..content.len() - 1]
        } else {
            content
        };
        let s = std::str::from_utf8(content).map_err(|e| AraComError::Deserialization {
            message: format!("String is not valid UTF-8: {e}"),
        })?;
        Ok(s.to_owned())
    }
}

// ---------------------------------------------------------------------------
// Vec<T> — SOME/IP wire format:
//   4-byte big-endian **byte length** of all serialized elements, then elements.
//   (NOT element count — SOME/IP uses byte length prefix per PRS_SOMEIP_00462)
// ---------------------------------------------------------------------------

impl<T: AraSerialize> AraSerialize for Vec<T> {
    fn ara_serialize(&self, buf: &mut Vec<u8>) -> Result<(), AraComError> {
        let capacity: usize = self.iter().map(|item| item.serialized_size()).sum();
        let mut elements_buf: Vec<u8> = Vec::with_capacity(capacity);
        for item in self {
            item.ara_serialize(&mut elements_buf)?;
        }
        let byte_len = elements_buf.len() as u32;
        buf.extend_from_slice(&byte_len.to_be_bytes());
        buf.extend_from_slice(&elements_buf);
        Ok(())
    }

    fn serialized_size(&self) -> usize {
        4 + self
            .iter()
            .map(|item| item.serialized_size())
            .sum::<usize>()
    }
}

impl<T: AraDeserialize + AraSerialize> AraDeserialize for Vec<T> {
    fn ara_deserialize(buf: &[u8]) -> Result<Self, AraComError> {
        if buf.len() < 4 {
            return Err(AraComError::Deserialization {
                message: format!("need 4-byte byte-length prefix for Vec, got {}", buf.len()),
            });
        }
        let byte_len = u32::from_be_bytes(buf[..4].try_into().unwrap()) as usize;
        if buf.len() < 4 + byte_len {
            return Err(AraComError::Deserialization {
                message: format!(
                    "Vec payload truncated: need {} bytes, got {}",
                    byte_len,
                    buf.len() - 4
                ),
            });
        }
        let payload = &buf[4..4 + byte_len];
        let mut offset = 0;
        let mut result = Vec::new();
        while offset < payload.len() {
            let item = T::ara_deserialize(&payload[offset..])?;
            offset += item.serialized_size();
            if offset > payload.len() {
                return Err(AraComError::Deserialization {
                    message: format!(
                        "Vec element overran payload: offset {} exceeds {} bytes",
                        offset,
                        payload.len()
                    ),
                });
            }
            result.push(item);
        }
        Ok(result)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn round_trip<T>(value: T) -> T
    where
        T: AraSerialize + AraDeserialize + Copy + std::fmt::Debug + PartialEq,
    {
        let mut buf = Vec::new();
        value.ara_serialize(&mut buf).unwrap();
        assert_eq!(buf.len(), value.serialized_size());
        T::ara_deserialize(&buf).unwrap()
    }

    // --- integer types ---

    #[test]
    fn test_u8_round_trip() {
        assert_eq!(round_trip(0u8), 0);
        assert_eq!(round_trip(255u8), 255);
    }

    #[test]
    fn test_u16_big_endian() {
        let mut buf = Vec::new();
        0x0102u16.ara_serialize(&mut buf).unwrap();
        assert_eq!(buf, [0x01, 0x02]);
        assert_eq!(u16::ara_deserialize(&buf).unwrap(), 0x0102);
    }

    #[test]
    fn test_u32_round_trip() {
        assert_eq!(round_trip(0xDEAD_BEEFu32), 0xDEAD_BEEF);
    }

    #[test]
    fn test_u64_round_trip() {
        assert_eq!(round_trip(u64::MAX), u64::MAX);
    }

    #[test]
    fn test_i32_negative() {
        assert_eq!(round_trip(-1i32), -1);
        assert_eq!(round_trip(i32::MIN), i32::MIN);
    }

    #[test]
    fn test_f32_round_trip() {
        assert_eq!(round_trip(1.5f32), 1.5f32);
        assert!(round_trip(f32::NAN).is_nan());
    }

    #[test]
    fn test_f64_round_trip() {
        assert_eq!(round_trip(std::f64::consts::PI), std::f64::consts::PI);
    }

    #[test]
    fn test_bool_round_trip() {
        assert!(!round_trip(false));
        assert!(round_trip(true));
    }

    #[test]
    fn test_bool_encoding() {
        let mut buf = Vec::new();
        true.ara_serialize(&mut buf).unwrap();
        assert_eq!(buf, [0x01]);
        let mut buf = Vec::new();
        false.ara_serialize(&mut buf).unwrap();
        assert_eq!(buf, [0x00]);
    }

    #[test]
    fn test_deserialize_insufficient_bytes() {
        let result = u32::ara_deserialize(&[0x00, 0x01]);
        assert!(result.is_err());
    }

    #[test]
    fn test_bool_invalid_byte() {
        let result = bool::ara_deserialize(&[0x02]);
        assert!(result.is_err());
    }

    // --- String ---

    #[test]
    fn test_string_round_trip() {
        let original = "hello SOME/IP".to_string();
        let mut buf = Vec::new();
        original.ara_serialize(&mut buf).unwrap();
        assert_eq!(buf.len(), original.serialized_size());
        let decoded = String::ara_deserialize(&buf).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_empty_string() {
        let original = String::new();
        let mut buf = Vec::new();
        original.ara_serialize(&mut buf).unwrap();
        // Empty string: just 4 zero bytes (vsomeip compat — no BOM/NUL)
        assert_eq!(buf, [0x00, 0x00, 0x00, 0x00]);
        assert_eq!(String::ara_deserialize(&buf).unwrap(), "");
    }

    #[test]
    fn test_string_bom_nul() {
        // "AB" => length=6 (3 BOM + 2 chars + 1 NUL), then BOM, "A", "B", NUL
        let s = "AB".to_string();
        let mut buf = Vec::new();
        s.ara_serialize(&mut buf).unwrap();
        assert_eq!(
            buf,
            [0x00, 0x00, 0x00, 0x06, 0xEF, 0xBB, 0xBF, 0x41, 0x42, 0x00]
        );
    }

    // --- Vec<T> ---

    #[test]
    fn test_vec_u32_round_trip() {
        let original: Vec<u32> = vec![1, 2, 3, 0xDEAD_BEEF];
        let mut buf = Vec::new();
        original.ara_serialize(&mut buf).unwrap();
        assert_eq!(buf.len(), original.serialized_size());
        assert_eq!(&buf[..4], &[0x00, 0x00, 0x00, 0x10]);
        let decoded: Vec<u32> = Vec::ara_deserialize(&buf).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_empty_vec() {
        let original: Vec<u8> = vec![];
        let mut buf = Vec::new();
        original.ara_serialize(&mut buf).unwrap();
        assert_eq!(buf, [0x00, 0x00, 0x00, 0x00]);
        let decoded: Vec<u8> = Vec::ara_deserialize(&buf).unwrap();
        assert!(decoded.is_empty());
    }

    #[test]
    fn test_vec_u16_byte_length() {
        // 2 x u16 = 4 bytes of payload, so prefix should be 0x00000004, NOT element count 0x00000002
        let v: Vec<u16> = vec![1u16, 2u16];
        let mut buf = Vec::new();
        v.ara_serialize(&mut buf).unwrap();
        assert_eq!(&buf[..4], &[0x00, 0x00, 0x00, 0x04]);
    }
}