mib-rs 0.10.0

SNMP MIB parser and resolver
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
//! Compilation of borrowed MIB metadata into owned index schemas.

use crate::mib::types::{NamedValue, Range};
use crate::mib::{Object, Oid};
use crate::types::BaseType;

use super::constraint::{ConstraintCheck, NormalizedConstraint, normalize_i64, normalize_usize};
use super::value::IndexValueKind;

/// Integer semantics retained by a schema component.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum IntegerIndexKind {
    /// Retains `Integer32` semantics and accepts only non-negative values.
    Integer32,
    /// Retains `Unsigned32` semantics.
    Unsigned32,
    /// Retains `Gauge32` semantics.
    Gauge32,
    /// Retains `TimeTicks` semantics.
    TimeTicks,
    /// Retains mechanically representable `Counter32` compatibility semantics.
    Counter32,
}

impl IntegerIndexKind {
    /// Semantic value kind accepted by this integer component.
    #[must_use]
    pub const fn value_kind(self) -> IndexValueKind {
        match self {
            Self::Integer32 => IndexValueKind::Integer32,
            Self::Unsigned32 => IndexValueKind::Unsigned32,
            Self::Gauge32 => IndexValueKind::Gauge32,
            Self::TimeTicks => IndexValueKind::TimeTicks,
            Self::Counter32 => IndexValueKind::Counter32,
        }
    }

    pub(crate) const fn maximum(self) -> i64 {
        match self {
            Self::Integer32 => i32::MAX as i64,
            Self::Unsigned32 | Self::Gauge32 | Self::TimeTicks | Self::Counter32 => u32::MAX as i64,
        }
    }
}

/// Octet-valued SMI type retained by a schema component.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum OctetIndexKind {
    /// Retains `OCTET STRING` semantics.
    OctetString,
    /// Retains `BITS` semantics.
    Bits,
    /// Retains `Opaque` semantics.
    Opaque,
}

impl OctetIndexKind {
    /// Semantic value kind accepted by this octet component.
    #[must_use]
    pub const fn value_kind(self) -> IndexValueKind {
        match self {
            Self::OctetString => IndexValueKind::OctetString,
            Self::Bits => IndexValueKind::Bits,
            Self::Opaque => IndexValueKind::Opaque,
        }
    }
}

/// Framing of an octet or OBJECT IDENTIFIER index component.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VariableFraming {
    /// Exactly this many value arcs, without a length prefix.
    Fixed(usize),
    /// One length arc followed by the value arcs.
    LengthPrefixed,
    /// The final component consumes the remainder without a prefix.
    Implied,
}

/// Normalized length constraints for octets or OBJECT IDENTIFIER arcs.
pub type LengthConstraint = NormalizedConstraint<usize>;

/// Effective integer range and enumeration restrictions.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IntegerConstraint {
    ranges: NormalizedConstraint<i64>,
    enumeration: Option<Box<[i64]>>,
}

impl IntegerConstraint {
    /// Normalized effective range alternatives.
    #[must_use]
    pub const fn ranges(&self) -> &NormalizedConstraint<i64> {
        &self.ranges
    }

    /// Effective accepted enumeration values, when this is an enumeration.
    #[must_use]
    pub fn enumeration(&self) -> Option<&[i64]> {
        self.enumeration.as_deref()
    }

    /// Check both range and enumeration restrictions.
    #[must_use]
    pub fn check(&self, value: i64) -> ConstraintCheck {
        let range_check = self.ranges.check(&value);
        if range_check == ConstraintCheck::Violation {
            return range_check;
        }
        if let Some(enumeration) = &self.enumeration
            && enumeration.binary_search(&value).is_err()
        {
            return ConstraintCheck::Violation;
        }
        range_check
    }
}

/// Algebraic wire representation for one index component.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IndexWireType {
    /// Encodes an integer-like value in one OID arc.
    Integer {
        /// Identifies the retained SMI integer semantics.
        kind: IntegerIndexKind,
        /// Contains the normalized effective range and enumeration constraints.
        allowed: IntegerConstraint,
    },
    /// Encodes an IPv4 address as four octet-valued arcs.
    IpAddress,
    /// Encodes an octet-valued SMI type with explicit framing rules.
    Octets {
        /// Identifies the retained octet-valued SMI semantics.
        kind: OctetIndexKind,
        /// Specifies how the component boundary is encoded.
        framing: VariableFraming,
        /// Contains normalized effective length constraints measured in octets.
        lengths: LengthConstraint,
    },
    /// Encodes an `OBJECT IDENTIFIER` value with explicit framing rules.
    ObjectIdentifier {
        /// Specifies how the component boundary is encoded.
        framing: VariableFraming,
        /// Contains normalized effective length constraints measured in OID arcs.
        lengths: LengthConstraint,
    },
}

impl IndexWireType {
    /// Semantic value kind required by this component.
    #[must_use]
    pub const fn value_kind(&self) -> IndexValueKind {
        match self {
            Self::Integer { kind, .. } => kind.value_kind(),
            Self::IpAddress => IndexValueKind::IpAddress,
            Self::Octets { kind, .. } => kind.value_kind(),
            Self::ObjectIdentifier { .. } => IndexValueKind::ObjectIdentifier,
        }
    }

    /// Framing for a variable-kind component.
    #[must_use]
    pub const fn framing(&self) -> Option<VariableFraming> {
        match self {
            Self::Octets { framing, .. } | Self::ObjectIdentifier { framing, .. } => Some(*framing),
            Self::Integer { .. } | Self::IpAddress => None,
        }
    }
}

/// Representable MIB deviations and schema concerns retained during compilation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IndexSchemaIssue {
    /// Counter32 is forbidden in INDEX but is mechanically representable.
    Counter32Compatibility,
    /// Part of an integer range or enumeration cannot be encoded in one OID arc.
    UnrepresentableIntegerDomainExcluded,
    /// At least one effective integer-range endpoint is unresolved.
    IncompleteIntegerConstraint,
    /// At least one effective SIZE endpoint is unresolved.
    IncompleteLengthConstraint,
    /// The referenced index object has no resolved numeric OID.
    UnresolvedObjectIdentity,
    /// A fixed-width component consumes no arcs and contributes no identity.
    ZeroWidthComponent,
    /// The complete effective index consumes no arcs and cannot identify rows.
    ZeroWidthIndex,
    /// An implied octet string may be empty, contrary to RFC 2578 section 7.7.
    ImpliedOctetsMayBeEmpty,
}

/// Owned metadata for one effective INDEX component.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IndexComponentSchema {
    name: String,
    object_oid: Option<Oid>,
    wire_type: IndexWireType,
    issues: Box<[IndexSchemaIssue]>,
}

impl IndexComponentSchema {
    /// Identifier written in the effective INDEX clause.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Numeric identity of the referenced object.
    ///
    /// Absent for bare-type indexes and object-backed indexes whose OID could
    /// not be resolved. The latter also records
    /// [`IndexSchemaIssue::UnresolvedObjectIdentity`].
    #[must_use]
    pub const fn object_oid(&self) -> Option<&Oid> {
        self.object_oid.as_ref()
    }

    /// Complete semantic type, framing, and constraints for this component.
    #[must_use]
    pub const fn wire_type(&self) -> &IndexWireType {
        &self.wire_type
    }

    /// Representable deviations discovered during compilation.
    #[must_use]
    pub const fn issues(&self) -> &[IndexSchemaIssue] {
        &self.issues
    }

    /// Semantic value kind required for encoding.
    #[must_use]
    pub const fn value_kind(&self) -> IndexValueKind {
        self.wire_type.value_kind()
    }
}

/// Immutable, owned schema for one effective row INDEX clause.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IndexSchema {
    components: Box<[IndexComponentSchema]>,
    minimum_suffix_arcs: usize,
    maximum_suffix_arcs: Option<usize>,
    issues: Box<[IndexSchemaIssue]>,
}

impl IndexSchema {
    /// Compile a row or column's effective INDEX clause into owned metadata.
    pub fn compile(object: Object<'_>) -> Result<Self, IndexSchemaError> {
        if !object.is_row() && !object.is_column() {
            return Err(IndexSchemaError::NotRowOrColumn {
                object: object.name().to_string(),
            });
        }
        let indexes: Vec<_> = object.effective_indexes().collect();
        if indexes.is_empty() {
            return Err(IndexSchemaError::NoEffectiveIndexes {
                object: object.name().to_string(),
            });
        }

        let component_count = indexes.len();
        let mut components = Vec::with_capacity(component_count);
        for (position, index) in indexes.into_iter().enumerate() {
            let Some(ty) = index.ty() else {
                return Err(IndexSchemaError::UnresolvedType {
                    position,
                    component: index.name().to_string(),
                });
            };
            let base = ty.effective_base();
            if base == BaseType::Unknown {
                return Err(IndexSchemaError::UnresolvedType {
                    position,
                    component: index.name().to_string(),
                });
            }
            if index.implied() && position + 1 != component_count {
                return Err(IndexSchemaError::ImpliedNotLast {
                    position,
                    component: index.name().to_string(),
                });
            }

            let source = ConstraintSource::new(index.object(), ty);
            let mut issues = Vec::new();
            let wire_type = compile_wire_type(
                position,
                index.name(),
                base,
                index.implied(),
                &source,
                &mut issues,
            )?;
            let index_object = index.object();
            let object_oid = index_object
                .and_then(Object::node)
                .map(|node| node.oid().clone());
            if index_object.is_some() && object_oid.is_none() {
                issues.push(IndexSchemaIssue::UnresolvedObjectIdentity);
            }
            components.push(IndexComponentSchema {
                name: index.name().to_string(),
                object_oid,
                wire_type,
                issues: issues.into_boxed_slice(),
            });
        }

        let mut minimum_suffix_arcs = 0usize;
        let mut maximum_suffix_arcs = Some(0usize);
        for component in &components {
            minimum_suffix_arcs = minimum_suffix_arcs
                .checked_add(minimum_width(&component.wire_type))
                .ok_or(IndexSchemaError::MetadataOverflow)?;
            maximum_suffix_arcs = maximum_suffix_arcs
                .zip(maximum_width(&component.wire_type))
                .and_then(|(total, width)| total.checked_add(width));
        }

        let issues = if maximum_suffix_arcs == Some(0) {
            vec![IndexSchemaIssue::ZeroWidthIndex].into_boxed_slice()
        } else {
            Box::new([])
        };

        Ok(Self {
            components: components.into_boxed_slice(),
            minimum_suffix_arcs,
            maximum_suffix_arcs,
            issues,
        })
    }

    /// Effective components in INDEX-clause order.
    #[must_use]
    pub const fn components(&self) -> &[IndexComponentSchema] {
        &self.components
    }

    /// Number of effective components.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.components.len()
    }

    /// Whether the schema has no components. Compiled schemas are never empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.components.is_empty()
    }

    /// Minimum canonical suffix width admitted by the schema.
    #[must_use]
    pub const fn minimum_suffix_arcs(&self) -> usize {
        self.minimum_suffix_arcs
    }

    /// Maximum canonical suffix width when statically known.
    #[must_use]
    pub const fn maximum_suffix_arcs(&self) -> Option<usize> {
        self.maximum_suffix_arcs
    }

    /// Whole-schema concerns discovered during compilation.
    #[must_use]
    pub const fn issues(&self) -> &[IndexSchemaIssue] {
        &self.issues
    }
}

/// Failure to compile deterministic owned index metadata.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum IndexSchemaError {
    /// The requested object is neither a table row nor a table column.
    #[error("object {object} is not a table row or column")]
    NotRowOrColumn {
        /// Names the requested object.
        object: String,
    },
    /// The row or column has no effective index components.
    #[error("object {object} has no effective INDEX clause")]
    NoEffectiveIndexes {
        /// Names the requested row or column.
        object: String,
    },
    /// A component's effective type did not resolve.
    ///
    /// `position` is zero-based in effective `INDEX` clause order.
    #[error("index component {position} ({component}) has no resolved effective type")]
    UnresolvedType {
        /// Contains the component's zero-based position.
        position: usize,
        /// Names the component.
        component: String,
    },
    /// A component uses a base type that the index codec cannot represent.
    ///
    /// `position` is zero-based in effective `INDEX` clause order.
    #[error("index component {position} ({component}) has unsupported base type {base}")]
    UnsupportedBaseType {
        /// Contains the component's zero-based position.
        position: usize,
        /// Names the component.
        component: String,
        /// Contains the unsupported effective base type.
        base: BaseType,
    },
    /// An `IMPLIED` component appears before the final effective component.
    ///
    /// `position` is zero-based in effective `INDEX` clause order.
    #[error("IMPLIED index component {position} ({component}) is not final")]
    ImpliedNotLast {
        /// Contains the component's zero-based position.
        position: usize,
        /// Names the component.
        component: String,
    },
    /// An `IMPLIED` component has a fixed-width value type.
    ///
    /// `position` is zero-based in effective `INDEX` clause order.
    #[error("IMPLIED index component {position} ({component}) is not variable-valued")]
    ImpliedNonVariable {
        /// Contains the component's zero-based position.
        position: usize,
        /// Names the component.
        component: String,
    },
    /// Effective constraints exclude every value representable as index arcs.
    ///
    /// `position` is zero-based in effective `INDEX` clause order.
    #[error("index component {position} ({component}) has no representable values")]
    EmptyRepresentableDomain {
        /// Contains the component's zero-based position.
        position: usize,
        /// Names the component.
        component: String,
    },
    /// Computing the schema's aggregate arc bounds overflowed `usize`.
    #[error("arithmetic overflow while compiling index metadata")]
    MetadataOverflow,
}

struct ConstraintSource<'a> {
    sizes: &'a [Range],
    sizes_constrained: bool,
    ranges: &'a [Range],
    ranges_constrained: bool,
    enums: &'a [NamedValue],
}

impl<'a> ConstraintSource<'a> {
    fn new(object: Option<Object<'a>>, ty: crate::mib::Type<'a>) -> Self {
        if let Some(object) = object {
            Self {
                sizes: object.effective_sizes(),
                sizes_constrained: object.effective_sizes_constrained(),
                ranges: object.effective_ranges(),
                ranges_constrained: object.effective_ranges_constrained(),
                enums: object.effective_enums(),
            }
        } else {
            Self {
                sizes: ty.effective_sizes(),
                sizes_constrained: ty.effective_sizes_constrained(),
                ranges: ty.effective_ranges(),
                ranges_constrained: ty.effective_ranges_constrained(),
                enums: ty.effective_enums(),
            }
        }
    }
}

fn compile_wire_type(
    position: usize,
    component: &str,
    base: BaseType,
    implied: bool,
    source: &ConstraintSource<'_>,
    issues: &mut Vec<IndexSchemaIssue>,
) -> Result<IndexWireType, IndexSchemaError> {
    let integer_kind = match base {
        BaseType::Integer32 => Some(IntegerIndexKind::Integer32),
        BaseType::Unsigned32 => Some(IntegerIndexKind::Unsigned32),
        BaseType::Gauge32 => Some(IntegerIndexKind::Gauge32),
        BaseType::TimeTicks => Some(IntegerIndexKind::TimeTicks),
        BaseType::Counter32 => Some(IntegerIndexKind::Counter32),
        _ => None,
    };
    if let Some(kind) = integer_kind {
        if implied {
            return Err(IndexSchemaError::ImpliedNonVariable {
                position,
                component: component.to_string(),
            });
        }
        if kind == IntegerIndexKind::Counter32 {
            issues.push(IndexSchemaIssue::Counter32Compatibility);
        }
        if source.ranges.iter().any(|range| {
            bound_outside_integer_domain(&range.min, kind.maximum())
                || bound_outside_integer_domain(&range.max, kind.maximum())
        }) || source
            .enums
            .iter()
            .any(|value| !(0..=kind.maximum()).contains(&value.value))
        {
            issues.push(IndexSchemaIssue::UnrepresentableIntegerDomainExcluded);
        }
        let ranges = normalize_i64(source.ranges, source.ranges_constrained, 0, kind.maximum());
        if ranges.is_incomplete() {
            issues.push(IndexSchemaIssue::IncompleteIntegerConstraint);
        }
        if matches!(ranges, NormalizedConstraint::Empty) {
            return Err(IndexSchemaError::EmptyRepresentableDomain {
                position,
                component: component.to_string(),
            });
        }
        let mut enumeration = (!source.enums.is_empty()).then(|| {
            source
                .enums
                .iter()
                .map(|value| value.value)
                .filter(|value| (0..=kind.maximum()).contains(value))
                .filter(|value| ranges.check(value) != ConstraintCheck::Violation)
                .collect::<Vec<_>>()
        });
        if let Some(values) = &mut enumeration {
            values.sort_unstable();
            values.dedup();
            if values.is_empty() {
                return Err(IndexSchemaError::EmptyRepresentableDomain {
                    position,
                    component: component.to_string(),
                });
            }
        }
        return Ok(IndexWireType::Integer {
            kind,
            allowed: IntegerConstraint {
                ranges,
                enumeration: enumeration.map(Vec::into_boxed_slice),
            },
        });
    }

    if base == BaseType::IpAddress {
        if implied {
            return Err(IndexSchemaError::ImpliedNonVariable {
                position,
                component: component.to_string(),
            });
        }
        return Ok(IndexWireType::IpAddress);
    }

    if base == BaseType::Counter64 {
        return Err(IndexSchemaError::UnsupportedBaseType {
            position,
            component: component.to_string(),
            base,
        });
    }

    let lengths = normalize_usize(source.sizes, source.sizes_constrained);
    if matches!(lengths, NormalizedConstraint::Empty) {
        return Err(IndexSchemaError::EmptyRepresentableDomain {
            position,
            component: component.to_string(),
        });
    }
    if lengths.is_incomplete() {
        issues.push(IndexSchemaIssue::IncompleteLengthConstraint);
    }

    if implied
        && matches!(
            base,
            BaseType::OctetString | BaseType::Bits | BaseType::Opaque
        )
        && lengths.exact_value().is_some()
    {
        return Err(IndexSchemaError::ImpliedNonVariable {
            position,
            component: component.to_string(),
        });
    }

    let framing = if implied {
        VariableFraming::Implied
    } else if let Some(&size) = lengths.exact_value() {
        VariableFraming::Fixed(size)
    } else {
        VariableFraming::LengthPrefixed
    };
    match base {
        BaseType::OctetString | BaseType::Bits | BaseType::Opaque => {
            if framing == VariableFraming::Fixed(0) {
                issues.push(IndexSchemaIssue::ZeroWidthComponent);
            }
            if implied && lengths.check(&0) != ConstraintCheck::Violation {
                issues.push(IndexSchemaIssue::ImpliedOctetsMayBeEmpty);
            }
            let kind = match base {
                BaseType::OctetString => OctetIndexKind::OctetString,
                BaseType::Bits => OctetIndexKind::Bits,
                BaseType::Opaque => OctetIndexKind::Opaque,
                _ => unreachable!(),
            };
            Ok(IndexWireType::Octets {
                kind,
                framing,
                lengths,
            })
        }
        BaseType::ObjectIdentifier => Ok(IndexWireType::ObjectIdentifier {
            framing: if implied {
                VariableFraming::Implied
            } else {
                VariableFraming::LengthPrefixed
            },
            lengths,
        }),
        _ => Err(IndexSchemaError::UnsupportedBaseType {
            position,
            component: component.to_string(),
            base,
        }),
    }
}

fn bound_outside_integer_domain(bound: &crate::mib::types::RangeBound, maximum: i64) -> bool {
    match bound {
        crate::mib::types::RangeBound::Signed(value) => !(0..=maximum).contains(value),
        crate::mib::types::RangeBound::Unsigned(value) => *value > maximum as u64,
        crate::mib::types::RangeBound::Min
        | crate::mib::types::RangeBound::Max
        | crate::mib::types::RangeBound::Raw(_) => false,
    }
}

fn minimum_width(wire_type: &IndexWireType) -> usize {
    match wire_type {
        IndexWireType::Integer { .. } => 1,
        IndexWireType::IpAddress => 4,
        IndexWireType::Octets {
            framing, lengths, ..
        }
        | IndexWireType::ObjectIdentifier { framing, lengths } => match framing {
            VariableFraming::Fixed(size) => *size,
            VariableFraming::LengthPrefixed => 1 + minimum_length(lengths),
            VariableFraming::Implied => minimum_length(lengths),
        },
    }
}

fn maximum_width(wire_type: &IndexWireType) -> Option<usize> {
    match wire_type {
        IndexWireType::Integer { .. } => Some(1),
        IndexWireType::IpAddress => Some(4),
        IndexWireType::Octets {
            framing, lengths, ..
        }
        | IndexWireType::ObjectIdentifier { framing, lengths } => match framing {
            VariableFraming::Fixed(size) => Some(*size),
            VariableFraming::LengthPrefixed => lengths
                .proven_maximum()
                .and_then(|maximum| maximum.checked_add(1)),
            VariableFraming::Implied => lengths.proven_maximum().copied(),
        },
    }
}

fn minimum_length(lengths: &LengthConstraint) -> usize {
    match lengths {
        NormalizedConstraint::Known(_) | NormalizedConstraint::Incomplete { .. } => {
            lengths.proven_minimum().copied().unwrap_or(0)
        }
        NormalizedConstraint::Unspecified | NormalizedConstraint::Empty => 0,
    }
}

#[cfg(test)]
mod tests {
    use crate::mib::types::{Range, RangeBound};

    use super::*;

    #[test]
    fn zero_length_oid_remains_length_prefixed() {
        let sizes = [Range {
            min: RangeBound::Unsigned(0),
            max: RangeBound::Unsigned(0),
            range: None,
        }];
        let source = ConstraintSource {
            sizes: &sizes,
            sizes_constrained: true,
            ranges: &[],
            ranges_constrained: false,
            enums: &[],
        };
        let mut issues = Vec::new();
        let wire = compile_wire_type(
            0,
            "oidIndex",
            BaseType::ObjectIdentifier,
            false,
            &source,
            &mut issues,
        )
        .unwrap();

        assert!(matches!(
            wire,
            IndexWireType::ObjectIdentifier {
                framing: VariableFraming::LengthPrefixed,
                ..
            }
        ));
        assert!(!issues.contains(&IndexSchemaIssue::ZeroWidthComponent));
    }
}