Skip to content

der: Simplify Reader trait: peek_8_bytes #1279

@dishmaker

Description

@dishmaker

Continuation from #1228

Reader trait contains too many methods.
All reader methods should return bytes for interoperability and ease of implementation.

Currently peek_header returns der::Header which is a library struct (cyclic dependency).
I think it should be read by der crate itself, not the user crate.

/// Peek forward in the input data, attempting to decode a [`Header`] from
/// the data at the current position in the decoder.
///
/// Does not modify the decoder's state.
fn peek_header(&self) -> Result<Header>;

I've simplified peek_header and peek_byte into one function.

/// Peek at most 8 bytes (3 byte tag + 5 length)
fn peek_bytes(&self) -> &[u8];

Dependency and clone

Also, peek_header is a cyclic dependecy, because reading it requires another reader.
PemReader accompishes it by .clone()ing itself.
That's a bad idea, because it enforced the usage of RefCell - to be clone'able.

pub struct PemReader<'i> {
    /// Inner PEM decoder wrapped in a BufReader.
    reader: RefCell<utils::BufReader<'i>>,

I my implementation there's no need for runtime borrow checks.
https://github.com/dishmaker/formats/blob/master/der/src/reader/pem.rs#L132

pub struct PemReader<'i> {
    /// Inner PEM decoder wrapped in a BufReader.
    reader: utils::BufReader<'i>,

As you can see, everything is simpler with peek_bytes.

Tests

PEM works
dishmaker@8a49da4

dishmaker@dm:~/formats$ cargo test -p der 
Running tests/pem.rs (target/debug/deps/pem)

running 3 tests
test to_pem ... ok
test from_pem ... ok
test from_pem_peek ... ok

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions