Struct bsn1::Der

source ·
pub struct Der { /* private fields */ }
Expand description

Der owns DerRef and represents ASN.1 DER.

The structure of Der is similar to that of Vec<u8>.

User can access the inner DerRef via the Deref and DerefMut implementation.

Implementations§

source§

impl Der

source

pub fn new(id: &IdRef, contents: &ContentsRef) -> Self

Creates a new instance from id and contents.

§Warnings

ASN.1 does not allow some universal identifiers for DER, however, this function accepts such identifiers. For example, ‘Octet String’ must be primitive in DER, but this function will construct a new instance even if id represents constructed ‘Octet String.’

§Panics

Panics if the total length of the return value exceeds isize::MAX.

§Examples
use bsn1::{ContentsRef, Der, IdRef};

let id = IdRef::octet_string();
let contents = <&ContentsRef>::from(&[10, 20, 30]);

let der = Der::new(id, contents);

assert_eq!(id, der.id());
assert_eq!(contents, der.contents());
source

pub fn with_id_length(id: &IdRef, length: usize) -> Self

Creates a new instance with id and ‘definite length’.

The ‘contents octets’ of the return value holds length bytes, but they are not initialized. Use mut_contents via DerefMut implementation to initialize them.

§Warnings

ASN.1 does not allow some universal identifiers for DER, however, this function accepts such identifiers. For example, ‘Octet String’ must be primitive in DER, but this function will construct a new instance even if id represents constructed ‘Octet String.’

§Panics

Panics if the total bytes exceed isize::MAX.

§Examples
use bsn1::{Der, IdRef, Length};

let mut der = Der::with_id_length(IdRef::octet_string(), 5);

assert_eq!(der.id(), IdRef::octet_string());
assert_eq!(der.length(), Length::Definite(5));
assert_eq!(der.contents().len(), 5);

der.mut_contents().as_mut().copy_from_slice(&[1, 2, 3, 4, 5]);
assert_eq!(der.contents().as_ref(), &[1, 2, 3, 4, 5]);
source

pub fn parse<R>(readable: &mut R) -> Result<Self, Error>
where R: ?Sized + Read,

Parses readable starting with DER octets and builds a new instance.

This function ignores extra octet(s) at the end of bytes if any.

On error, the state of readable is unspecified; otherwise, readable is advanced to the end of the DER octets.

§Performance

This function is not so efficient compared with DerRef::parse. If you have a slice of serialized DER, use DerRef::parse and then call Der::from instead.

§Warnings

ASN.1 does not allow some universal identifiers for DER, however, this function accepts such an identifier. For example, ‘Octet String’ must be primitive in DER, but this function returns Ok for constructed Octet String DER.

§Examples
use bsn1::{Der, DerRef};

// Serialize DER of '10' as Integer.
let der = Der::from(10_i32);
let mut serialized = Vec::from(der.as_ref() as &[u8]);

// Deserialize.
let deserialized = Der::parse(&mut &serialized[..]).unwrap();
assert_eq!(der, deserialized);

// Extra octets at the end does not affect the result.
serialized.push(0x00);
serialized.push(0x01);
let deserialized = Der::parse(&mut &serialized[..]).unwrap();

assert_eq!(der, deserialized);

// We can access to the inner slice of `serialized`.
// We can use `DerRef::parse` instead of this function.
// (`DerRef::parse` is more efficient than this function.)
let deserialized: Der = DerRef::parse(&mut &serialized[..]).unwrap().into();
assert_eq!(der, deserialized);
source

pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self

Builds a new instance holding bytes without any check.

bytes must not include any extra octet.

If it is not sure whether bytes are valid octets as an ‘DER’, use parse instead.

§Safety

The behaviour is undefined if bytes is not formatted as a DER.

§Examples
use bsn1::Der;

let der = Der::from(10_i32);
let serialized: &[u8]  = der.as_ref();
let deserialized = unsafe { Der::from_bytes_unchecked(&serialized) };
assert_eq!(der, deserialized);
source

pub unsafe fn from_vec_unchecked(bytes: Vec<u8>) -> Self

Builds a new instance holding bytes without any check.

bytes must not includ any extra octet.

If it is not sure whether bytes are valid octets as an ‘DER’, use parse instead.

§Safety

The behavior is undefined if bytes is not formatted as a DER.

§Examples
use bsn1::Der;

let der = Der::from(5_i32);
let serialized = der.clone().into_vec();
let deserialized = unsafe { Der::from_vec_unchecked(serialized) };

assert_eq!(der, deserialized);
source

pub fn from_id_iterator<I>(id: &IdRef, contents: I) -> Self
where I: Iterator + Clone, I::Item: AsRef<[u8]>,

Creates a new instance containing concatenated contents.

§Warnings

ASN.1 does not allow some universal identifiers for DER, however, this function accepts such an identifier. For example, ‘Octet String’ must be primitive in DER, but this function will construct a new instance even if id represents constructed ‘Octet String.’

§Panics

Panics if the total length of the return value exceeds isize::MAX.

§Examples
use bsn1::{ContentsRef, Der, IdRef};

// Build an sequence DER containing 2 other DERs.
let contents0 = vec![Der::from("foo"), Der::from(29_i32)];
let der0 = Der::from_id_iterator(IdRef::sequence(), contents0.iter());

let mut contents1: Vec<u8> = Der::from("foo").into_vec();
contents1.extend_from_slice(&Der::from(29_i32).into_vec());
let der1 = Der::new(IdRef::sequence(), <&ContentsRef>::from(&contents1[..]));

assert_eq!(der0, der1);

// Build an utf8-string DER using function `from_id_iterator()`.
let contents = vec!["Foo", "Bar"];
let der = Der::from_id_iterator(
            IdRef::utf8_string(), contents.iter().map(|s| s.as_bytes()));
assert_eq!(der, Der::from("FooBar"));
source

pub fn into_vec(self) -> Vec<u8>

Consumes self, returning Vec.

§Examples
use bsn1::Der;

let der = Der::from("foo");
let v = der.clone().into_vec();

assert_eq!(der.as_ref() as &[u8], &v);
source

pub fn push(&mut self, byte: u8)

Appends byte to the end of the ‘contents octets’.

Note that this method may shift the ‘contents octets’, and the performance is O(n) where n is the byte count of ‘contents octets’ in the worst-case, because the byte count of ‘length octets’ may change. (DER is composed of ‘identifier octets’, ‘length octets’ and ‘contents octets’ in this order.)

§Examples
use bsn1::{Der, IdRef, Length};

let bytes: Vec<u8> = (0..10).collect();
let mut der = Der::from(&bytes[..9]);
der.push(bytes[9]);

assert_eq!(der.id(), IdRef::octet_string());
assert_eq!(der.length(), Length::Definite(bytes.len()));
assert_eq!(der.contents().as_ref(), &bytes[..]);
source

pub fn extend_from_slice<T>(&mut self, bytes: &T)
where T: ?Sized + AsRef<[u8]>,

Appends bytes to the end of the ‘contents octets’.

Note that this method may shift the ‘contents octets’, and the performance is O(n) where n is the byte count of ‘contents octets’ in the worst-case, because the byte count of ‘length octets’ may change. (DER is composed of ‘identifier octets’, ‘length octets’ and ‘contents octets’ in this order.)

§Examples
use bsn1::{Der, IdRef, Length};

let bytes: Vec<u8> = (0..10).collect();
let mut der = Der::from(&bytes[..5]);
der.extend_from_slice(&bytes[5..]);

assert_eq!(der.id(), IdRef::octet_string());
assert_eq!(der.length(), Length::Definite(bytes.len()));
assert_eq!(der.contents().as_ref(), &bytes[..]);
source

pub fn truncate(&mut self, new_length: usize)

Enshorten the contents, keeping the first new_length and discarding the rest if new_length is less than the length of the current ‘contents octets’; otherwise, does nothing.

Note that this method may shift the ‘contents octets’, and the performance is O(n) where n is the byte count of ‘contents octets’ in the worst-case, because the byte count of ‘length octets’ may change. (DER is composed of ‘identifier octets’, ‘length octets’ and ‘contents octets’ in this order.)

§Warnings

new_length specifies the length of the ‘contents octets’ after this method returns. The total length of self will be greater than new_length.

§Examples
use bsn1::{Der, IdRef, Length};

// Create a DER of '0..=255' as Octet String.
let bytes: Vec<u8> = (0..=255).collect();
let mut der = Der::from(&bytes[..]);

// Truncate the length
der.truncate(100);

assert_eq!(der.id(), IdRef::octet_string());        // The identifier is not changed.
assert_eq!(der.length(), Length::Definite(100));    // The length is changed.
assert_eq!(der.contents().as_ref(), &bytes[..100]); // The contents is changed.

Methods from Deref<Target = DerRef>§

source

pub fn id(&self) -> &IdRef

Returns a reference to the IdRef of self.

§Examples
use bsn1::{Der, DerRef, IdRef};

let der = Der::from(4_i32);
let der: &DerRef = der.as_ref();
assert_eq!(IdRef::integer(), der.id());
source

pub fn mut_id(&mut self) -> &mut IdRef

Returns a mutable reference to the IdRef of self.

§Examples
use bsn1::{ClassTag, Der, DerRef, PCTag};

let mut der = Der::from(4_i32);
let der: &mut DerRef = der.as_mut();

assert_eq!(der.id().class(), ClassTag::Universal);
der.mut_id().set_class(ClassTag::Private);
assert_eq!(der.id().class(), ClassTag::Private);

assert_eq!(der.id().pc(), PCTag::Primitive);
der.mut_id().set_pc(PCTag::Constructed);
assert_eq!(der.id().pc(), PCTag::Constructed);
source

pub fn length(&self) -> Length

Returns Length of self.

Note that DER does not allow indefinite Length. The return value is always Length::Definite.

§Warnings

Length stands for the length octets in DER: i.e. the length of the ‘contents octets’. The total byte count of the DER is greater than the value.

§Examples
use bsn1::{Der, DerRef, Length};

let der = Der::from("Foo");
let der: &DerRef = der.as_ref();

assert_eq!(Length::Definite("Foo".len()), der.length());
source

pub fn contents(&self) -> &ContentsRef

Returns a reference to the contents octets of self.

§Examples
use bsn1::{Der, DerRef};

let der = Der::from("Foo");
let der: &DerRef = der.as_ref();

assert_eq!(der.contents().as_ref(), "Foo".as_bytes());
source

pub fn mut_contents(&mut self) -> &mut ContentsRef

Returns a mutable reference to the ‘contents octets’ of self.

§Examples
use bsn1::{Der, DerRef};

let mut der = Der::from("Foo");
let der: &mut DerRef = der.as_mut();

assert_eq!(der.contents().as_ref(), "Foo".as_bytes());

der.mut_contents()[0] = 'B' as u8;
assert_eq!(der.contents().as_ref(), "Boo".as_bytes());
source

pub fn disassemble(&self) -> (&IdRef, Length, &ContentsRef)

Returns references to IdRef, Length, and ContentsRef of self.

§Examples
use bsn1::{Der, DerRef, IdRef};

let der = Der::from("Foo");
let der: &DerRef = der.as_ref();

let (id, length, contents) = der.disassemble();

assert_eq!(id, IdRef::utf8_string());
assert_eq!(length.definite().unwrap(), "Foo".len());
assert_eq!(contents.as_ref(), "Foo".as_bytes());
source

pub fn disassemble_mut(&mut self) -> (&mut IdRef, Length, &mut ContentsRef)

Returns mutable references to IdRef, Length, and ContentsRef of self.

§Examples
use bsn1::{Der, DerRef, IdRef};

let mut der = Der::from("Foo");
let der: &mut DerRef = der.as_mut();

let (id, length, contents) = der.disassemble_mut();

assert_eq!(id, IdRef::utf8_string());
assert_eq!(length.definite().unwrap(), "Foo".len());
assert_eq!(contents.as_ref(), "Foo".as_bytes());

contents[0] = 'B' as u8;
assert_eq!(der.contents().as_ref() as &[u8], "Boo".as_bytes());

Trait Implementations§

source§

impl AsMut<DerRef> for Der

source§

fn as_mut(&mut self) -> &mut DerRef

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl AsRef<[u8]> for Der

source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl AsRef<DerRef> for Der

source§

fn as_ref(&self) -> &DerRef

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl Borrow<DerRef> for Der

source§

fn borrow(&self) -> &DerRef

Immutably borrows from an owned value. Read more
source§

impl Clone for Der

source§

fn clone(&self) -> Der

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Der

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Deref for Der

§

type Target = DerRef

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl DerefMut for Der

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl From<&[u8]> for Der

source§

fn from(contents: &[u8]) -> Self

Converts to this type from the input type.
source§

impl From<&DerRef> for Der

source§

fn from(der_ref: &DerRef) -> Self

Converts to this type from the input type.
source§

impl From<&str> for Der

source§

fn from(contents: &str) -> Self

Creates a new instance representing utf8-string containing contents.

source§

impl From<Der> for Ber

source§

fn from(der: Der) -> Self

Converts to this type from the input type.
source§

impl From<bool> for Der

source§

fn from(contents: bool) -> Self

Creates a new instance representing boolean containing contents.

source§

impl From<i128> for Der

source§

fn from(contents: i128) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<i16> for Der

source§

fn from(contents: i16) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<i32> for Der

source§

fn from(contents: i32) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<i64> for Der

source§

fn from(contents: i64) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<i8> for Der

source§

fn from(contents: i8) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<isize> for Der

source§

fn from(contents: isize) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<u128> for Der

source§

fn from(contents: u128) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<u16> for Der

source§

fn from(contents: u16) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<u32> for Der

source§

fn from(contents: u32) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<u64> for Der

source§

fn from(contents: u64) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<u8> for Der

source§

fn from(contents: u8) -> Self

Creates a new instance representing integer containing contents.

source§

impl From<usize> for Der

source§

fn from(contents: usize) -> Self

Creates a new instance representing integer containing contents.

source§

impl Hash for Der

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<T> PartialEq<T> for Der
where T: Borrow<DerRef>,

source§

fn eq(&self, other: &T) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Eq for Der

Auto Trait Implementations§

§

impl Freeze for Der

§

impl RefUnwindSafe for Der

§

impl Send for Der

§

impl Sync for Der

§

impl Unpin for Der

§

impl UnwindSafe for Der

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.