async-snmp 0.12.0

Modern async-first SNMP client library for 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
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
//! Object Identifier (OID) type.
//!
//! OIDs are stored as `SmallVec<[u32; 16]>` to avoid heap allocation for common OIDs.

use crate::error::internal::DecodeErrorKind;
use crate::error::{Error, Result, UNKNOWN_TARGET};
use smallvec::SmallVec;
use std::fmt;

/// Maximum number of arcs (subidentifiers) allowed in an OID.
///
/// Per RFC 2578 Section 3.5: "there are at most 128 sub-identifiers in a value".
///
/// This limit is enforced during BER decoding via [`Oid::from_ber()`], and can
/// be checked via [`Oid::validate_length()`] for OIDs constructed from other sources.
pub const MAX_OID_LEN: usize = 128;

/// Object Identifier.
///
/// Stored as a sequence of arc values (u32). Uses SmallVec to avoid
/// heap allocation for OIDs with 16 or fewer arcs.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Oid {
    arcs: SmallVec<[u32; 16]>,
}

impl Oid {
    /// Create an empty OID.
    pub fn empty() -> Self {
        Self {
            arcs: SmallVec::new(),
        }
    }

    /// Create an OID from arc values.
    ///
    /// Accepts any iterator of `u32` values.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::oid::Oid;
    ///
    /// // From a Vec
    /// let oid = Oid::new(vec![1, 3, 6, 1, 2, 1]);
    /// assert_eq!(oid.arcs(), &[1, 3, 6, 1, 2, 1]);
    ///
    /// // From an array
    /// let oid = Oid::new([1, 3, 6, 1]);
    /// assert_eq!(oid.len(), 4);
    ///
    /// // From a range
    /// let oid = Oid::new(0..5);
    /// assert_eq!(oid.arcs(), &[0, 1, 2, 3, 4]);
    /// ```
    pub fn new(arcs: impl IntoIterator<Item = u32>) -> Self {
        Self {
            arcs: arcs.into_iter().collect(),
        }
    }

    /// Create an OID from a slice of arcs.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::oid::Oid;
    ///
    /// let arcs = [1, 3, 6, 1, 2, 1, 1, 1, 0];
    /// let oid = Oid::from_slice(&arcs);
    /// assert_eq!(oid.to_string(), "1.3.6.1.2.1.1.1.0");
    ///
    /// // Empty slice creates an empty OID
    /// let empty = Oid::from_slice(&[]);
    /// assert!(empty.is_empty());
    /// ```
    pub fn from_slice(arcs: &[u32]) -> Self {
        Self {
            arcs: SmallVec::from_slice(arcs),
        }
    }

    /// Parse an OID from dotted string notation (e.g., "1.3.6.1.2.1.1.1.0").
    ///
    /// # Validation
    ///
    /// This method parses the string format but does **not** validate arc constraints
    /// per X.690 Section 8.19.4. Invalid OIDs like `"3.0"` (arc1 must be 0, 1, or 2)
    /// or `"0.40"` (arc2 must be ≤39 when arc1 < 2) will parse successfully.
    ///
    /// To validate arc constraints, call [`validate()`](Self::validate) after parsing,
    /// or use [`to_ber_checked()`](Self::to_ber_checked) which validates before encoding.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::oid::Oid;
    ///
    /// // Valid OID
    /// let oid = Oid::parse("1.3.6.1.2.1.1.1.0").unwrap();
    /// assert!(oid.validate().is_ok());
    ///
    /// // Invalid arc1 parses but fails validation
    /// let invalid = Oid::parse("3.0").unwrap();
    /// assert!(invalid.validate().is_err());
    /// ```
    pub fn parse(s: &str) -> Result<Self> {
        // Accept leading-dot notation (e.g. ".1.3.6.1.2.1") used by net-snmp
        // and common in SNMP documentation to indicate absolute OIDs.
        let s = s.strip_prefix('.').unwrap_or(s);

        if s.is_empty() {
            return Ok(Self::empty());
        }

        let mut arcs = SmallVec::new();

        for part in s.split('.') {
            if part.is_empty() {
                return Err(Error::InvalidOid(format!("'{}': empty arc", s).into()).boxed());
            }

            let arc: u32 = part
                .parse()
                .map_err(|_| Error::InvalidOid(format!("'{}': invalid arc", s).into()).boxed())?;

            arcs.push(arc);
        }

        Ok(Self { arcs })
    }

    /// Get the arc values.
    pub fn arcs(&self) -> &[u32] {
        &self.arcs
    }

    /// Get the number of arcs.
    pub fn len(&self) -> usize {
        self.arcs.len()
    }

    /// Check if the OID is empty.
    pub fn is_empty(&self) -> bool {
        self.arcs.is_empty()
    }

    /// Check if this OID starts with another OID.
    ///
    /// Returns `true` if `self` begins with the same arcs as `other`.
    /// An OID always starts with itself, and any OID starts with an empty OID.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::oid::Oid;
    ///
    /// let sys_descr = Oid::parse("1.3.6.1.2.1.1.1.0").unwrap();
    /// let system = Oid::parse("1.3.6.1.2.1.1").unwrap();
    /// let interfaces = Oid::parse("1.3.6.1.2.1.2").unwrap();
    ///
    /// // sysDescr is under the system subtree
    /// assert!(sys_descr.starts_with(&system));
    ///
    /// // sysDescr is not under the interfaces subtree
    /// assert!(!sys_descr.starts_with(&interfaces));
    ///
    /// // Every OID starts with itself
    /// assert!(sys_descr.starts_with(&sys_descr));
    ///
    /// // Every OID starts with the empty OID
    /// assert!(sys_descr.starts_with(&Oid::empty()));
    /// ```
    pub fn starts_with(&self, other: &Oid) -> bool {
        self.arcs.len() >= other.arcs.len() && self.arcs[..other.arcs.len()] == other.arcs[..]
    }

    /// Get the parent OID (all arcs except the last).
    ///
    /// Returns `None` if the OID is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::oid::Oid;
    ///
    /// let sys_descr = Oid::parse("1.3.6.1.2.1.1.1.0").unwrap();
    /// let parent = sys_descr.parent().unwrap();
    /// assert_eq!(parent.to_string(), "1.3.6.1.2.1.1.1");
    ///
    /// // Can chain parent() calls
    /// let grandparent = parent.parent().unwrap();
    /// assert_eq!(grandparent.to_string(), "1.3.6.1.2.1.1");
    ///
    /// // Empty OID has no parent
    /// assert!(Oid::empty().parent().is_none());
    /// ```
    pub fn parent(&self) -> Option<Oid> {
        if self.arcs.is_empty() {
            None
        } else {
            Some(Oid {
                arcs: SmallVec::from_slice(&self.arcs[..self.arcs.len() - 1]),
            })
        }
    }

    /// Create a child OID by appending an arc.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::oid::Oid;
    ///
    /// let system = Oid::parse("1.3.6.1.2.1.1").unwrap();
    ///
    /// // sysDescr is system.1
    /// let sys_descr = system.child(1);
    /// assert_eq!(sys_descr.to_string(), "1.3.6.1.2.1.1.1");
    ///
    /// // sysDescr.0 is the scalar instance
    /// let sys_descr_instance = sys_descr.child(0);
    /// assert_eq!(sys_descr_instance.to_string(), "1.3.6.1.2.1.1.1.0");
    /// ```
    pub fn child(&self, arc: u32) -> Oid {
        let mut arcs = self.arcs.clone();
        arcs.push(arc);
        Oid { arcs }
    }

    /// Strip a prefix OID, returning the remaining arcs as a new Oid.
    ///
    /// Returns `None` if `self` doesn't start with the given prefix.
    /// Follows `str::strip_prefix` semantics - stripping an equal OID returns an empty OID.
    ///
    /// This is useful for extracting table indexes from walked OIDs.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::{oid, Oid};
    ///
    /// let if_descr_5 = oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 5);
    /// let if_descr = oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2);
    ///
    /// // Extract the index
    /// let index = if_descr_5.strip_prefix(&if_descr).unwrap();
    /// assert_eq!(index.arcs(), &[5]);
    ///
    /// // Non-matching prefix returns None
    /// let sys_descr = oid!(1, 3, 6, 1, 2, 1, 1, 1);
    /// assert!(if_descr_5.strip_prefix(&sys_descr).is_none());
    ///
    /// // Equal OIDs return empty
    /// let same = oid!(1, 3, 6);
    /// assert!(same.strip_prefix(&same).unwrap().is_empty());
    ///
    /// // Empty prefix returns self
    /// let any = oid!(1, 2, 3);
    /// assert_eq!(any.strip_prefix(&Oid::empty()).unwrap(), any);
    /// ```
    pub fn strip_prefix(&self, prefix: &Oid) -> Option<Oid> {
        if self.starts_with(prefix) {
            Some(Oid::from_slice(&self.arcs[prefix.len()..]))
        } else {
            None
        }
    }

    /// Get the last N arcs as a slice (for multi-level table indexes).
    ///
    /// Returns `None` if `n` exceeds the OID length.
    ///
    /// This is useful for grouping SNMP table walk results by composite indexes.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::oid;
    ///
    /// // ipNetToMediaPhysAddress has index (ifIndex, IpAddress) = 5 arcs
    /// let oid = oid!(1, 3, 6, 1, 2, 1, 4, 22, 1, 2, 1, 192, 168, 1, 100);
    ///
    /// // Get the 5-arc index (ifIndex=1, IP=192.168.1.100)
    /// let index = oid.suffix(5).unwrap();
    /// assert_eq!(index, &[1, 192, 168, 1, 100]);
    ///
    /// // Get just the last arc
    /// assert_eq!(oid.suffix(1), Some(&[100][..]));
    ///
    /// // suffix(0) returns empty slice
    /// assert_eq!(oid.suffix(0), Some(&[][..]));
    ///
    /// // Too large returns None
    /// assert!(oid.suffix(100).is_none());
    /// ```
    pub fn suffix(&self, n: usize) -> Option<&[u32]> {
        if n <= self.arcs.len() {
            Some(&self.arcs[self.arcs.len() - n..])
        } else {
            None
        }
    }

    /// Validate OID arcs per X.690 Section 8.19.4.
    ///
    /// - arc1 must be 0, 1, or 2
    /// - arc2 must be <= 39 when arc1 is 0 or 1
    /// - arc2 must not cause overflow when computing first subidentifier (arc1*40 + arc2)
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::oid::Oid;
    ///
    /// // Standard SNMP OIDs are valid
    /// let oid = Oid::parse("1.3.6.1.2.1.1.1.0").unwrap();
    /// assert!(oid.validate().is_ok());
    ///
    /// // arc1 must be 0, 1, or 2
    /// let invalid = Oid::from_slice(&[3, 0]);
    /// assert!(invalid.validate().is_err());
    ///
    /// // arc2 must be <= 39 when arc1 is 0 or 1
    /// let invalid = Oid::from_slice(&[0, 40]);
    /// assert!(invalid.validate().is_err());
    ///
    /// // arc2 can be large when arc1 is 2, but must not overflow
    /// let valid = Oid::from_slice(&[2, 999]);
    /// assert!(valid.validate().is_ok());
    /// ```
    pub fn validate(&self) -> Result<()> {
        if self.arcs.is_empty() {
            return Ok(());
        }

        let arc1 = self.arcs[0];

        // arc1 must be 0, 1, or 2
        if arc1 > 2 {
            return Err(Error::InvalidOid(
                format!("first arc must be 0, 1, or 2, got {}", arc1).into(),
            )
            .boxed());
        }

        // Validate arc2 constraints
        if self.arcs.len() >= 2 {
            let arc2 = self.arcs[1];

            // arc2 must be <= 39 when arc1 < 2
            if arc1 < 2 && arc2 >= 40 {
                return Err(Error::InvalidOid(
                    format!(
                        "second arc must be <= 39 when first arc is {}, got {}",
                        arc1, arc2
                    )
                    .into(),
                )
                .boxed());
            }

            // Check that first subidentifier (arc1*40 + arc2) won't overflow u32.
            // Max valid arc2 = u32::MAX - arc1*40
            let base = arc1 * 40;
            if arc2 > u32::MAX - base {
                return Err(
                    Error::InvalidOid("subidentifier overflow in first two arcs".into()).boxed(),
                );
            }
        }

        Ok(())
    }

    /// Validate that the OID doesn't exceed the maximum arc count.
    ///
    /// SNMP implementations commonly limit OIDs to 128 subidentifiers. This check
    /// provides protection against DoS attacks from maliciously long OIDs.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_snmp::oid::{Oid, MAX_OID_LEN};
    ///
    /// let oid = Oid::parse("1.3.6.1.2.1.1.1.0").unwrap();
    /// assert!(oid.validate_length().is_ok());
    ///
    /// // Create an OID with too many arcs
    /// let too_long: Vec<u32> = (0..150).collect();
    /// let long_oid = Oid::new(too_long);
    /// assert!(long_oid.validate_length().is_err());
    /// ```
    pub fn validate_length(&self) -> Result<()> {
        if self.arcs.len() > MAX_OID_LEN {
            return Err(Error::InvalidOid(
                format!(
                    "OID has {} arcs, exceeds maximum {}",
                    self.arcs.len(),
                    MAX_OID_LEN
                )
                .into(),
            )
            .boxed());
        }
        Ok(())
    }

    /// Validate both arc constraints and length.
    ///
    /// Combines [`validate()`](Self::validate) and [`validate_length()`](Self::validate_length).
    pub fn validate_all(&self) -> Result<()> {
        self.validate()?;
        self.validate_length()
    }

    /// Encode to BER format, returning bytes in a stack-allocated buffer.
    ///
    /// Uses SmallVec to avoid heap allocation for OIDs with up to ~20 arcs.
    /// This is the optimized version used internally by encoding routines.
    ///
    /// OID encoding (X.690 Section 8.19):
    /// - First two arcs encoded as (arc1 * 40) + arc2 using base-128
    /// - Remaining arcs encoded as base-128 variable length
    pub(crate) fn to_ber_smallvec(&self) -> SmallVec<[u8; 64]> {
        let mut bytes = SmallVec::new();

        if self.arcs.is_empty() {
            return bytes;
        }

        // First two arcs combined into first subidentifier.
        // Uses base-128 encoding because arc2 can be > 127 when arc1=2.
        encode_subidentifier_smallvec(&mut bytes, first_subidentifier(&self.arcs));

        // Remaining arcs
        for &arc in self.arcs.iter().skip(2) {
            encode_subidentifier_smallvec(&mut bytes, arc);
        }

        bytes
    }

    /// Encode to BER format.
    ///
    /// OID encoding (X.690 Section 8.19):
    /// - First two arcs encoded as (arc1 * 40) + arc2 using base-128
    /// - Remaining arcs encoded as base-128 variable length
    ///
    /// # Empty OID Encoding
    ///
    /// Empty OIDs are encoded as zero bytes (empty content). Note that net-snmp
    /// encodes empty OIDs as `[0x00]` (single zero byte). This difference is
    /// unlikely to matter in practice since empty OIDs are rarely used in SNMP.
    ///
    /// # Validation
    ///
    /// This method does not validate arc constraints. Use [`to_ber_checked()`](Self::to_ber_checked)
    /// for validation, or call [`validate()`](Self::validate) first.
    pub fn to_ber(&self) -> Vec<u8> {
        self.to_ber_smallvec().to_vec()
    }

    /// Encode to BER format with validation.
    ///
    /// Returns an error if the OID has invalid arcs per X.690 Section 8.19.4.
    pub fn to_ber_checked(&self) -> Result<Vec<u8>> {
        self.validate()?;
        Ok(self.to_ber())
    }

    /// Returns the BER content size (excluding tag and length bytes).
    pub(crate) fn ber_content_size(&self) -> usize {
        use crate::ber::base128_len;

        if self.arcs.is_empty() {
            return 0;
        }

        let mut len = 0;

        // First subidentifier (arc1*40 + arc2)
        len += base128_len(first_subidentifier(&self.arcs));

        // Remaining arcs
        for &arc in self.arcs.iter().skip(2) {
            len += base128_len(arc);
        }

        len
    }

    /// Returns the total BER-encoded size (tag + length + content).
    pub(crate) fn ber_encoded_size(&self) -> usize {
        use crate::ber::length_encoded_len;

        let content_len = self.ber_content_size();
        1 + length_encoded_len(content_len) + content_len
    }

    /// Decode from BER format.
    ///
    /// Enforces [`MAX_OID_LEN`] limit per RFC 2578 Section 3.5.
    pub fn from_ber(data: &[u8]) -> Result<Self> {
        if data.is_empty() {
            return Ok(Self::empty());
        }

        let mut arcs = SmallVec::new();

        // Decode first subidentifier (which encodes arc1*40 + arc2)
        // This may be multi-byte for large arc2 values (when arc1=2)
        let (first_subid, consumed) = decode_subidentifier(data)?;

        // Decode first two arcs from the first subidentifier
        if first_subid < 40 {
            arcs.push(0);
            arcs.push(first_subid);
        } else if first_subid < 80 {
            arcs.push(1);
            arcs.push(first_subid - 40);
        } else {
            arcs.push(2);
            arcs.push(first_subid - 80);
        }

        // Decode remaining arcs
        let mut i = consumed;
        while i < data.len() {
            let (arc, bytes_consumed) = decode_subidentifier(&data[i..])?;
            arcs.push(arc);
            i += bytes_consumed;

            // RFC 2578 Section 3.5: "at most 128 sub-identifiers in a value"
            if arcs.len() > MAX_OID_LEN {
                tracing::debug!(target: "async_snmp::oid", { snmp.offset = %i, kind = %DecodeErrorKind::OidTooLong { count: arcs.len(), max: MAX_OID_LEN } }, "OID exceeds maximum arc count");
                return Err(Error::MalformedResponse {
                    target: UNKNOWN_TARGET,
                }
                .boxed());
            }
        }

        Ok(Self { arcs })
    }
}

/// Compute the first OID subidentifier value from an arc slice.
///
/// Per X.690 Section 8.19: the first two arcs are encoded as `arc1 * 40 + arc2`.
/// If there is only one arc, it is encoded as `arc1 * 40`.
#[inline]
fn first_subidentifier(arcs: &SmallVec<[u32; 16]>) -> u32 {
    if arcs.len() >= 2 {
        arcs[0] * 40 + arcs[1]
    } else {
        arcs[0] * 40
    }
}

/// Encode a subidentifier in base-128 variable length into a SmallVec.
#[inline]
fn encode_subidentifier_smallvec(bytes: &mut SmallVec<[u8; 64]>, value: u32) {
    if value == 0 {
        bytes.push(0);
        return;
    }

    // Count how many 7-bit groups we need
    let mut temp = value;
    let mut count = 0;
    while temp > 0 {
        count += 1;
        temp >>= 7;
    }

    // Encode from MSB to LSB
    for i in (0..count).rev() {
        let mut byte = ((value >> (i * 7)) & 0x7F) as u8;
        if i > 0 {
            byte |= 0x80; // Continuation bit
        }
        bytes.push(byte);
    }
}

/// Decode a subidentifier, returning (value, bytes_consumed).
fn decode_subidentifier(data: &[u8]) -> Result<(u32, usize)> {
    let mut value: u32 = 0;
    let mut i = 0;

    loop {
        if i >= data.len() {
            tracing::debug!(target: "async_snmp::oid", { snmp.offset = %i, kind = %DecodeErrorKind::TruncatedData }, "unexpected end of data in OID subidentifier");
            return Err(Error::MalformedResponse {
                target: UNKNOWN_TARGET,
            }
            .boxed());
        }

        let byte = data[i];
        i += 1;

        // Check for overflow before shifting
        if value > (u32::MAX >> 7) {
            tracing::debug!(target: "async_snmp::oid", { snmp.offset = %i, kind = %DecodeErrorKind::IntegerOverflow }, "OID subidentifier overflow");
            return Err(Error::MalformedResponse {
                target: UNKNOWN_TARGET,
            }
            .boxed());
        }

        value = (value << 7) | ((byte & 0x7F) as u32);

        if byte & 0x80 == 0 {
            // Last byte
            break;
        }
    }

    Ok((value, i))
}

impl fmt::Debug for Oid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Oid({})", self)
    }
}

impl fmt::Display for Oid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        for arc in &self.arcs {
            if !first {
                write!(f, ".")?;
            }
            write!(f, "{}", arc)?;
            first = false;
        }
        Ok(())
    }
}

impl std::str::FromStr for Oid {
    type Err = Box<crate::error::Error>;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl From<&[u32]> for Oid {
    fn from(arcs: &[u32]) -> Self {
        Self::from_slice(arcs)
    }
}

impl<const N: usize> From<[u32; N]> for Oid {
    fn from(arcs: [u32; N]) -> Self {
        Self::new(arcs)
    }
}

impl From<Vec<u32>> for Oid {
    fn from(arcs: Vec<u32>) -> Self {
        Self {
            arcs: SmallVec::from_vec(arcs),
        }
    }
}

impl AsRef<[u32]> for Oid {
    fn as_ref(&self) -> &[u32] {
        self.arcs()
    }
}

impl<'a> IntoIterator for &'a Oid {
    type Item = &'a u32;
    type IntoIter = std::slice::Iter<'a, u32>;

    fn into_iter(self) -> Self::IntoIter {
        self.arcs().iter()
    }
}

impl IntoIterator for Oid {
    type Item = u32;
    type IntoIter = smallvec::IntoIter<[u32; 16]>;

    fn into_iter(self) -> Self::IntoIter {
        self.arcs.into_iter()
    }
}

impl PartialOrd for Oid {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Oid {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.arcs.cmp(&other.arcs)
    }
}

/// Macro to create an OID at compile time.
///
/// This is the preferred way to create OID constants since it's concise
/// and avoids parsing overhead.
///
/// # Examples
///
/// ```
/// use async_snmp::oid;
///
/// // Create an OID for sysDescr.0
/// let sys_descr = oid!(1, 3, 6, 1, 2, 1, 1, 1, 0);
/// assert_eq!(sys_descr.to_string(), "1.3.6.1.2.1.1.1.0");
///
/// // Trailing commas are allowed
/// let sys_name = oid!(1, 3, 6, 1, 2, 1, 1, 5, 0,);
///
/// // Can use in const contexts (via from_slice)
/// let interfaces = oid!(1, 3, 6, 1, 2, 1, 2);
/// assert!(sys_descr.starts_with(&oid!(1, 3, 6, 1, 2, 1, 1)));
/// ```
#[macro_export]
macro_rules! oid {
    ($($arc:expr),* $(,)?) => {
        $crate::oid::Oid::from_slice(&[$($arc),*])
    };
}

// ========================================================================
// mib-rs OID conversions (feature = "mib")
// ========================================================================

#[cfg(feature = "mib")]
impl From<&mib_rs::Oid> for Oid {
    fn from(oid: &mib_rs::Oid) -> Self {
        Oid::from_slice(oid.as_ref())
    }
}

#[cfg(feature = "mib")]
impl From<mib_rs::Oid> for Oid {
    fn from(oid: mib_rs::Oid) -> Self {
        Oid::from_slice(oid.as_ref())
    }
}

#[cfg(feature = "mib")]
impl Oid {
    /// Convert to a mib-rs OID.
    ///
    /// This is a method rather than a `From` impl because the orphan rule
    /// prevents implementing `From<&Oid> for mib_rs::Oid` (foreign trait
    /// for foreign type).
    pub fn to_mib_oid(&self) -> mib_rs::Oid {
        mib_rs::Oid::from(self.arcs())
    }
}

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

    #[test]
    fn test_parse() {
        let oid = Oid::parse("1.3.6.1.2.1.1.1.0").unwrap();
        assert_eq!(oid.arcs(), &[1, 3, 6, 1, 2, 1, 1, 1, 0]);
    }

    #[test]
    fn test_parse_leading_dot() {
        let oid = Oid::parse(".1.3.6").unwrap();
        assert_eq!(oid.arcs(), &[1, 3, 6]);

        let oid = Oid::parse(".1.3.6.1.2.1").unwrap();
        assert_eq!(oid.arcs(), &[1, 3, 6, 1, 2, 1]);

        // Leading dot on single arc
        let oid = Oid::parse(".0").unwrap();
        assert_eq!(oid.arcs(), &[0]);

        // Just a dot yields empty OID
        let oid = Oid::parse(".").unwrap();
        assert!(oid.is_empty());
    }

    #[test]
    fn test_parse_rejects_empty_components() {
        assert!(Oid::parse("1.3.6.").is_err()); // Trailing dot
        assert!(Oid::parse("1..3.6").is_err()); // Double dot
        assert!(Oid::parse("..1.3").is_err()); // Double leading dot
        assert!(Oid::parse("...").is_err()); // All dots
    }

    #[test]
    fn test_display() {
        let oid = Oid::from_slice(&[1, 3, 6, 1, 2, 1, 1, 1, 0]);
        assert_eq!(oid.to_string(), "1.3.6.1.2.1.1.1.0");
    }

    #[test]
    fn test_starts_with() {
        let oid = Oid::parse("1.3.6.1.2.1.1.1.0").unwrap();
        let prefix = Oid::parse("1.3.6.1").unwrap();
        assert!(oid.starts_with(&prefix));
        assert!(!prefix.starts_with(&oid));
    }

    #[test]
    fn test_ber_roundtrip() {
        let oid = Oid::parse("1.3.6.1.2.1.1.1.0").unwrap();
        let ber = oid.to_ber();
        let decoded = Oid::from_ber(&ber).unwrap();
        assert_eq!(oid, decoded);
    }

    #[test]
    fn test_ber_encoding() {
        // 1.3.6.1 encodes as: (1*40+3)=43, 6, 1 = [0x2B, 0x06, 0x01]
        let oid = Oid::parse("1.3.6.1").unwrap();
        assert_eq!(oid.to_ber(), vec![0x2B, 0x06, 0x01]);
    }

    #[test]
    fn test_macro() {
        let oid = oid!(1, 3, 6, 1);
        assert_eq!(oid.arcs(), &[1, 3, 6, 1]);
    }

    #[test]
    fn from_vec_u32() {
        let v = vec![1, 3, 6, 1, 2, 1];
        let oid = Oid::from(v);
        assert_eq!(oid.arcs(), &[1, 3, 6, 1, 2, 1]);
    }

    #[test]
    fn oid_as_ref() {
        let oid = Oid::new([1, 3, 6, 1]);
        let slice: &[u32] = oid.as_ref();
        assert_eq!(slice, &[1, 3, 6, 1]);
    }

    // AUDIT-001: Test arc validation
    // X.690 Section 8.19.4: arc1 must be 0, 1, or 2; arc2 must be <= 39 when arc1 < 2
    #[test]
    fn test_validate_arc1_must_be_0_1_or_2() {
        // arc1 = 3 is invalid
        let oid = Oid::from_slice(&[3, 0]);
        let result = oid.validate();
        assert!(result.is_err(), "arc1=3 should be invalid");
    }

    #[test]
    fn test_validate_arc2_limit_when_arc1_is_0() {
        // arc1 = 0, arc2 = 40 is invalid (max is 39)
        let oid = Oid::from_slice(&[0, 40]);
        let result = oid.validate();
        assert!(result.is_err(), "arc2=40 with arc1=0 should be invalid");

        // arc1 = 0, arc2 = 39 is valid
        let oid = Oid::from_slice(&[0, 39]);
        assert!(
            oid.validate().is_ok(),
            "arc2=39 with arc1=0 should be valid"
        );
    }

    #[test]
    fn test_validate_arc2_limit_when_arc1_is_1() {
        // arc1 = 1, arc2 = 40 is invalid
        let oid = Oid::from_slice(&[1, 40]);
        let result = oid.validate();
        assert!(result.is_err(), "arc2=40 with arc1=1 should be invalid");

        // arc1 = 1, arc2 = 39 is valid
        let oid = Oid::from_slice(&[1, 39]);
        assert!(
            oid.validate().is_ok(),
            "arc2=39 with arc1=1 should be valid"
        );
    }

    #[test]
    fn test_validate_arc2_no_limit_when_arc1_is_2() {
        // arc1 = 2, arc2 can be anything (e.g., 999)
        let oid = Oid::from_slice(&[2, 999]);
        assert!(
            oid.validate().is_ok(),
            "arc2=999 with arc1=2 should be valid"
        );
    }

    #[test]
    fn test_to_ber_validates_arcs() {
        // Invalid OID should return error from to_ber_checked
        let oid = Oid::from_slice(&[3, 0]); // arc1=3 is invalid
        let result = oid.to_ber_checked();
        assert!(
            result.is_err(),
            "to_ber_checked should fail for invalid arc1"
        );
    }

    // AUDIT-002: Test first subidentifier encoding for large arc2 values
    // X.690 Section 8.19 example: OID {2 999 3} has first subidentifier = 1079
    #[test]
    fn test_ber_encoding_large_arc2() {
        // OID 2.999.3: first subid = 2*40 + 999 = 1079 = 0x437
        // 1079 in base-128: 0x88 0x37 (continuation bit set on first byte)
        let oid = Oid::from_slice(&[2, 999, 3]);
        let ber = oid.to_ber();
        // First subidentifier 1079 = 0b10000110111 = 7 bits: 0b0110111 (0x37), 7 bits: 0b0001000 (0x08)
        // In base-128: (1079 >> 7) = 8, (1079 & 0x7F) = 55
        // So: 0x88 (8 | 0x80), 0x37 (55)
        assert_eq!(
            ber[0], 0x88,
            "first byte should be 0x88 (8 with continuation)"
        );
        assert_eq!(
            ber[1], 0x37,
            "second byte should be 0x37 (55, no continuation)"
        );
        assert_eq!(ber[2], 0x03, "third byte should be 0x03 (arc 3)");
        assert_eq!(ber.len(), 3, "OID 2.999.3 should encode to 3 bytes");
    }

    #[test]
    fn test_ber_roundtrip_large_arc2() {
        // Ensure roundtrip works for OID with large arc2
        let oid = Oid::from_slice(&[2, 999, 3]);
        let ber = oid.to_ber();
        let decoded = Oid::from_ber(&ber).unwrap();
        assert_eq!(oid, decoded, "roundtrip should preserve OID 2.999.3");
    }

    #[test]
    fn test_ber_encoding_arc2_equals_80() {
        // Edge case: arc1=2, arc2=0 gives first subid = 80, which is exactly 1 byte
        let oid = Oid::from_slice(&[2, 0]);
        let ber = oid.to_ber();
        assert_eq!(ber, vec![80], "OID 2.0 should encode to [80]");
    }

    #[test]
    fn test_ber_encoding_arc2_equals_127() {
        // arc1=2, arc2=47 gives first subid = 127, still fits in 1 byte
        let oid = Oid::from_slice(&[2, 47]);
        let ber = oid.to_ber();
        assert_eq!(ber, vec![127], "OID 2.47 should encode to [127]");
    }

    #[test]
    fn test_ber_encoding_arc2_equals_128_needs_2_bytes() {
        // arc1=2, arc2=48 gives first subid = 128, needs 2 bytes in base-128
        let oid = Oid::from_slice(&[2, 48]);
        let ber = oid.to_ber();
        // 128 = 0x80 = base-128: 0x81 0x00
        assert_eq!(
            ber,
            vec![0x81, 0x00],
            "OID 2.48 should encode to [0x81, 0x00]"
        );
    }

    #[test]
    fn test_from_ber_zero_length() {
        // A zero-length OID content (BER encoding 06 00) is accepted and returns
        // an empty OID. This matches net-snmp's behavior in snmplib/asn1.c which
        // treats the same encoding as 0.0 rather than rejecting it. Our empty OID
        // differs from net-snmp's 0.0 - net-snmp encodes empty OIDs as [0x00]
        // (a single zero byte yielding 0.0), while we produce truly zero arcs.
        // Devices send this when returning endOfMibView with a malformed zero-length
        // OID instead of echoing back the requested OID (RFC 3416 violation).
        let result = Oid::from_ber(&[]);
        assert!(result.is_ok(), "zero-length OID content should be accepted");
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_oid_non_minimal_subidentifier() {
        // Non-minimal subidentifier encoding with leading 0x80 bytes should be accepted
        // 0x80 0x01 should decode as 1 (non-minimal: minimal would be just 0x01)
        // OID: 1.3 followed by arc 1 encoded as 0x80 0x01
        let result = Oid::from_ber(&[0x2B, 0x80, 0x01]);
        assert!(
            result.is_ok(),
            "should accept non-minimal subidentifier 0x80 0x01"
        );
        let oid = result.unwrap();
        assert_eq!(oid.arcs(), &[1, 3, 1]);

        // 0x80 0x80 0x01 should decode as 1 (two leading 0x80 bytes)
        let result = Oid::from_ber(&[0x2B, 0x80, 0x80, 0x01]);
        assert!(
            result.is_ok(),
            "should accept non-minimal subidentifier 0x80 0x80 0x01"
        );
        let oid = result.unwrap();
        assert_eq!(oid.arcs(), &[1, 3, 1]);

        // 0x80 0x00 should decode as 0 (non-minimal zero)
        let result = Oid::from_ber(&[0x2B, 0x80, 0x00]);
        assert!(
            result.is_ok(),
            "should accept non-minimal subidentifier 0x80 0x00"
        );
        let oid = result.unwrap();
        assert_eq!(oid.arcs(), &[1, 3, 0]);
    }

    // Tests for MAX_OID_LEN validation
    #[test]
    fn test_validate_length_within_limit() {
        // OID with MAX_OID_LEN arcs should be valid
        let arcs: Vec<u32> = (0..MAX_OID_LEN as u32).collect();
        let oid = Oid::new(arcs);
        assert!(
            oid.validate_length().is_ok(),
            "OID with exactly MAX_OID_LEN arcs should be valid"
        );
    }

    #[test]
    fn test_validate_length_exceeds_limit() {
        // OID with more than MAX_OID_LEN arcs should fail
        let arcs: Vec<u32> = (0..(MAX_OID_LEN + 1) as u32).collect();
        let oid = Oid::new(arcs);
        let result = oid.validate_length();
        assert!(
            result.is_err(),
            "OID exceeding MAX_OID_LEN should fail validation"
        );
    }

    #[test]
    fn test_validate_all_combines_checks() {
        // Valid OID
        let oid = Oid::from_slice(&[1, 3, 6, 1]);
        assert!(oid.validate_all().is_ok());

        // Invalid arc1 (fails validate)
        let oid = Oid::from_slice(&[3, 0]);
        assert!(oid.validate_all().is_err());

        // Too many arcs (fails validate_length)
        let arcs: Vec<u32> = (0..(MAX_OID_LEN + 1) as u32).collect();
        let oid = Oid::new(arcs);
        assert!(oid.validate_all().is_err());
    }

    #[test]
    fn test_oid_fromstr() {
        // Test basic parsing via FromStr trait
        let oid: Oid = "1.3.6.1.2.1.1.1.0".parse().unwrap();
        assert_eq!(oid, oid!(1, 3, 6, 1, 2, 1, 1, 1, 0));

        // Test empty OID
        let empty: Oid = "".parse().unwrap();
        assert!(empty.is_empty());

        // Test single arc
        let single: Oid = "1".parse().unwrap();
        assert_eq!(single.arcs(), &[1]);

        // Test roundtrip Display -> FromStr
        let original = oid!(1, 3, 6, 1, 4, 1, 9, 9, 42);
        let displayed = original.to_string();
        let parsed: Oid = displayed.parse().unwrap();
        assert_eq!(original, parsed);
    }

    #[test]
    fn test_oid_fromstr_invalid() {
        // Invalid arc value
        assert!("1.3.abc.1".parse::<Oid>().is_err());

        // Negative number (parsed as invalid)
        assert!("1.3.-6.1".parse::<Oid>().is_err());
    }

    // Test for first subidentifier overflow (arc1*40 + arc2 must fit in u32)
    // When arc1=2, arc2 cannot exceed u32::MAX - 80
    #[test]
    fn test_validate_arc2_overflow_when_arc1_is_2() {
        // Maximum valid arc2 when arc1=2: u32::MAX - 80 = 4294967215
        let max_valid_arc2 = u32::MAX - 80;
        let oid = Oid::from_slice(&[2, max_valid_arc2]);
        assert!(
            oid.validate().is_ok(),
            "arc2={} with arc1=2 should be valid (max that fits)",
            max_valid_arc2
        );

        // One more than max should fail validation
        let overflow_arc2 = u32::MAX - 79; // 2*40 + this = u32::MAX + 1
        let oid = Oid::from_slice(&[2, overflow_arc2]);
        assert!(
            oid.validate().is_err(),
            "arc2={} with arc1=2 should be invalid (would overflow first subidentifier)",
            overflow_arc2
        );

        // Also test arc2 = u32::MAX should definitely fail
        let oid = Oid::from_slice(&[2, u32::MAX]);
        assert!(
            oid.validate().is_err(),
            "arc2=u32::MAX with arc1=2 should be invalid"
        );
    }

    #[test]
    fn test_to_ber_checked_rejects_overflow() {
        // Encoding an OID that would overflow should fail via to_ber_checked
        let oid = Oid::from_slice(&[2, u32::MAX]);
        let result = oid.to_ber_checked();
        assert!(
            result.is_err(),
            "to_ber_checked should reject OID that would overflow"
        );
    }

    #[test]
    fn test_from_ber_enforces_max_oid_len() {
        // Create BER data for an OID with more than MAX_OID_LEN arcs
        // OID encoding: first subid encodes arc1*40+arc2, then each subsequent arc
        // First subid gives us 2 arcs (e.g., 1 and 3), so we need MAX_OID_LEN - 2
        // additional arcs to hit exactly MAX_OID_LEN.

        // Build OID at exactly MAX_OID_LEN: 1.3 followed by (MAX_OID_LEN - 2) arcs of value 1
        let mut ber_at_limit = vec![0x2B]; // First subid = 1*40 + 3 = 43 (encodes arc1=1, arc2=3)
        ber_at_limit.extend(std::iter::repeat_n(0x01, MAX_OID_LEN - 2));

        let result = Oid::from_ber(&ber_at_limit);
        assert!(
            result.is_ok(),
            "OID with exactly MAX_OID_LEN arcs should decode successfully"
        );
        assert_eq!(result.unwrap().len(), MAX_OID_LEN);

        // Now one more arc should exceed the limit
        let mut ber_over_limit = vec![0x2B]; // arc1=1, arc2=3
        ber_over_limit.extend(std::iter::repeat_n(0x01, MAX_OID_LEN - 1));

        let result = Oid::from_ber(&ber_over_limit);
        assert!(
            result.is_err(),
            "OID exceeding MAX_OID_LEN should fail to decode"
        );
    }

    // ========================================================================
    // Suffix Extraction Tests
    // ========================================================================

    #[test]
    fn test_strip_prefix() {
        let if_descr_5 = oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 5);
        let if_descr = oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2);

        // Extract the index
        let index = if_descr_5.strip_prefix(&if_descr).unwrap();
        assert_eq!(index.arcs(), &[5]);

        // Non-matching prefix returns None
        let sys_descr = oid!(1, 3, 6, 1, 2, 1, 1, 1);
        assert!(if_descr_5.strip_prefix(&sys_descr).is_none());

        // Equal OIDs return empty
        let same = oid!(1, 3, 6);
        assert!(same.strip_prefix(&same).unwrap().is_empty());

        // Empty prefix returns self
        let any = oid!(1, 2, 3);
        assert_eq!(any.strip_prefix(&Oid::empty()).unwrap(), any);

        // Multi-arc index
        let composite = oid!(1, 3, 6, 1, 2, 1, 4, 22, 1, 2, 1, 192, 168, 1, 100);
        let column = oid!(1, 3, 6, 1, 2, 1, 4, 22, 1, 2);
        let idx = composite.strip_prefix(&column).unwrap();
        assert_eq!(idx.arcs(), &[1, 192, 168, 1, 100]);
    }

    #[test]
    fn test_suffix() {
        let oid = oid!(1, 3, 6, 1, 2, 1, 4, 22, 1, 2, 1, 192, 168, 1, 100);

        // Get the 5-arc index
        assert_eq!(oid.suffix(5), Some(&[1, 192, 168, 1, 100][..]));

        // Get just the last arc
        assert_eq!(oid.suffix(1), Some(&[100][..]));

        // suffix(0) returns empty slice
        assert_eq!(oid.suffix(0), Some(&[][..]));

        // Exact length returns full OID
        assert_eq!(oid.suffix(15), Some(oid.arcs()));

        // Too large returns None
        assert!(oid.suffix(16).is_none());
        assert!(oid.suffix(100).is_none());

        // Empty OID
        let empty = Oid::empty();
        assert_eq!(empty.suffix(0), Some(&[][..]));
        assert!(empty.suffix(1).is_none());
    }

    #[test]
    fn oid_into_iter_ref() {
        let oid = Oid::new([1, 3, 6]);
        let arcs: Vec<&u32> = (&oid).into_iter().collect();
        assert_eq!(arcs, vec![&1, &3, &6]);
    }

    #[test]
    fn oid_into_iter_owned() {
        let oid = Oid::new([1, 3, 6]);
        let arcs: Vec<u32> = oid.into_iter().collect();
        assert_eq!(arcs, vec![1, 3, 6]);
    }

    #[test]
    fn oid_for_loop() {
        let oid = Oid::new([1, 3, 6]);
        let mut sum = 0u32;
        for arc in &oid {
            sum += arc;
        }
        assert_eq!(sum, 10);
    }
}