simple-someip 0.13.0

A lightweight SOME/IP serialization and communication library
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
use super::Error;
use crate::protocol::byte_order::WriteBytesExt;
use automotive_wire_codec::{Decode, DecodeIter, Encode, take};

pub const ENTRY_SIZE: usize = 16;

/// The type of an SD entry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EntryType {
    /// Find a service (0x00).
    FindService,
    /// Offer a service (0x01).
    OfferService,
    /// Stop offering a service (0x02).
    StopOfferService,
    /// Subscribe to an event group (0x06).
    Subscribe,
    /// Acknowledge an event group subscription (0x07).
    SubscribeAck,
}

impl TryFrom<u8> for EntryType {
    type Error = Error;
    fn try_from(value: u8) -> Result<Self, Error> {
        match value {
            0x00 => Ok(EntryType::FindService),
            0x01 => Ok(EntryType::OfferService),
            0x02 => Ok(EntryType::StopOfferService),
            0x06 => Ok(EntryType::Subscribe),
            0x07 => Ok(EntryType::SubscribeAck),
            _ => Err(Error::InvalidEntryType(value)),
        }
    }
}

impl From<EntryType> for u8 {
    fn from(service_entry_type: EntryType) -> u8 {
        match service_entry_type {
            EntryType::FindService => 0x00,
            EntryType::OfferService => 0x01,
            EntryType::StopOfferService => 0x02,
            EntryType::Subscribe => 0x06,
            EntryType::SubscribeAck => 0x07,
        }
    }
}

/// Packed pair of 4-bit option run counts (first and second options run).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OptionsCount {
    /// Number of options in the first options run.
    pub first_options_count: u8,
    /// Number of options in the second options run.
    pub second_options_count: u8,
}

impl From<u8> for OptionsCount {
    fn from(value: u8) -> Self {
        let first_options_count = (value & 0xf0) >> 4;
        let second_options_count = value & 0x0f;

        Self {
            first_options_count,
            second_options_count,
        }
    }
}

impl From<OptionsCount> for u8 {
    fn from(options_count: OptionsCount) -> u8 {
        ((options_count.first_options_count << 4) & 0xf0)
            | (options_count.second_options_count & 0x0f)
    }
}

impl OptionsCount {
    /// # Panics
    /// Panics if either count is >= 16 (each count must fit in a 4-bit nibble).
    #[must_use]
    pub const fn new(first_options_count: u8, second_options_count: u8) -> Self {
        assert!(first_options_count < 16);
        assert!(second_options_count < 16);
        OptionsCount {
            first_options_count,
            second_options_count,
        }
    }
}

/// An SD entry for event group operations (subscribe / subscribe-ack).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EventGroupEntry {
    /// Index into the options array for the first options run.
    pub index_first_options_run: u8,
    /// Index into the options array for the second options run.
    pub index_second_options_run: u8,
    /// Number of options in each run.
    pub options_count: OptionsCount,
    /// The SOME/IP service ID.
    pub service_id: u16,
    /// The SOME/IP instance ID.
    pub instance_id: u16,
    /// The major version of the service interface.
    pub major_version: u8,
    /// Time-to-live in seconds (24-bit value).
    pub ttl: u32,
    /// Event group counter.
    pub counter: u16,
    /// The event group ID.
    pub event_group_id: u16,
}

impl EventGroupEntry {
    /// Creates a new event group entry with default option indices.
    #[must_use]
    pub const fn new(
        service_id: u16,
        instance_id: u16,
        major_version: u8,
        ttl: u32,
        event_group_id: u16,
    ) -> Self {
        Self {
            index_first_options_run: 0,
            index_second_options_run: 0,
            options_count: OptionsCount::new(1, 0),
            service_id,
            instance_id,
            major_version,
            ttl,
            counter: 0,
            event_group_id,
        }
    }
}

impl Encode for EventGroupEntry {
    type Error = crate::protocol::Error;

    fn encoded_size(&self) -> Result<usize, Self::Error> {
        Ok(15)
    }

    fn encode(&self, writer: &mut impl embedded_io::Write) -> Result<usize, Self::Error> {
        writer.write_u8(self.index_first_options_run)?;
        writer.write_u8(self.index_second_options_run)?;
        writer.write_u8(u8::from(self.options_count))?;
        writer.write_u16_be(self.service_id)?;
        writer.write_u16_be(self.instance_id)?;
        writer.write_u8(self.major_version)?;
        writer.write_u24_be(self.ttl)?;
        writer.write_u16_be(self.counter)?;
        writer.write_u16_be(self.event_group_id)?;
        Ok(15)
    }
}

/// An SD entry for service operations (find / offer / stop-offer).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ServiceEntry {
    /// Index into the options array for the first options run.
    pub index_first_options_run: u8,
    /// Index into the options array for the second options run.
    pub index_second_options_run: u8,
    /// Number of options in each run.
    pub options_count: OptionsCount,
    /// The SOME/IP service ID.
    pub service_id: u16,
    /// The SOME/IP instance ID.
    pub instance_id: u16,
    /// The major version of the service interface.
    pub major_version: u8,
    /// Time-to-live in seconds (24-bit value).
    pub ttl: u32,
    /// The minor version of the service interface.
    pub minor_version: u32,
}

impl ServiceEntry {
    /// Creates a `FindService` entry with wildcard instance/version fields.
    #[must_use]
    pub const fn find(service_id: u16) -> Self {
        Self {
            index_first_options_run: 0,
            index_second_options_run: 0,
            options_count: OptionsCount::new(1, 0),
            service_id,
            instance_id: 0xFFFF,
            major_version: 0xFF,
            ttl: 0x00FF_FFFF,
            minor_version: 0xFFFF_FFFF,
        }
    }
}

impl Encode for ServiceEntry {
    type Error = crate::protocol::Error;

    fn encoded_size(&self) -> Result<usize, Self::Error> {
        Ok(15)
    }

    fn encode(&self, writer: &mut impl embedded_io::Write) -> Result<usize, Self::Error> {
        writer.write_u8(self.index_first_options_run)?;
        writer.write_u8(self.index_second_options_run)?;
        writer.write_u8(u8::from(self.options_count))?;
        writer.write_u16_be(self.service_id)?;
        writer.write_u16_be(self.instance_id)?;
        writer.write_u8(self.major_version)?;
        writer.write_u24_be(self.ttl)?;
        writer.write_u32_be(self.minor_version)?;
        Ok(15)
    }
}

/// A decoded SD entry, wrapping a [`ServiceEntry`] or [`EventGroupEntry`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Entry {
    /// Find a service.
    FindService(ServiceEntry),
    /// Offer a service.
    OfferService(ServiceEntry),
    /// Stop offering a service.
    StopOfferService(ServiceEntry),
    /// Subscribe to an event group.
    SubscribeEventGroup(EventGroupEntry),
    /// Acknowledge an event group subscription.
    SubscribeAckEventGroup(EventGroupEntry),
}

impl Entry {
    /// Returns the number of options in the first options run.
    #[must_use]
    pub fn first_options_count(&self) -> u8 {
        match self {
            Entry::FindService(service_entry)
            | Entry::OfferService(service_entry)
            | Entry::StopOfferService(service_entry) => {
                service_entry.options_count.first_options_count
            }
            Entry::SubscribeEventGroup(event_group_entry)
            | Entry::SubscribeAckEventGroup(event_group_entry) => {
                event_group_entry.options_count.first_options_count
            }
        }
    }

    /// Returns the number of options in the second options run.
    #[must_use]
    pub fn second_options_count(&self) -> u8 {
        match self {
            Entry::FindService(service_entry)
            | Entry::OfferService(service_entry)
            | Entry::StopOfferService(service_entry) => {
                service_entry.options_count.second_options_count
            }
            Entry::SubscribeEventGroup(event_group_entry)
            | Entry::SubscribeAckEventGroup(event_group_entry) => {
                event_group_entry.options_count.second_options_count
            }
        }
    }

    /// Returns the total number of options across both runs.
    #[must_use]
    pub fn total_options_count(&self) -> u8 {
        self.first_options_count() + self.second_options_count()
    }
}

impl Encode for Entry {
    type Error = crate::protocol::Error;

    fn encoded_size(&self) -> Result<usize, Self::Error> {
        // 1 type byte + 15 body bytes = 16 (ENTRY_SIZE) for every variant.
        Ok(ENTRY_SIZE)
    }

    fn encode(&self, writer: &mut impl embedded_io::Write) -> Result<usize, Self::Error> {
        let body = match self {
            Entry::FindService(service_entry) => {
                writer.write_u8(u8::from(EntryType::FindService))?;
                service_entry.encode(writer)?
            }
            Entry::OfferService(service_entry) => {
                writer.write_u8(u8::from(EntryType::OfferService))?;
                service_entry.encode(writer)?
            }
            Entry::StopOfferService(service_entry) => {
                writer.write_u8(u8::from(EntryType::StopOfferService))?;
                service_entry.encode(writer)?
            }
            Entry::SubscribeEventGroup(event_group_entry) => {
                writer.write_u8(u8::from(EntryType::Subscribe))?;
                event_group_entry.encode(writer)?
            }
            Entry::SubscribeAckEventGroup(event_group_entry) => {
                writer.write_u8(u8::from(EntryType::SubscribeAck))?;
                event_group_entry.encode(writer)?
            }
        };
        // 1 type byte + `body` (15) = 16.
        Ok(1 + body)
    }
}

// --- Zero-copy view types ---

/// Zero-copy view into a 16-byte SD entry in a buffer.
///
/// Wire layout (16 bytes total):
/// - `[0]`: entry type
/// - `[1]`: `index_first_options_run`
/// - `[2]`: `index_second_options_run`
/// - `[3]`: `options_count` (packed nibbles)
/// - `[4..6]`: `service_id` (BE)
/// - `[6..8]`: `instance_id` (BE)
/// - `[8]`: `major_version`
/// - `[9..12]`: ttl (24-bit BE)
/// - `[12..16]`: `minor_version` (BE) for service entries,
///   OR `[12..14]` counter + `[14..16]` `event_group_id` for eventgroup entries
#[derive(Clone, Copy, Debug)]
pub struct EntryView<'a>(&'a [u8; ENTRY_SIZE]);

impl EntryView<'_> {
    /// Returns the entry type.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidEntryType`] if the type byte is not recognized.
    pub fn entry_type(&self) -> Result<EntryType, Error> {
        EntryType::try_from(self.0[0])
    }

    /// Returns the index of the first options run.
    #[must_use]
    pub fn index_first_options_run(&self) -> u8 {
        self.0[1]
    }

    /// Returns the index of the second options run.
    #[must_use]
    pub fn index_second_options_run(&self) -> u8 {
        self.0[2]
    }

    /// Returns the packed options count.
    #[must_use]
    pub fn options_count(&self) -> OptionsCount {
        OptionsCount::from(self.0[3])
    }

    /// Returns the service ID.
    #[must_use]
    pub fn service_id(&self) -> u16 {
        u16::from_be_bytes([self.0[4], self.0[5]])
    }

    /// Returns the instance ID.
    #[must_use]
    pub fn instance_id(&self) -> u16 {
        u16::from_be_bytes([self.0[6], self.0[7]])
    }

    /// Returns the major version.
    #[must_use]
    pub fn major_version(&self) -> u8 {
        self.0[8]
    }

    /// Returns the TTL (24-bit value).
    #[must_use]
    pub fn ttl(&self) -> u32 {
        u32::from_be_bytes([0, self.0[9], self.0[10], self.0[11]])
    }

    /// Minor version (only valid for service entries).
    #[must_use]
    pub fn minor_version(&self) -> u32 {
        u32::from_be_bytes([self.0[12], self.0[13], self.0[14], self.0[15]])
    }

    /// Counter field (only valid for eventgroup entries). Masked to lower 4 bits.
    #[must_use]
    pub fn counter(&self) -> u16 {
        u16::from_be_bytes([self.0[12], self.0[13]]) & 0x000f
    }

    /// Event group ID (only valid for eventgroup entries).
    #[must_use]
    pub fn event_group_id(&self) -> u16 {
        u16::from_be_bytes([self.0[14], self.0[15]])
    }

    /// Converts this view into an owned [`Entry`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidEntryType`] if the entry type byte is not recognized.
    pub fn to_owned(&self) -> Result<Entry, Error> {
        let entry_type = self.entry_type()?;
        match entry_type {
            EntryType::FindService => Ok(Entry::FindService(self.to_service_entry())),
            EntryType::OfferService => Ok(Entry::OfferService(self.to_service_entry())),
            EntryType::StopOfferService => Ok(Entry::StopOfferService(self.to_service_entry())),
            EntryType::Subscribe => Ok(Entry::SubscribeEventGroup(self.to_event_group_entry())),
            EntryType::SubscribeAck => {
                Ok(Entry::SubscribeAckEventGroup(self.to_event_group_entry()))
            }
        }
    }

    fn to_service_entry(self) -> ServiceEntry {
        ServiceEntry {
            index_first_options_run: self.index_first_options_run(),
            index_second_options_run: self.index_second_options_run(),
            options_count: self.options_count(),
            service_id: self.service_id(),
            instance_id: self.instance_id(),
            major_version: self.major_version(),
            ttl: self.ttl(),
            minor_version: self.minor_version(),
        }
    }

    fn to_event_group_entry(self) -> EventGroupEntry {
        EventGroupEntry {
            index_first_options_run: self.index_first_options_run(),
            index_second_options_run: self.index_second_options_run(),
            options_count: self.options_count(),
            service_id: self.service_id(),
            instance_id: self.instance_id(),
            major_version: self.major_version(),
            ttl: self.ttl(),
            counter: self.counter(),
            event_group_id: self.event_group_id(),
        }
    }
}

impl<'a> Decode<'a> for EntryView<'a> {
    type Error = crate::protocol::Error;

    /// Decode a single 16-byte SD entry from the front of `buf`.
    ///
    /// This is a pure fixed-stride slice: it does NOT validate the entry-type
    /// byte. Validation is deferred to [`EntryView::entry_type`] /
    /// [`EntryView::to_owned`] (the L2 validation pass), keeping this a lazy
    /// zero-copy view.
    ///
    /// # Errors
    ///
    /// Returns [`Incomplete`](automotive_wire_codec::Incomplete) if fewer than
    /// `ENTRY_SIZE` (16) bytes remain.
    ///
    /// # Panics
    ///
    /// Cannot panic — `take` guarantees exactly `ENTRY_SIZE` bytes.
    fn decode(buf: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
        let (head, rest) = take(buf, ENTRY_SIZE)?;
        let entry_bytes: &'a [u8; ENTRY_SIZE] =
            head.try_into().expect("take guarantees ENTRY_SIZE bytes");
        Ok((EntryView(entry_bytes), rest))
    }
}

impl<'a> DecodeIter<'a> for EntryView<'a> {
    type Error = crate::protocol::Error;

    /// SD entries have a fixed 16-byte (`ENTRY_SIZE`) stride, enabling
    /// [`DecodeIterator::remaining_len`](automotive_wire_codec::DecodeIterator::remaining_len).
    const WIRE_SIZE: Option<usize> = Some(ENTRY_SIZE);

    /// Decode the next entry, or `Ok(None)` at a clean end of buffer.
    ///
    /// A partial (non-multiple-of-16) trailing element is surfaced as an
    /// `Err` rather than silently dropped.
    ///
    /// # Errors
    ///
    /// Returns [`Incomplete`](automotive_wire_codec::Incomplete) if a partial
    /// entry remains after a good start.
    fn decode_next(buf: &'a [u8]) -> Result<Option<(Self, &'a [u8])>, Self::Error> {
        if buf.is_empty() {
            return Ok(None);
        }
        Self::decode(buf).map(Some)
    }
}

/// Iterator over 16-byte SD entries in a validated buffer.
/// Entries are guaranteed valid (validated upfront in `SdHeaderView::parse`).
pub struct EntryIter<'a> {
    remaining: &'a [u8],
}

impl<'a> EntryIter<'a> {
    pub(crate) fn new(buf: &'a [u8]) -> Self {
        Self { remaining: buf }
    }
}

impl<'a> Iterator for EntryIter<'a> {
    type Item = EntryView<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining.len() < ENTRY_SIZE {
            return None;
        }
        let entry_bytes: &[u8; ENTRY_SIZE] = self.remaining[..ENTRY_SIZE]
            .try_into()
            .expect("length checked above");
        self.remaining = &self.remaining[ENTRY_SIZE..];
        Some(EntryView(entry_bytes))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let n = self.remaining.len() / ENTRY_SIZE;
        (n, Some(n))
    }
}

impl ExactSizeIterator for EntryIter<'_> {}

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

    fn encode_entry(entry: &Entry) -> [u8; 17] {
        let mut buf = [0u8; 17];
        entry.encode(&mut buf.as_mut_slice()).unwrap();
        buf
    }

    fn make_service_entry() -> ServiceEntry {
        ServiceEntry {
            index_first_options_run: 1,
            index_second_options_run: 2,
            options_count: OptionsCount::new(3, 4),
            service_id: 0x1234,
            instance_id: 0x5678,
            major_version: 0x01,
            ttl: 0x0000_00FF,
            minor_version: 0x0000_0002,
        }
    }

    fn make_event_group_entry() -> EventGroupEntry {
        EventGroupEntry {
            index_first_options_run: 1,
            index_second_options_run: 2,
            options_count: OptionsCount::new(3, 4),
            service_id: 0xABCD,
            instance_id: 0x0001,
            major_version: 0x02,
            ttl: 0x0000_0064,
            counter: 0x0003,
            event_group_id: 0x0010,
        }
    }

    // --- EntryType ---

    #[test]
    fn entry_type_try_from_all_valid_values() {
        assert_eq!(EntryType::try_from(0x00).unwrap(), EntryType::FindService);
        assert_eq!(EntryType::try_from(0x01).unwrap(), EntryType::OfferService);
        assert_eq!(
            EntryType::try_from(0x02).unwrap(),
            EntryType::StopOfferService
        );
        assert_eq!(EntryType::try_from(0x06).unwrap(), EntryType::Subscribe);
        assert_eq!(EntryType::try_from(0x07).unwrap(), EntryType::SubscribeAck);
    }

    #[test]
    fn entry_type_try_from_invalid_returns_error() {
        assert!(matches!(
            EntryType::try_from(0x03),
            Err(Error::InvalidEntryType(0x03))
        ));
    }

    #[test]
    fn entry_type_into_u8_all_variants() {
        assert_eq!(u8::from(EntryType::FindService), 0x00);
        assert_eq!(u8::from(EntryType::OfferService), 0x01);
        assert_eq!(u8::from(EntryType::StopOfferService), 0x02);
        assert_eq!(u8::from(EntryType::Subscribe), 0x06);
        assert_eq!(u8::from(EntryType::SubscribeAck), 0x07);
    }

    // --- OptionsCount ---

    #[test]
    fn options_count_round_trip() {
        let oc = OptionsCount::new(3, 7);
        let byte = u8::from(oc);
        let decoded = OptionsCount::from(byte);
        assert_eq!(decoded.first_options_count, 3);
        assert_eq!(decoded.second_options_count, 7);
    }

    // --- required_size ---

    #[test]
    fn service_entry_encoded_size() {
        // 15 body bytes (no leading type byte — that belongs to `Entry`).
        assert_eq!(make_service_entry().encoded_size().unwrap(), 15);
    }

    #[test]
    fn event_group_entry_encoded_size() {
        assert_eq!(make_event_group_entry().encoded_size().unwrap(), 15);
    }

    #[test]
    fn entry_encoded_size_all_variants() {
        // 1 type byte + 15 body bytes = 16 (ENTRY_SIZE) for every variant.
        assert_eq!(
            Entry::FindService(make_service_entry())
                .encoded_size()
                .unwrap(),
            16
        );
        assert_eq!(
            Entry::OfferService(make_service_entry())
                .encoded_size()
                .unwrap(),
            16
        );
        assert_eq!(
            Entry::StopOfferService(make_service_entry())
                .encoded_size()
                .unwrap(),
            16
        );
        assert_eq!(
            Entry::SubscribeEventGroup(make_event_group_entry())
                .encoded_size()
                .unwrap(),
            16
        );
        assert_eq!(
            Entry::SubscribeAckEventGroup(make_event_group_entry())
                .encoded_size()
                .unwrap(),
            16
        );
    }

    // --- first/second/total options count ---

    #[test]
    fn entry_options_count_service_variants() {
        let se = make_service_entry(); // first=3, second=4
        for entry in [
            Entry::FindService(se),
            Entry::OfferService(make_service_entry()),
            Entry::StopOfferService(make_service_entry()),
        ] {
            assert_eq!(entry.first_options_count(), 3);
            assert_eq!(entry.second_options_count(), 4);
            assert_eq!(entry.total_options_count(), 7);
        }
    }

    #[test]
    fn entry_options_count_event_group_variants() {
        let eg = make_event_group_entry(); // first=3, second=4
        for entry in [
            Entry::SubscribeEventGroup(eg.clone()),
            Entry::SubscribeAckEventGroup(eg),
        ] {
            assert_eq!(entry.first_options_count(), 3);
            assert_eq!(entry.second_options_count(), 4);
            assert_eq!(entry.total_options_count(), 7);
        }
    }

    // --- Entry encode / EntryView round-trips ---

    #[test]
    fn find_service_entry_round_trips() {
        let entry = Entry::FindService(make_service_entry());
        let buf = encode_entry(&entry);
        // EntryView works on 16 bytes (type byte is first byte of the 16-byte entry)
        // But Entry::encode writes type(1) + data(15) = 16 bytes out of the 17-byte buffer
        let entry_bytes: &[u8; ENTRY_SIZE] = buf[..ENTRY_SIZE].try_into().unwrap();
        let view = EntryView(entry_bytes);
        assert_eq!(view.to_owned().unwrap(), entry);
    }

    #[test]
    fn offer_service_entry_round_trips() {
        let entry = Entry::OfferService(make_service_entry());
        let buf = encode_entry(&entry);
        let entry_bytes: &[u8; ENTRY_SIZE] = buf[..ENTRY_SIZE].try_into().unwrap();
        let view = EntryView(entry_bytes);
        assert_eq!(view.to_owned().unwrap(), entry);
    }

    #[test]
    fn stop_offer_service_entry_round_trips() {
        let entry = Entry::StopOfferService(make_service_entry());
        let buf = encode_entry(&entry);
        let entry_bytes: &[u8; ENTRY_SIZE] = buf[..ENTRY_SIZE].try_into().unwrap();
        let view = EntryView(entry_bytes);
        assert_eq!(view.to_owned().unwrap(), entry);
    }

    #[test]
    fn subscribe_event_group_entry_round_trips() {
        let entry = Entry::SubscribeEventGroup(make_event_group_entry());
        let buf = encode_entry(&entry);
        let entry_bytes: &[u8; ENTRY_SIZE] = buf[..ENTRY_SIZE].try_into().unwrap();
        let view = EntryView(entry_bytes);
        assert_eq!(view.to_owned().unwrap(), entry);
    }

    #[test]
    fn subscribe_ack_event_group_entry_round_trips() {
        let entry = Entry::SubscribeAckEventGroup(make_event_group_entry());
        let buf = encode_entry(&entry);
        let entry_bytes: &[u8; ENTRY_SIZE] = buf[..ENTRY_SIZE].try_into().unwrap();
        let view = EntryView(entry_bytes);
        assert_eq!(view.to_owned().unwrap(), entry);
    }

    #[test]
    fn entry_view_invalid_type_returns_error() {
        let buf: [u8; ENTRY_SIZE] = [0x03; ENTRY_SIZE]; // 0x03 is not a valid EntryType
        let view = EntryView(&buf);
        assert!(matches!(
            view.to_owned(),
            Err(Error::InvalidEntryType(0x03))
        ));
    }

    // --- EntryIter ---

    #[test]
    fn entry_iter_empty() {
        let iter = EntryIter::new(&[]);
        assert_eq!(iter.len(), 0);
    }

    #[test]
    fn entry_iter_two_entries() {
        let e1 = Entry::FindService(make_service_entry());
        let e2 = Entry::SubscribeEventGroup(make_event_group_entry());
        let buf1 = encode_entry(&e1);
        let buf2 = encode_entry(&e2);
        // Concatenate the 16-byte entries (first 16 bytes of each 17-byte encode)
        let mut combined = [0u8; 32];
        combined[..16].copy_from_slice(&buf1[..16]);
        combined[16..32].copy_from_slice(&buf2[..16]);

        let mut iter = EntryIter::new(&combined);
        assert_eq!(iter.len(), 2);
        assert_eq!(iter.next().unwrap().to_owned().unwrap(), e1);
        assert_eq!(iter.next().unwrap().to_owned().unwrap(), e2);
        assert!(iter.next().is_none());
    }

    // --- Decode / DecodeIter (Phase 3 lazy L1) ---

    fn two_entry_buf(e1: &Entry, e2: &Entry) -> [u8; 32] {
        let b1 = encode_entry(e1);
        let b2 = encode_entry(e2);
        let mut combined = [0u8; 32];
        combined[..16].copy_from_slice(&b1[..16]);
        combined[16..32].copy_from_slice(&b2[..16]);
        combined
    }

    #[test]
    fn decode_yields_entry_and_remainder() {
        let e1 = Entry::FindService(make_service_entry());
        let e2 = Entry::SubscribeEventGroup(make_event_group_entry());
        let buf = two_entry_buf(&e1, &e2);
        let (view, rest) = EntryView::decode(&buf).unwrap();
        assert_eq!(view.to_owned().unwrap(), e1);
        assert_eq!(rest.len(), 16);
        let (view2, rest2) = EntryView::decode(rest).unwrap();
        assert_eq!(view2.to_owned().unwrap(), e2);
        assert!(rest2.is_empty());
    }

    #[test]
    fn decode_truncated_is_incomplete() {
        let e1 = Entry::FindService(make_service_entry());
        let buf = encode_entry(&e1);
        assert!(matches!(
            EntryView::decode(&buf[..15]),
            Err(crate::protocol::Error::Incomplete(
                automotive_wire_codec::Incomplete {
                    needed: 16,
                    available: 15,
                }
            ))
        ));
    }

    #[test]
    fn decode_exact_rejects_trailing() {
        let e1 = Entry::FindService(make_service_entry());
        let e2 = Entry::OfferService(make_service_entry());
        let buf = two_entry_buf(&e1, &e2);
        assert!(matches!(
            EntryView::decode_exact(&buf),
            Err(crate::protocol::Error::Trailing(_))
        ));
        // Single entry consumes the whole buffer.
        assert!(EntryView::decode_exact(&buf[..16]).is_ok());
    }

    #[test]
    fn decode_iter_yields_all_then_none() {
        let e1 = Entry::FindService(make_service_entry());
        let e2 = Entry::SubscribeEventGroup(make_event_group_entry());
        let buf = two_entry_buf(&e1, &e2);
        let mut iter = EntryView::iter(&buf);
        assert_eq!(iter.next().unwrap().unwrap().to_owned().unwrap(), e1);
        assert_eq!(iter.next().unwrap().unwrap().to_owned().unwrap(), e2);
        assert!(iter.next().is_none());
    }

    #[test]
    fn decode_iter_surfaces_truncated_tail_as_err() {
        let e1 = Entry::FindService(make_service_entry());
        let buf = two_entry_buf(&e1, &Entry::OfferService(make_service_entry()));
        // One full entry plus a partial (8-byte) tail.
        let mut iter = EntryView::iter(&buf[..24]);
        assert!(matches!(iter.next(), Some(Ok(_))));
        assert!(matches!(
            iter.next(),
            Some(Err(crate::protocol::Error::Incomplete(_)))
        ));
        // Adapter fuses after the first error.
        assert!(iter.next().is_none());
    }

    #[test]
    fn decode_iter_empty_is_immediately_none() {
        let mut iter = EntryView::iter(&[]);
        assert!(iter.next().is_none());
    }

    #[test]
    fn decode_iter_remaining_len_counts_entries() {
        let e1 = Entry::FindService(make_service_entry());
        let e2 = Entry::SubscribeEventGroup(make_event_group_entry());
        let buf = two_entry_buf(&e1, &e2);
        let mut iter = EntryView::iter(&buf);
        assert_eq!(iter.remaining_len(), Some(2));
        iter.next();
        assert_eq!(iter.remaining_len(), Some(1));
        iter.next();
        iter.next(); // Ok(None) -> done
        assert_eq!(iter.remaining_len(), Some(0));
    }

    #[test]
    fn decode_iter_does_not_validate_entry_type() {
        // An invalid entry-type byte (0x03) must still decode as a view — the
        // lazy path defers type validation to `to_owned` / `entry_type`.
        let buf = [0x03u8; ENTRY_SIZE];
        let mut iter = EntryView::iter(&buf);
        let view = iter.next().unwrap().unwrap();
        assert!(matches!(
            view.to_owned(),
            Err(Error::InvalidEntryType(0x03))
        ));
    }

    // --- Encode size-exactness invariant ---

    #[test]
    fn entry_encoded_size_matches_bytes_written() {
        use automotive_wire_codec::CountingSink;
        for entry in [
            Entry::FindService(make_service_entry()),
            Entry::SubscribeEventGroup(make_event_group_entry()),
        ] {
            let mut sink = CountingSink::new();
            let written = entry.encode(&mut sink).unwrap();
            assert_eq!(written, entry.encoded_size().unwrap());
            assert_eq!(written, sink.count());
        }
    }

    #[test]
    fn service_entry_encoded_size_matches_bytes_written() {
        use automotive_wire_codec::CountingSink;
        let se = make_service_entry();
        let mut sink = CountingSink::new();
        let written = se.encode(&mut sink).unwrap();
        assert_eq!(written, se.encoded_size().unwrap());
        assert_eq!(written, sink.count());

        let eg = make_event_group_entry();
        let mut sink = CountingSink::new();
        let written = eg.encode(&mut sink).unwrap();
        assert_eq!(written, eg.encoded_size().unwrap());
        assert_eq!(written, sink.count());
    }

    #[test]
    fn entry_encode_to_slice_too_small_yields_insufficient_buffer() {
        use automotive_wire_codec::{EncodeToSliceError, InsufficientBuffer};
        let entry = Entry::FindService(make_service_entry());
        let mut buf = [0u8; 4]; // far smaller than 16
        let err = entry.encode_to_slice(&mut buf).unwrap_err();
        assert!(matches!(
            err,
            EncodeToSliceError::InsufficientBuffer(InsufficientBuffer {
                needed: 16,
                available: 4,
            })
        ));
    }
}