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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
use core::net::{Ipv4Addr, Ipv6Addr};

use super::Error;
use crate::protocol::byte_order::WriteBytesExt;
use automotive_wire_codec::{Decode, DecodeIter, Encode, ensure_len, take};

/// Maximum length of an SD configuration option string in bytes.
pub const MAX_CONFIGURATION_STRING_LENGTH: usize = 256;

// --- SD option wire-layout constants ---
//
// Every SD option begins with a 4-byte fixed header:
//   [0..2]: length (u16 BE)        — value is `wire_size - OPTION_LENGTH_SIZE_DELTA`
//   [2]:    option type (u8)
//   [3]:    reserved/discard flag (u8)
// Per-type payload follows starting at offset `OPTION_PAYLOAD_OFFSET`.

/// Size of the fixed SD option header (length + type + discard flag).
pub(crate) const OPTION_HEADER_SIZE: usize = 4;
/// The SD option length field encodes `wire_size - OPTION_LENGTH_SIZE_DELTA`.
pub(crate) const OPTION_LENGTH_SIZE_DELTA: usize = 3;
/// Byte offset of the option type byte inside the fixed header.
const OPTION_TYPE_OFFSET: usize = 2;
/// Byte offset at which per-type payload begins.
const OPTION_PAYLOAD_OFFSET: usize = 4;

// IPv4 endpoint / multicast / SD options.
/// Total wire size of an IPv4 endpoint/multicast/SD option.
pub(crate) const IPV4_OPTION_WIRE_SIZE: usize = 12;
/// Length-field value stored on the wire for an IPv4 option.
pub(crate) const IPV4_OPTION_LENGTH_FIELD: u16 = 9;
/// Byte offset of the 4-octet IPv4 address within the option.
pub(crate) const IPV4_OPTION_IP_OFFSET: usize = OPTION_PAYLOAD_OFFSET;
/// Byte offset of the transport protocol byte inside an IPv4 option.
pub(crate) const IPV4_OPTION_PROTOCOL_OFFSET: usize = 9;
/// Byte offset of the port (u16 BE) inside an IPv4 option.
pub(crate) const IPV4_OPTION_PORT_OFFSET: usize = 10;

// IPv6 endpoint / multicast / SD options.
/// Total wire size of an IPv6 endpoint/multicast/SD option.
pub(crate) const IPV6_OPTION_WIRE_SIZE: usize = 24;
/// Length-field value stored on the wire for an IPv6 option.
pub(crate) const IPV6_OPTION_LENGTH_FIELD: u16 = 21;
/// Byte offset of the 16-octet IPv6 address within the option.
const IPV6_OPTION_IP_OFFSET: usize = OPTION_PAYLOAD_OFFSET;
/// Byte offset (exclusive) marking the end of the 16-octet IPv6 address.
const IPV6_OPTION_IP_END: usize = IPV6_OPTION_IP_OFFSET + 16;
/// Byte offset of the transport protocol byte inside an IPv6 option.
pub(crate) const IPV6_OPTION_PROTOCOL_OFFSET: usize = 21;
/// Byte offset of the port (u16 BE) inside an IPv6 option.
const IPV6_OPTION_PORT_OFFSET: usize = 22;

// Load-balancing option.
/// Total wire size of a load-balancing option.
const LOAD_BALANCING_OPTION_WIRE_SIZE: usize = 8;
/// Length-field value stored on the wire for a load-balancing option.
pub(crate) const LOAD_BALANCING_OPTION_LENGTH_FIELD: u16 = 5;

// Configuration option.
/// The configuration option's length field value is `1 + string_len`
/// (the `+1` accounts for the trailing null terminator byte).
const CONFIGURATION_OPTION_LENGTH_STRING_DELTA: u16 = 1;

pub use crate::net_endpoint::TransportProtocol;

impl TryFrom<u8> for TransportProtocol {
    type Error = Error;
    fn try_from(value: u8) -> Result<Self, Error> {
        match value {
            0x11 => Ok(TransportProtocol::Udp),
            0x06 => Ok(TransportProtocol::Tcp),
            _ => Err(Error::InvalidOptionTransportProtocol(value)),
        }
    }
}

impl TryFrom<TransportProtocol> for u8 {
    type Error = Error;
    fn try_from(value: TransportProtocol) -> Result<u8, Error> {
        match value {
            TransportProtocol::Udp => Ok(0x11),
            TransportProtocol::Tcp => Ok(0x06),
        }
    }
}

/// The type of an SD option.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OptionType {
    /// Configuration option (0x01).
    Configuration,
    /// Load balancing option (0x02).
    LoadBalancing,
    /// IPv4 endpoint option (0x04).
    IpV4Endpoint,
    /// IPv6 endpoint option (0x06).
    IpV6Endpoint,
    /// IPv4 multicast option (0x14).
    IpV4Multicast,
    /// IPv6 multicast option (0x16).
    IpV6Multicast,
    /// IPv4 SD option (0x24).
    IpV4SD,
    /// IPv6 SD option (0x26).
    IpV6SD,
}

impl TryFrom<u8> for OptionType {
    type Error = Error;
    fn try_from(value: u8) -> Result<Self, Error> {
        match value {
            0x01 => Ok(OptionType::Configuration),
            0x02 => Ok(OptionType::LoadBalancing),
            0x04 => Ok(OptionType::IpV4Endpoint),
            0x06 => Ok(OptionType::IpV6Endpoint),
            0x14 => Ok(OptionType::IpV4Multicast),
            0x16 => Ok(OptionType::IpV6Multicast),
            0x24 => Ok(OptionType::IpV4SD),
            0x26 => Ok(OptionType::IpV6SD),
            _ => Err(Error::InvalidOptionType(value)),
        }
    }
}

impl From<OptionType> for u8 {
    fn from(option_type: OptionType) -> u8 {
        match option_type {
            OptionType::Configuration => 0x01,
            OptionType::LoadBalancing => 0x02,
            OptionType::IpV4Endpoint => 0x04,
            OptionType::IpV6Endpoint => 0x06,
            OptionType::IpV4Multicast => 0x14,
            OptionType::IpV6Multicast => 0x16,
            OptionType::IpV4SD => 0x24,
            OptionType::IpV6SD => 0x26,
        }
    }
}

// Boxing is not available in no_std, so allow the large variant.
#[allow(clippy::large_enum_variant)]
/// A decoded SD option.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Options {
    /// A configuration key-value string.
    Configuration {
        /// The raw configuration string bytes.
        configuration_string: heapless::Vec<u8, MAX_CONFIGURATION_STRING_LENGTH>,
    },
    /// Load balancing parameters.
    LoadBalancing {
        /// The priority value.
        priority: u16,
        /// The weight value.
        weight: u16,
    },
    /// An IPv4 endpoint.
    IpV4Endpoint {
        /// The IPv4 address.
        ip: Ipv4Addr,
        /// The transport protocol (UDP or TCP).
        protocol: TransportProtocol,
        /// The port number.
        port: u16,
    },
    /// An IPv6 endpoint.
    IpV6Endpoint {
        /// The IPv6 address.
        ip: Ipv6Addr,
        /// The transport protocol (UDP or TCP).
        protocol: TransportProtocol,
        /// The port number.
        port: u16,
    },
    /// An IPv4 multicast address.
    IpV4Multicast {
        /// The IPv4 multicast address.
        ip: Ipv4Addr,
        /// The transport protocol (UDP or TCP).
        protocol: TransportProtocol,
        /// The port number.
        port: u16,
    },
    /// An IPv6 multicast address.
    IpV6Multicast {
        /// The IPv6 multicast address.
        ip: Ipv6Addr,
        /// The transport protocol (UDP or TCP).
        protocol: TransportProtocol,
        /// The port number.
        port: u16,
    },
    /// An IPv4 SD endpoint.
    IpV4SD {
        /// The IPv4 address.
        ip: Ipv4Addr,
        /// The transport protocol (UDP or TCP).
        protocol: TransportProtocol,
        /// The port number.
        port: u16,
    },
    /// An IPv6 SD endpoint.
    IpV6SD {
        /// The IPv6 address.
        ip: Ipv6Addr,
        /// The transport protocol (UDP or TCP).
        protocol: TransportProtocol,
        /// The port number.
        port: u16,
    },
}

impl Options {
    /// Returns the total wire size of this option in bytes.
    #[must_use]
    pub fn size(&self) -> usize {
        match self {
            Options::Configuration {
                configuration_string,
            } => OPTION_HEADER_SIZE + configuration_string.len(),
            Options::LoadBalancing { .. } => LOAD_BALANCING_OPTION_WIRE_SIZE,
            Options::IpV4Endpoint { .. }
            | Options::IpV4Multicast { .. }
            | Options::IpV4SD { .. } => IPV4_OPTION_WIRE_SIZE,
            Options::IpV6Endpoint { .. }
            | Options::IpV6Multicast { .. }
            | Options::IpV6SD { .. } => IPV6_OPTION_WIRE_SIZE,
        }
    }
}

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

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

    /// Serializes this option to a writer.
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the writer fails.
    ///
    /// # Panics
    ///
    /// Panics if the option size minus `OPTION_LENGTH_SIZE_DELTA` exceeds `u16::MAX`
    /// (unreachable in practice).
    fn encode(&self, writer: &mut impl embedded_io::Write) -> Result<usize, Self::Error> {
        writer.write_u16_be(
            u16::try_from(self.size() - OPTION_LENGTH_SIZE_DELTA).expect("option size fits u16"),
        )?;
        match self {
            Options::Configuration {
                configuration_string,
            } => {
                writer.write_u8(u8::from(OptionType::Configuration))?;
                writer.write_u8(0)?;
                writer.write_bytes(configuration_string)?;
                Ok(self.size())
            }
            Options::LoadBalancing { priority, weight } => {
                writer.write_u8(u8::from(OptionType::LoadBalancing))?;
                writer.write_u8(0)?;
                writer.write_u16_be(*priority)?;
                writer.write_u16_be(*weight)?;
                Ok(LOAD_BALANCING_OPTION_WIRE_SIZE)
            }
            Options::IpV4Endpoint { ip, protocol, port } => {
                write_ipv4_option(writer, OptionType::IpV4Endpoint, *ip, *protocol, *port)
            }
            Options::IpV6Endpoint { ip, protocol, port } => {
                write_ipv6_option(writer, OptionType::IpV6Endpoint, *ip, *protocol, *port)
            }
            Options::IpV4Multicast { ip, protocol, port } => {
                write_ipv4_option(writer, OptionType::IpV4Multicast, *ip, *protocol, *port)
            }
            Options::IpV6Multicast { ip, protocol, port } => {
                write_ipv6_option(writer, OptionType::IpV6Multicast, *ip, *protocol, *port)
            }
            Options::IpV4SD { ip, protocol, port } => {
                write_ipv4_option(writer, OptionType::IpV4SD, *ip, *protocol, *port)
            }
            Options::IpV6SD { ip, protocol, port } => {
                write_ipv6_option(writer, OptionType::IpV6SD, *ip, *protocol, *port)
            }
        }
    }
}

fn write_ipv4_option<T: embedded_io::Write>(
    writer: &mut T,
    option_type: OptionType,
    ip: Ipv4Addr,
    protocol: TransportProtocol,
    port: u16,
) -> Result<usize, crate::protocol::Error> {
    writer.write_u8(u8::from(option_type))?;
    writer.write_u8(0)?;
    writer.write_u32_be(ip.to_bits())?;
    writer.write_u8(0)?;
    writer.write_u8(u8::try_from(protocol)?)?;
    writer.write_u16_be(port)?;
    Ok(IPV4_OPTION_WIRE_SIZE)
}

fn write_ipv6_option<T: embedded_io::Write>(
    writer: &mut T,
    option_type: OptionType,
    ip: Ipv6Addr,
    protocol: TransportProtocol,
    port: u16,
) -> Result<usize, crate::protocol::Error> {
    writer.write_u8(u8::from(option_type))?;
    writer.write_u8(0)?;
    writer.write_bytes(&ip.octets())?;
    writer.write_u8(0)?;
    writer.write_u8(u8::try_from(protocol)?)?;
    writer.write_u16_be(port)?;
    Ok(IPV6_OPTION_WIRE_SIZE)
}

/// Extract the first `IpV4Endpoint` (socket address + transport
/// protocol) from a slice of owned options.
///
/// Returns `None` if no `IpV4Endpoint` option is present.
#[must_use]
pub fn extract_ipv4_endpoint(
    options: &[Options],
) -> Option<(core::net::SocketAddrV4, TransportProtocol)> {
    options.iter().find_map(|opt| match opt {
        Options::IpV4Endpoint { ip, protocol, port } => {
            Some((core::net::SocketAddrV4::new(*ip, *port), *protocol))
        }
        _ => None,
    })
}

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

/// Zero-copy view into a variable-length SD option in a buffer.
///
/// Wire layout:
/// - `[0..2]`: length (u16 BE) = `total_size` - 3
/// - `[2]`: option type (u8)
/// - `[3]`: reserved/discard flag (u8)
/// - `[4..]`: type-specific data
#[derive(Clone, Copy, Debug)]
pub struct OptionView<'a>(&'a [u8]);

impl<'a> OptionView<'a> {
    /// Returns the option type.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidOptionType`] if the type byte is unrecognized.
    pub fn option_type(&self) -> Result<OptionType, Error> {
        OptionType::try_from(self.0[OPTION_TYPE_OFFSET])
    }

    /// Total wire size of this option (length field value + `OPTION_LENGTH_SIZE_DELTA`).
    #[must_use]
    pub fn wire_size(&self) -> usize {
        let length = u16::from_be_bytes([self.0[0], self.0[1]]);
        usize::from(length) + OPTION_LENGTH_SIZE_DELTA
    }

    /// Fully validate this option's wire format (type, per-type length, and
    /// transport-protocol byte for IP-bearing options).
    ///
    /// Used by the eager L2 validation walk in
    /// [`SdHeaderView::parse`](super::SdHeaderView::parse) so that its
    /// infallible option accessors can trust the buffer thereafter.
    ///
    /// # Errors
    ///
    /// Returns an error if the option type, length, or transport-protocol byte
    /// is invalid.
    pub(crate) fn validate(&self) -> Result<(), Error> {
        validate_option(self.0).map(|_| ())
    }

    /// A view is only guaranteed to hold the 4-byte option header -- `decode`
    /// is deliberately lazy about the type and per-type length -- so each
    /// accessor that reads a body checks its own span before indexing.
    fn ensure_body_len(&self, needed: usize) -> Result<(), Error> {
        if self.0.len() < needed {
            return Err(Error::IncorrectOptionsSize {
                needed,
                available: self.0.len(),
            });
        }
        Ok(())
    }

    /// Parse as IPv4 endpoint/multicast/SD option.
    /// Returns `(ip, protocol, port)`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidOptionTransportProtocol`] if the protocol byte is unrecognized.
    /// Views obtained via [`SdHeaderView::parse`](super::SdHeaderView::parse) have already
    /// had their protocol byte validated, so this error cannot occur for those callers —
    /// it is retained only to keep the API usable if an `OptionView` is ever constructed
    /// outside the validated parse path.
    pub fn as_ipv4(&self) -> Result<(Ipv4Addr, TransportProtocol, u16), Error> {
        self.ensure_body_len(IPV4_OPTION_WIRE_SIZE)?;
        let ip = Ipv4Addr::from_bits(u32::from_be_bytes([
            self.0[IPV4_OPTION_IP_OFFSET],
            self.0[IPV4_OPTION_IP_OFFSET + 1],
            self.0[IPV4_OPTION_IP_OFFSET + 2],
            self.0[IPV4_OPTION_IP_OFFSET + 3],
        ]));
        let protocol = TransportProtocol::try_from(self.0[IPV4_OPTION_PROTOCOL_OFFSET])?;
        let port = u16::from_be_bytes([
            self.0[IPV4_OPTION_PORT_OFFSET],
            self.0[IPV4_OPTION_PORT_OFFSET + 1],
        ]);
        Ok((ip, protocol, port))
    }

    /// Parse as IPv6 endpoint/multicast/SD option.
    /// Returns `(ip, protocol, port)`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidOptionTransportProtocol`] if the protocol byte is unrecognized.
    /// Views obtained via [`SdHeaderView::parse`](super::SdHeaderView::parse) have already
    /// had their protocol byte validated, so this error cannot occur for those callers —
    /// it is retained only to keep the API usable if an `OptionView` is ever constructed
    /// outside the validated parse path.
    pub fn as_ipv6(&self) -> Result<(Ipv6Addr, TransportProtocol, u16), Error> {
        self.ensure_body_len(IPV6_OPTION_WIRE_SIZE)?;
        let mut octets = [0u8; 16];
        octets.copy_from_slice(&self.0[IPV6_OPTION_IP_OFFSET..IPV6_OPTION_IP_END]);
        let ip = Ipv6Addr::from(octets);
        let protocol = TransportProtocol::try_from(self.0[IPV6_OPTION_PROTOCOL_OFFSET])?;
        let port = u16::from_be_bytes([
            self.0[IPV6_OPTION_PORT_OFFSET],
            self.0[IPV6_OPTION_PORT_OFFSET + 1],
        ]);
        Ok((ip, protocol, port))
    }

    /// Raw configuration bytes (for Configuration options).
    #[must_use]
    pub fn configuration_bytes(&self) -> &'a [u8] {
        let length = u16::from_be_bytes([self.0[0], self.0[1]]);
        let string_len = length.saturating_sub(CONFIGURATION_OPTION_LENGTH_STRING_DELTA);
        &self.0[OPTION_PAYLOAD_OFFSET..OPTION_PAYLOAD_OFFSET + usize::from(string_len)]
    }

    /// Parse as load-balancing option. Returns `(priority, weight)`.
    ///
    /// # Errors
    ///
    /// Currently always succeeds; the `Result` return type is reserved for future validation.
    pub fn as_load_balancing(&self) -> Result<(u16, u16), Error> {
        self.ensure_body_len(LOAD_BALANCING_OPTION_WIRE_SIZE)?;
        let priority = u16::from_be_bytes([
            self.0[OPTION_PAYLOAD_OFFSET],
            self.0[OPTION_PAYLOAD_OFFSET + 1],
        ]);
        let weight = u16::from_be_bytes([
            self.0[OPTION_PAYLOAD_OFFSET + 2],
            self.0[OPTION_PAYLOAD_OFFSET + 3],
        ]);
        Ok((priority, weight))
    }

    /// Converts this view into an owned [`Options`].
    ///
    /// # Errors
    ///
    /// Returns an error if the option type is unrecognized, the transport protocol byte
    /// is invalid, or the configuration string exceeds [`MAX_CONFIGURATION_STRING_LENGTH`].
    ///
    /// # Panics
    ///
    /// Panics if a configuration string passes the length check but fails to fit into the
    /// heapless buffer (unreachable in practice).
    pub fn to_owned(&self) -> Result<Options, Error> {
        let option_type = self.option_type()?;
        match option_type {
            OptionType::Configuration => {
                let config_bytes = self.configuration_bytes();
                if config_bytes.len() > MAX_CONFIGURATION_STRING_LENGTH {
                    return Err(Error::ConfigurationStringTooLong(config_bytes.len()));
                }
                let mut configuration_string =
                    heapless::Vec::<u8, MAX_CONFIGURATION_STRING_LENGTH>::new();
                configuration_string
                    .extend_from_slice(config_bytes)
                    .expect("length validated above");
                Ok(Options::Configuration {
                    configuration_string,
                })
            }
            OptionType::LoadBalancing => {
                let (priority, weight) = self.as_load_balancing()?;
                Ok(Options::LoadBalancing { priority, weight })
            }
            OptionType::IpV4Endpoint => {
                let (ip, protocol, port) = self.as_ipv4()?;
                Ok(Options::IpV4Endpoint { ip, protocol, port })
            }
            OptionType::IpV6Endpoint => {
                let (ip, protocol, port) = self.as_ipv6()?;
                Ok(Options::IpV6Endpoint { ip, protocol, port })
            }
            OptionType::IpV4Multicast => {
                let (ip, protocol, port) = self.as_ipv4()?;
                Ok(Options::IpV4Multicast { ip, protocol, port })
            }
            OptionType::IpV6Multicast => {
                let (ip, protocol, port) = self.as_ipv6()?;
                Ok(Options::IpV6Multicast { ip, protocol, port })
            }
            OptionType::IpV4SD => {
                let (ip, protocol, port) = self.as_ipv4()?;
                Ok(Options::IpV4SD { ip, protocol, port })
            }
            OptionType::IpV6SD => {
                let (ip, protocol, port) = self.as_ipv6()?;
                Ok(Options::IpV6SD { ip, protocol, port })
            }
        }
    }
}

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

    /// Decode a single variable-length SD option from the front of `buf`.
    ///
    /// The stride comes from the option's 2-byte length field. This slices
    /// only; it does NOT validate the option type, per-type length, or
    /// transport-protocol byte. Validation is deferred to the accessors
    /// (`option_type` / `as_ipv4` / `to_owned`) — the L2 validation pass —
    /// keeping this a lazy zero-copy view.
    ///
    /// # Errors
    ///
    /// Returns [`Incomplete`](automotive_wire_codec::Incomplete) if fewer than
    /// the fixed option header remains, or if the declared wire size exceeds
    /// the remaining bytes, and
    /// [`IncorrectOptionsSize`](Error::IncorrectOptionsSize) if the declared
    /// wire size is smaller than the option header itself.
    fn decode(buf: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
        ensure_len(buf, OPTION_HEADER_SIZE)?;
        let length = u16::from_be_bytes([buf[0], buf[1]]);
        let wire_size = usize::from(length) + OPTION_LENGTH_SIZE_DELTA;
        // `wire_size` is `length + 3`, so a declared `length` below 1 produces
        // a view shorter than the 4-byte header this function just required --
        // a view that contradicts its own header. `configuration_bytes` reads
        // from `OPTION_PAYLOAD_OFFSET` unconditionally and would index past the
        // end of such a view. Reject it here so no accessor can see one.
        if wire_size < OPTION_HEADER_SIZE {
            return Err(Error::IncorrectOptionsSize {
                needed: OPTION_HEADER_SIZE,
                available: wire_size,
            }
            .into());
        }
        let (head, rest) = take(buf, wire_size)?;
        Ok((OptionView(head), rest))
    }
}

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

    // Variable stride (from the length field): keep the default WIRE_SIZE = None.

    /// Decode the next option, or `Ok(None)` at a clean end of buffer.
    ///
    /// A partial/truncated trailing option after a good start is surfaced as an
    /// `Err` rather than silently dropped.
    ///
    /// # Errors
    ///
    /// Returns [`Incomplete`](automotive_wire_codec::Incomplete) if a partial
    /// option 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 variable-length SD options in a validated buffer.
/// Options are guaranteed valid (validated upfront in `SdHeaderView::parse`).
///
/// `OptionIter` is a thin wrapper around a borrowed byte slice and is
/// `Clone`, so callers that need to walk the same options multiple
/// times (e.g. to extract the subset referenced by a particular entry's
/// options run) can explicitly clone the iterator. It is deliberately
/// **not** `Copy` — making an iterator `Copy` is a footgun because
/// advancing the original does not advance the hidden copies, which
/// makes "this iterator is already exhausted" invariants easy to break
/// accidentally. Clone when you mean to reuse; don't let the compiler
/// duplicate for you.
#[derive(Clone)]
pub struct OptionIter<'a> {
    remaining: &'a [u8],
}

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

impl<'a> Iterator for OptionIter<'a> {
    type Item = OptionView<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining.len() < OPTION_HEADER_SIZE {
            return None;
        }
        let length = u16::from_be_bytes([self.remaining[0], self.remaining[1]]);
        let wire_size = usize::from(length) + OPTION_LENGTH_SIZE_DELTA;
        if wire_size > self.remaining.len() {
            return None;
        }
        let view = OptionView(&self.remaining[..wire_size]);
        self.remaining = &self.remaining[wire_size..];
        Some(view)
    }
}

/// Validate a single option's wire format and return its wire size.
/// Used during `SdHeaderView::parse` for upfront validation.
///
/// In addition to length/type checks, this validates the transport protocol
/// byte of IP-bearing options so that `OptionView::as_ipv4` / `as_ipv6` on
/// views obtained through `SdHeaderView::parse` cannot observe an unknown
/// protocol byte.
pub(crate) fn validate_option(buf: &[u8]) -> Result<usize, Error> {
    if buf.len() < OPTION_HEADER_SIZE {
        return Err(Error::IncorrectOptionsSize {
            needed: OPTION_HEADER_SIZE,
            available: buf.len(),
        });
    }
    let length = u16::from_be_bytes([buf[0], buf[1]]);
    let wire_size = usize::from(length) + OPTION_LENGTH_SIZE_DELTA;
    if wire_size > buf.len() {
        return Err(Error::IncorrectOptionsSize {
            needed: wire_size,
            available: buf.len(),
        });
    }
    let option_type_byte = buf[OPTION_TYPE_OFFSET];
    let option_type = OptionType::try_from(option_type_byte)?;
    // Validate expected lengths for fixed-size options
    match option_type {
        OptionType::IpV4Endpoint | OptionType::IpV4Multicast | OptionType::IpV4SD => {
            if length != IPV4_OPTION_LENGTH_FIELD {
                return Err(Error::InvalidOptionLength {
                    option_type: option_type_byte,
                    expected: IPV4_OPTION_LENGTH_FIELD,
                    actual: length,
                });
            }
            TransportProtocol::try_from(buf[IPV4_OPTION_PROTOCOL_OFFSET])?;
        }
        OptionType::IpV6Endpoint | OptionType::IpV6Multicast | OptionType::IpV6SD => {
            if length != IPV6_OPTION_LENGTH_FIELD {
                return Err(Error::InvalidOptionLength {
                    option_type: option_type_byte,
                    expected: IPV6_OPTION_LENGTH_FIELD,
                    actual: length,
                });
            }
            TransportProtocol::try_from(buf[IPV6_OPTION_PROTOCOL_OFFSET])?;
        }
        OptionType::LoadBalancing => {
            if length != LOAD_BALANCING_OPTION_LENGTH_FIELD {
                return Err(Error::InvalidOptionLength {
                    option_type: option_type_byte,
                    expected: LOAD_BALANCING_OPTION_LENGTH_FIELD,
                    actual: length,
                });
            }
        }
        OptionType::Configuration => {
            // Configuration strings are variable length; just check it doesn't exceed max
            let string_len = length.saturating_sub(CONFIGURATION_OPTION_LENGTH_STRING_DELTA);
            if usize::from(string_len) > MAX_CONFIGURATION_STRING_LENGTH {
                return Err(Error::ConfigurationStringTooLong(string_len.into()));
            }
        }
    }
    Ok(wire_size)
}

#[cfg(test)]
mod tests {
    use core::net::{Ipv4Addr, Ipv6Addr};

    use super::*;

    // --- Under-length option views (PR #153 review, blocking finding) ---
    //
    // `decode` required OPTION_HEADER_SIZE (4) but then took
    // `length + OPTION_LENGTH_SIZE_DELTA` (3), so a small declared `length`
    // produced a view shorter than the header `decode` had just insisted on,
    // and the accessors indexed it unconditionally.

    /// `length = 0` yields a 3-byte view — shorter than the 4-byte header
    /// `decode` just required. `configuration_bytes` then indexed past its end.
    #[test]
    fn decode_rejects_a_wire_size_below_the_option_header() {
        let buf = [0x00, 0x00, 0x01, 0x00];
        assert!(
            matches!(
                OptionView::decode(&buf),
                Err(crate::protocol::Error::Sd(
                    Error::IncorrectOptionsSize { .. }
                ))
            ),
            "a 3-byte view cannot satisfy the 4-byte option header",
        );
    }

    /// The review's repro: `length = 2` gives a 5-byte view typed as IPv4
    /// Endpoint (0x04), which needs 12.
    #[test]
    fn as_ipv4_rejects_a_view_too_short_for_an_ipv4_option() {
        let buf = [0x00, 0x02, 0x04, 0x00, 0x00];
        let (view, _) = OptionView::decode(&buf).expect("header-sized view decodes");
        assert!(matches!(
            view.as_ipv4(),
            Err(Error::IncorrectOptionsSize { .. })
        ));
    }

    /// Same shape reached through the documented lazy path the review cites.
    #[test]
    fn to_owned_rejects_a_short_ipv4_option_instead_of_panicking() {
        let buf = [0x00, 0x02, 0x04, 0x00, 0x00];
        let (view, _) = OptionView::decode(&buf).expect("header-sized view decodes");
        assert!(view.to_owned().is_err());
    }

    #[test]
    fn as_ipv6_rejects_a_view_too_short_for_an_ipv6_option() {
        let buf = [0x00, 0x02, 0x06, 0x00, 0x00];
        let (view, _) = OptionView::decode(&buf).expect("header-sized view decodes");
        assert!(matches!(
            view.as_ipv6(),
            Err(Error::IncorrectOptionsSize { .. })
        ));
    }

    #[test]
    fn as_load_balancing_rejects_a_view_too_short_for_the_option() {
        let buf = [0x00, 0x02, 0x02, 0x00, 0x00];
        let (view, _) = OptionView::decode(&buf).expect("header-sized view decodes");
        assert!(matches!(
            view.as_load_balancing(),
            Err(Error::IncorrectOptionsSize { .. })
        ));
    }

    /// A well-formed option must keep decoding — the guards must not reject
    /// valid input.
    #[test]
    fn a_well_formed_ipv4_option_still_decodes() {
        let mut buf = [0u8; IPV4_OPTION_WIRE_SIZE];
        buf[0..2].copy_from_slice(&IPV4_OPTION_LENGTH_FIELD.to_be_bytes());
        buf[OPTION_TYPE_OFFSET] = 0x04;
        buf[IPV4_OPTION_PROTOCOL_OFFSET] = 0x11;
        let (view, rest) = OptionView::decode(&buf).expect("valid option decodes");
        assert!(rest.is_empty());
        assert!(view.as_ipv4().is_ok());
    }

    // --- TransportProtocol ---

    #[test]
    fn transport_protocol_tcp_round_trip() {
        assert_eq!(
            TransportProtocol::try_from(0x06).unwrap(),
            TransportProtocol::Tcp
        );
        assert_eq!(u8::try_from(TransportProtocol::Tcp).unwrap(), 0x06);
    }

    #[test]
    fn transport_protocol_invalid_returns_error() {
        assert!(matches!(
            TransportProtocol::try_from(0xFF),
            Err(Error::InvalidOptionTransportProtocol(0xFF))
        ));
    }

    // --- OptionView: parse from encoded bytes ---

    #[test]
    fn option_view_ipv4_endpoint_tcp() {
        let buf: [u8; 12] = [
            0x00, 0x09, // length = 9
            0x04, // type = IpV4Endpoint
            0x00, // discard flag
            192, 168, 0, 1,    // ip
            0x00, // reserved
            0x06, // protocol = TCP
            0x04, 0xD2, // port = 1234
        ];
        let view = OptionView(&buf);
        assert_eq!(view.option_type().unwrap(), OptionType::IpV4Endpoint);
        assert_eq!(view.wire_size(), 12);
        let (ip, protocol, port) = view.as_ipv4().unwrap();
        assert_eq!(ip, Ipv4Addr::new(192, 168, 0, 1));
        assert_eq!(protocol, TransportProtocol::Tcp);
        assert_eq!(port, 1234);
    }

    #[test]
    fn option_view_to_owned_invalid_type() {
        let buf: [u8; 4] = [0x00, 0x00, 0xFF, 0x00]; // type = 0xFF (invalid)
        let view = OptionView(&buf);
        assert!(matches!(
            view.to_owned(),
            Err(Error::InvalidOptionType(0xFF))
        ));
    }

    // --- Round-trip tests for all option types ---

    fn round_trip(option: &Options) {
        let size = option.size();
        let mut buf = [0u8; 4 + MAX_CONFIGURATION_STRING_LENGTH];
        let written = option.encode(&mut &mut buf[..size]).unwrap();
        assert_eq!(written, size);
        let view = OptionView(&buf[..size]);
        let parsed = view.to_owned().unwrap();
        assert_eq!(*option, parsed);
    }

    #[test]
    fn configuration_round_trip() {
        let mut config_string = heapless::Vec::<u8, MAX_CONFIGURATION_STRING_LENGTH>::new();
        config_string.extend_from_slice(b"test=value").unwrap();
        let option = Options::Configuration {
            configuration_string: config_string,
        };
        round_trip(&option);
    }

    #[test]
    fn configuration_empty_round_trip() {
        let option = Options::Configuration {
            configuration_string: heapless::Vec::new(),
        };
        round_trip(&option);
    }

    #[test]
    fn load_balancing_round_trip() {
        let option = Options::LoadBalancing {
            priority: 100,
            weight: 200,
        };
        round_trip(&option);
    }

    #[test]
    fn ipv4_endpoint_round_trip() {
        let option = Options::IpV4Endpoint {
            ip: Ipv4Addr::new(10, 0, 0, 1),
            protocol: TransportProtocol::Udp,
            port: 30490,
        };
        round_trip(&option);
    }

    #[test]
    fn ipv6_endpoint_round_trip() {
        let option = Options::IpV6Endpoint {
            ip: Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1),
            protocol: TransportProtocol::Tcp,
            port: 8080,
        };
        round_trip(&option);
    }

    #[test]
    fn ipv4_multicast_round_trip() {
        let option = Options::IpV4Multicast {
            ip: Ipv4Addr::new(239, 0, 0, 1),
            protocol: TransportProtocol::Udp,
            port: 30490,
        };
        round_trip(&option);
    }

    #[test]
    fn ipv6_multicast_round_trip() {
        let option = Options::IpV6Multicast {
            ip: Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1),
            protocol: TransportProtocol::Udp,
            port: 30490,
        };
        round_trip(&option);
    }

    #[test]
    fn ipv4_sd_round_trip() {
        let option = Options::IpV4SD {
            ip: Ipv4Addr::new(172, 16, 0, 1),
            protocol: TransportProtocol::Udp,
            port: 30490,
        };
        round_trip(&option);
    }

    #[test]
    fn ipv6_sd_round_trip() {
        let option = Options::IpV6SD {
            ip: Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1),
            protocol: TransportProtocol::Tcp,
            port: 9999,
        };
        round_trip(&option);
    }

    // --- Error cases ---

    #[test]
    fn load_balancing_invalid_length_returns_error() {
        // length = 3 (wrong, should be 5), wire_size = 6
        let mut buf = [0u8; 6];
        buf[0] = 0x00;
        buf[1] = 0x03; // length = 3
        buf[2] = 0x02; // type = LoadBalancing
        buf[3] = 0x00; // discard flag
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionLength {
                option_type: 0x02,
                expected: 5,
                actual: 3,
            })
        ));
    }

    #[test]
    fn ipv4_endpoint_invalid_length_returns_error() {
        // length = 5 (wrong, should be 9), wire_size = 8
        let mut buf = [0u8; 8];
        buf[0] = 0x00;
        buf[1] = 0x05; // length = 5
        buf[2] = 0x04; // type = IpV4Endpoint
        buf[3] = 0x00;
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionLength {
                option_type: 0x04,
                expected: 9,
                actual: 5,
            })
        ));
    }

    #[test]
    fn ipv6_endpoint_invalid_length_returns_error() {
        // length = 9 (wrong, should be 21), wire_size = 12
        let mut buf = [0u8; 12];
        buf[0] = 0x00;
        buf[1] = 0x09; // length = 9
        buf[2] = 0x06; // type = IpV6Endpoint
        buf[3] = 0x00;
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionLength {
                option_type: 0x06,
                expected: 21,
                actual: 9,
            })
        ));
    }

    #[test]
    fn ipv4_multicast_invalid_length_returns_error() {
        // length = 5 (wrong, should be 9), wire_size = 8
        let mut buf = [0u8; 8];
        buf[0] = 0x00;
        buf[1] = 0x05;
        buf[2] = 0x14; // type = IpV4Multicast
        buf[3] = 0x00;
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionLength {
                option_type: 0x14,
                expected: 9,
                actual: 5,
            })
        ));
    }

    #[test]
    fn ipv6_multicast_invalid_length_returns_error() {
        // length = 9 (wrong, should be 21), wire_size = 12
        let mut buf = [0u8; 12];
        buf[0] = 0x00;
        buf[1] = 0x09;
        buf[2] = 0x16; // type = IpV6Multicast
        buf[3] = 0x00;
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionLength {
                option_type: 0x16,
                expected: 21,
                actual: 9,
            })
        ));
    }

    #[test]
    fn ipv4_sd_invalid_length_returns_error() {
        // length = 5 (wrong, should be 9), wire_size = 8
        let mut buf = [0u8; 8];
        buf[0] = 0x00;
        buf[1] = 0x05;
        buf[2] = 0x24; // type = IpV4SD
        buf[3] = 0x00;
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionLength {
                option_type: 0x24,
                expected: 9,
                actual: 5,
            })
        ));
    }

    /// Build a well-formed IPv4 option wire buffer (length + type correct) with a
    /// caller-chosen transport protocol byte — used to exercise protocol-byte
    /// validation without hand-rolling wire offsets.
    fn ipv4_option_with_protocol(
        option_type: OptionType,
        protocol_byte: u8,
    ) -> [u8; IPV4_OPTION_WIRE_SIZE] {
        let mut buf = [0u8; IPV4_OPTION_WIRE_SIZE];
        buf[0..2].copy_from_slice(&IPV4_OPTION_LENGTH_FIELD.to_be_bytes());
        buf[OPTION_TYPE_OFFSET] = u8::from(option_type);
        buf[IPV4_OPTION_PROTOCOL_OFFSET] = protocol_byte;
        buf
    }

    /// Build a well-formed IPv6 option wire buffer (length + type correct) with a
    /// caller-chosen transport protocol byte.
    fn ipv6_option_with_protocol(
        option_type: OptionType,
        protocol_byte: u8,
    ) -> [u8; IPV6_OPTION_WIRE_SIZE] {
        let mut buf = [0u8; IPV6_OPTION_WIRE_SIZE];
        buf[0..2].copy_from_slice(&IPV6_OPTION_LENGTH_FIELD.to_be_bytes());
        buf[OPTION_TYPE_OFFSET] = u8::from(option_type);
        buf[IPV6_OPTION_PROTOCOL_OFFSET] = protocol_byte;
        buf
    }

    #[test]
    fn ipv4_endpoint_invalid_transport_protocol_returns_error() {
        let buf = ipv4_option_with_protocol(OptionType::IpV4Endpoint, 0xAB);
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionTransportProtocol(0xAB))
        ));
    }

    #[test]
    fn ipv4_multicast_invalid_transport_protocol_returns_error() {
        let buf = ipv4_option_with_protocol(OptionType::IpV4Multicast, 0x42);
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionTransportProtocol(0x42))
        ));
    }

    #[test]
    fn ipv4_sd_invalid_transport_protocol_returns_error() {
        let buf = ipv4_option_with_protocol(OptionType::IpV4SD, 0x01);
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionTransportProtocol(0x01))
        ));
    }

    #[test]
    fn ipv6_endpoint_invalid_transport_protocol_returns_error() {
        let buf = ipv6_option_with_protocol(OptionType::IpV6Endpoint, 0x99);
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionTransportProtocol(0x99))
        ));
    }

    #[test]
    fn ipv6_multicast_invalid_transport_protocol_returns_error() {
        let buf = ipv6_option_with_protocol(OptionType::IpV6Multicast, 0x00);
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionTransportProtocol(0x00))
        ));
    }

    #[test]
    fn ipv6_sd_invalid_transport_protocol_returns_error() {
        let buf = ipv6_option_with_protocol(OptionType::IpV6SD, 0xFE);
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionTransportProtocol(0xFE))
        ));
    }

    #[test]
    fn ipv6_sd_invalid_length_returns_error() {
        // length = 9 (wrong, should be 21), wire_size = 12
        let mut buf = [0u8; 12];
        buf[0] = 0x00;
        buf[1] = 0x09;
        buf[2] = 0x26; // type = IpV6SD
        buf[3] = 0x00;
        assert!(matches!(
            validate_option(&buf),
            Err(Error::InvalidOptionLength {
                option_type: 0x26,
                expected: 21,
                actual: 9,
            })
        ));
    }

    // --- OptionIter ---

    #[test]
    fn option_iter_empty() {
        let iter = OptionIter::new(&[]);
        assert_eq!(iter.count(), 0);
    }

    #[test]
    fn option_iter_two_options() {
        let opt1 = Options::IpV4Endpoint {
            ip: Ipv4Addr::new(10, 0, 0, 1),
            protocol: TransportProtocol::Udp,
            port: 30490,
        };
        let opt2 = Options::LoadBalancing {
            priority: 100,
            weight: 200,
        };
        let mut buf = [0u8; 24]; // 12 + 8 = 20
        let n1 = opt1.encode(&mut &mut buf[..12]).unwrap();
        let n2 = opt2.encode(&mut &mut buf[12..20]).unwrap();
        let total = n1 + n2;

        let mut iter = OptionIter::new(&buf[..total]);
        let v1 = iter.next().unwrap();
        assert_eq!(v1.to_owned().unwrap(), opt1);
        let v2 = iter.next().unwrap();
        assert_eq!(v2.to_owned().unwrap(), opt2);
        assert!(iter.next().is_none());
    }

    #[test]
    fn option_iter_clone_allows_reuse() {
        // Cloning should snapshot the iterator state — advancing the
        // original must not affect the clone, and the clone must be
        // able to walk the full sequence independently.
        let opt1 = Options::IpV4Endpoint {
            ip: Ipv4Addr::new(10, 0, 0, 1),
            protocol: TransportProtocol::Udp,
            port: 30490,
        };
        let opt2 = Options::IpV4Endpoint {
            ip: Ipv4Addr::new(10, 0, 0, 2),
            protocol: TransportProtocol::Udp,
            port: 30491,
        };
        let mut buf = [0u8; 24];
        let n1 = opt1.encode(&mut &mut buf[..12]).unwrap();
        let n2 = opt2.encode(&mut &mut buf[12..24]).unwrap();
        let total = n1 + n2;

        let iter = OptionIter::new(&buf[..total]);
        let clone = iter.clone();

        // Walk the original: it should produce opt1 then opt2.
        let mut walker = iter;
        let a = walker.next().unwrap().to_owned().unwrap();
        let b = walker.next().unwrap().to_owned().unwrap();
        assert!(walker.next().is_none());
        assert_eq!(a, opt1);
        assert_eq!(b, opt2);

        // The clone is untouched by the original's advance — it still
        // starts from the beginning and yields both options.
        let mut walker2 = clone;
        let a2 = walker2.next().unwrap().to_owned().unwrap();
        let b2 = walker2.next().unwrap().to_owned().unwrap();
        assert!(walker2.next().is_none());
        assert_eq!(a2, opt1);
        assert_eq!(b2, opt2);
    }

    #[test]
    fn option_iter_clone_mid_walk_preserves_position() {
        // After partially walking the original iterator, cloning it
        // should yield a new iterator that starts from the current
        // position of the original — not from the beginning.
        let opt1 = Options::IpV4Endpoint {
            ip: Ipv4Addr::new(10, 0, 0, 1),
            protocol: TransportProtocol::Udp,
            port: 30490,
        };
        let opt2 = Options::IpV4Endpoint {
            ip: Ipv4Addr::new(10, 0, 0, 2),
            protocol: TransportProtocol::Udp,
            port: 30491,
        };
        let mut buf = [0u8; 24];
        let n1 = opt1.encode(&mut &mut buf[..12]).unwrap();
        let n2 = opt2.encode(&mut &mut buf[12..24]).unwrap();
        let total = n1 + n2;

        let mut iter = OptionIter::new(&buf[..total]);
        // Advance past opt1.
        let _ = iter.next().unwrap();

        // Clone from this mid-walk position; the clone should yield
        // only opt2 (and then end).
        let mut clone = iter.clone();
        let remaining = clone.next().unwrap().to_owned().unwrap();
        assert!(clone.next().is_none());
        assert_eq!(remaining, opt2);
    }

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

    fn two_option_buf() -> ([u8; 24], usize, Options, Options) {
        let opt1 = Options::IpV4Endpoint {
            ip: Ipv4Addr::new(10, 0, 0, 1),
            protocol: TransportProtocol::Udp,
            port: 30490,
        };
        let opt2 = Options::LoadBalancing {
            priority: 100,
            weight: 200,
        };
        let mut buf = [0u8; 24];
        let n1 = opt1.encode(&mut &mut buf[..12]).unwrap();
        let n2 = opt2.encode(&mut &mut buf[12..20]).unwrap();
        (buf, n1 + n2, opt1, opt2)
    }

    #[test]
    fn decode_yields_option_and_remainder() {
        let (buf, total, opt1, opt2) = two_option_buf();
        let (view, rest) = OptionView::decode(&buf[..total]).unwrap();
        assert_eq!(view.to_owned().unwrap(), opt1);
        assert_eq!(rest.len(), 8);
        let (view2, rest2) = OptionView::decode(rest).unwrap();
        assert_eq!(view2.to_owned().unwrap(), opt2);
        assert!(rest2.is_empty());
    }

    #[test]
    fn decode_short_header_is_incomplete() {
        assert!(matches!(
            OptionView::decode(&[0x00, 0x09, 0x04]),
            Err(crate::protocol::Error::Incomplete(
                automotive_wire_codec::Incomplete {
                    needed: 4,
                    available: 3,
                }
            ))
        ));
    }

    #[test]
    fn decode_truncated_body_is_incomplete() {
        let (buf, _total, _opt1, _opt2) = two_option_buf();
        // A well-formed 12-byte IPv4 option header declaring 12 bytes, but
        // only 8 present.
        assert!(matches!(
            OptionView::decode(&buf[..8]),
            Err(crate::protocol::Error::Incomplete(
                automotive_wire_codec::Incomplete {
                    needed: 12,
                    available: 8,
                }
            ))
        ));
    }

    #[test]
    fn decode_iter_yields_all_then_none() {
        let (buf, total, opt1, opt2) = two_option_buf();
        let mut iter = OptionView::iter(&buf[..total]);
        assert_eq!(iter.next().unwrap().unwrap().to_owned().unwrap(), opt1);
        assert_eq!(iter.next().unwrap().unwrap().to_owned().unwrap(), opt2);
        assert!(iter.next().is_none());
    }

    #[test]
    fn decode_iter_surfaces_truncated_tail_as_err() {
        let (buf, total, _opt1, _opt2) = two_option_buf();
        // First option (12 bytes) is complete; chop the second short.
        let mut iter = OptionView::iter(&buf[..total - 2]);
        assert!(matches!(iter.next(), Some(Ok(_))));
        assert!(matches!(
            iter.next(),
            Some(Err(crate::protocol::Error::Incomplete(_)))
        ));
        assert!(iter.next().is_none());
    }

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

    #[test]
    fn decode_iter_variable_width_has_no_remaining_len() {
        let (buf, total, _opt1, _opt2) = two_option_buf();
        let iter = OptionView::iter(&buf[..total]);
        assert_eq!(iter.remaining_len(), None);
    }

    #[test]
    fn decode_does_not_validate_option_type() {
        // Option type byte 0xFF is invalid, but decode only slices by length.
        let buf: [u8; 4] = [0x00, 0x01, 0xFF, 0x00]; // length = 1, wire_size = 4
        let (view, rest) = OptionView::decode(&buf).unwrap();
        assert!(rest.is_empty());
        assert!(matches!(
            view.option_type(),
            Err(Error::InvalidOptionType(0xFF))
        ));
    }

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

    #[test]
    fn encoded_size_matches_bytes_written_for_each_variant() {
        use automotive_wire_codec::CountingSink;
        let mut config_string = heapless::Vec::<u8, MAX_CONFIGURATION_STRING_LENGTH>::new();
        config_string.extend_from_slice(b"k=v").unwrap();
        let options = [
            Options::Configuration {
                configuration_string: config_string,
            },
            Options::LoadBalancing {
                priority: 1,
                weight: 2,
            },
            Options::IpV4Endpoint {
                ip: Ipv4Addr::new(10, 0, 0, 1),
                protocol: TransportProtocol::Udp,
                port: 30490,
            },
            Options::IpV6Endpoint {
                ip: Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1),
                protocol: TransportProtocol::Tcp,
                port: 8080,
            },
        ];
        for option in &options {
            let mut sink = CountingSink::new();
            let written = option.encode(&mut sink).unwrap();
            assert_eq!(written, option.encoded_size().unwrap());
            assert_eq!(written, sink.count());
        }
    }

    #[test]
    fn encode_to_slice_too_small_yields_insufficient_buffer() {
        use automotive_wire_codec::{EncodeToSliceError, InsufficientBuffer};
        let option = Options::IpV4Endpoint {
            ip: Ipv4Addr::new(10, 0, 0, 1),
            protocol: TransportProtocol::Udp,
            port: 30490,
        };
        let mut buf = [0u8; 4]; // needs 12
        let err = option.encode_to_slice(&mut buf).unwrap_err();
        assert!(matches!(
            err,
            EncodeToSliceError::InsufficientBuffer(InsufficientBuffer {
                needed: 12,
                available: 4,
            })
        ));
    }
}