Skip to content

Commit

Permalink
const-oid: add ObjectIdentifier::push_arc (#504)
Browse files Browse the repository at this point in the history
Impl'd as a `const fn`.
  • Loading branch information
tarcieri committed Mar 11, 2022
1 parent 3d96b7f commit d1bed1c
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
19 changes: 14 additions & 5 deletions const-oid/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ enum State {
}

impl Encoder {
/// Create a new encoder initialized to an empty default state
/// Create a new encoder initialized to an empty default state.
pub(crate) const fn new() -> Self {
Self {
state: State::Initial,
Expand All @@ -41,7 +41,16 @@ impl Encoder {
}
}

/// Encode an [`Arc`] as base 128 into the internal buffer
/// Extend an existing OID.
pub(crate) const fn extend(oid: ObjectIdentifier) -> Self {
Self {
state: State::Body,
bytes: oid.bytes,
cursor: oid.length as usize,
}
}

/// Encode an [`Arc`] as base 128 into the internal buffer.
pub(crate) const fn arc(mut self, arc: Arc) -> Result<Self> {
match self.state {
State::Initial => {
Expand Down Expand Up @@ -84,7 +93,7 @@ impl Encoder {
}
}

/// Finish encoding an OID
/// Finish encoding an OID.
pub(crate) const fn finish(self) -> Result<ObjectIdentifier> {
if self.cursor >= 2 {
Ok(ObjectIdentifier {
Expand All @@ -96,7 +105,7 @@ impl Encoder {
}
}

/// Encode a single byte of a base128 value
/// Encode a single byte of a Base 128 value.
const fn encode_base128_byte(mut self, mut n: u32, i: usize, continued: bool) -> Result<Self> {
let mask = if continued { 0b10000000 } else { 0 };

Expand All @@ -116,7 +125,7 @@ impl Encoder {
}
}

/// Compute the length - 1 of an arc when encoded in base 128
/// Compute the length - 1 of an arc when encoded in base 128.
const fn base128_len(arc: Arc) -> usize {
match arc {
0..=0x7f => 0,
Expand Down
9 changes: 9 additions & 0 deletions const-oid/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,15 @@ impl ObjectIdentifier {
pub fn arcs(&self) -> Arcs<'_> {
Arcs::new(self)
}

/// Push an additional arc onto this OID, returning the child OID.
pub const fn push_arc(self, arc: Arc) -> Result<Self> {
// TODO(tarcieri): use `?` when stable in `const fn`
match Encoder::extend(self).arc(arc) {
Ok(encoder) => encoder.finish(),
Err(err) => Err(err),
}
}
}

impl AsRef<[u8]> for ObjectIdentifier {
Expand Down
9 changes: 9 additions & 0 deletions const-oid/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,12 @@ fn parse_invalid_second_arc() {
Err(Error::ArcInvalid { arc: 40 })
);
}

#[test]
fn push_arc() {
let oid = ObjectIdentifier::new_unwrap("1.2.3");
assert_eq!(
oid.push_arc(4).unwrap(),
ObjectIdentifier::new_unwrap("1.2.3.4")
);
}

0 comments on commit d1bed1c

Please sign in to comment.