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
//! Encoders for the Basic Encoding Rules (BER)
//!
//! Free-function wrappers around [`crate::codecs::ber::BerLength`] and
//! [`crate::codecs::ber::BerOid`] that expose a flat function signature
//! compatible with `#[klv(enc = ...)]` attributes. Use these anywhere a
//! `fn(T) -> Vec<u8>` encoder is required.
//!
//! The decode counterparts live in [`crate::codecs::ber::dec`].
//!
//! Author: aav
/// Encodes a value as a BER-encoded length, returning the encoded bytes
///
/// Generic over `T: OfBerCommon`, which covers `u8`..=`u128`. Values less
/// than 128 are encoded in short form (1 byte); larger values use long form
/// where the first byte carries `0x80 | num_bytes`, followed by the value's
/// significant bytes in big-endian order, leading zeros stripped.
///
/// The decode counterpart ([`super::dec::ber_length`]) erases the type to
/// [`usize`]. Use [`crate::codecs::ber::BerLength`] directly for a
/// type-preserving roundtrip that preserves the full `T` precision.
///
/// # Arguments
///
/// * `input` - The unsigned integer length to encode
///
/// # Returns
///
/// A [`Vec<u8>`] containing the BER-encoded representation of the length
///
/// # Example
///
/// ```rust
/// use tinyklv::codecs::ber::enc::ber_length;
///
/// // short form: value < 128
/// assert_eq!(ber_length(47_u64), vec![47]);
///
/// // long form: value >= 128
/// assert_eq!(ber_length(201_u64), vec![128 + 1, 201]);
/// ```
/// Encodes a value as BER-OID variable-length bytes, returning the encoded bytes
///
/// Each 7 bits of the input value occupy one output byte, with the most
/// significant group first. All bytes except the last have their MSB set to 1
/// (continuation); the last byte has MSB 0 (terminator). A value of 0 encodes
/// to a single zero byte.
///
/// # Arguments
///
/// * `input` - The unsigned integer value to encode as a BER-OID
///
/// # Returns
///
/// A [`Vec<u8>`] containing the BER-OID-encoded representation of the value
///
/// # Example
///
/// ```rust
/// use tinyklv::codecs::ber::enc::ber_oid;
///
/// assert_eq!(ber_oid(23298_u64), vec![129, 182, 2]);
/// ```