Skip to content

Commit ef0c838

Browse files
authored
der: docs: rename variable encoder -> writer and improve example (#2078)
1 parent d5b06c5 commit ef0c838

File tree

11 files changed

+76
-80
lines changed

11 files changed

+76
-80
lines changed

der/src/asn1/general_string.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ impl EncodeValue for GeneralStringRef<'_> {
3030
self.inner.value_len()
3131
}
3232

33-
fn encode_value(&self, encoder: &mut impl Writer) -> crate::Result<()> {
34-
self.inner.encode_value(encoder)
33+
fn encode_value(&self, writer: &mut impl Writer) -> crate::Result<()> {
34+
self.inner.encode_value(writer)
3535
}
3636
}

der/src/asn1/generalized_time.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -371,9 +371,9 @@ mod tests {
371371
assert_eq!(utc_time.to_unix_duration().as_secs(), 673573540);
372372

373373
let mut buf = [0u8; 128];
374-
let mut encoder = SliceWriter::new(&mut buf);
375-
utc_time.encode(&mut encoder).unwrap();
376-
assert_eq!(example_bytes, encoder.finish().unwrap());
374+
let mut writer = SliceWriter::new(&mut buf);
375+
utc_time.encode(&mut writer).unwrap();
376+
assert_eq!(example_bytes, writer.finish().unwrap());
377377
}
378378

379379
#[test]
@@ -383,9 +383,9 @@ mod tests {
383383
assert_eq!(utc_time.to_unix_duration().as_secs(), 253402300799);
384384

385385
let mut buf = [0u8; 128];
386-
let mut encoder = SliceWriter::new(&mut buf);
387-
utc_time.encode(&mut encoder).unwrap();
388-
assert_eq!(example_bytes, encoder.finish().unwrap());
386+
let mut writer = SliceWriter::new(&mut buf);
387+
utc_time.encode(&mut writer).unwrap();
388+
assert_eq!(example_bytes, writer.finish().unwrap());
389389
}
390390

391391
#[test]

der/src/asn1/integer/int.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -507,21 +507,21 @@ mod tests {
507507
let uint = IntRef::from_der(example).unwrap();
508508

509509
let mut buf = [0u8; 128];
510-
let mut encoder = SliceWriter::new(&mut buf);
511-
uint.encode(&mut encoder).unwrap();
510+
let mut writer = SliceWriter::new(&mut buf);
511+
uint.encode(&mut writer).unwrap();
512512

513-
let result = encoder.finish().unwrap();
513+
let result = writer.finish().unwrap();
514514
assert_eq!(example, result);
515515
}
516516

517517
for &example in &[INEG128_BYTES, INEG129_BYTES, INEG32768_BYTES] {
518518
let uint = IntRef::from_der(example).unwrap();
519519

520520
let mut buf = [0u8; 128];
521-
let mut encoder = SliceWriter::new(&mut buf);
522-
uint.encode(&mut encoder).unwrap();
521+
let mut writer = SliceWriter::new(&mut buf);
522+
uint.encode(&mut writer).unwrap();
523523

524-
let result = encoder.finish().unwrap();
524+
let result = writer.finish().unwrap();
525525
assert_eq!(example, result);
526526
}
527527
}

der/src/asn1/integer/uint.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -353,17 +353,17 @@ pub(super) fn decode_to_array<const N: usize>(bytes: &[u8]) -> Result<[u8; N]> {
353353
}
354354

355355
/// Encode the given big endian bytes representing an integer as ASN.1 DER.
356-
pub(crate) fn encode_bytes<W>(encoder: &mut W, bytes: &[u8]) -> Result<()>
356+
pub(crate) fn encode_bytes<W>(writer: &mut W, bytes: &[u8]) -> Result<()>
357357
where
358358
W: Writer + ?Sized,
359359
{
360360
let bytes = strip_leading_zeroes(bytes);
361361

362362
if needs_leading_zero(bytes) {
363-
encoder.write_byte(0)?;
363+
writer.write_byte(0)?;
364364
}
365365

366-
encoder.write(bytes)
366+
writer.write(bytes)
367367
}
368368

369369
/// Get the encoded length for the given unsigned integer serialized as bytes.
@@ -459,10 +459,10 @@ mod tests {
459459
let uint = UintRef::from_der(example).unwrap();
460460

461461
let mut buf = [0u8; 128];
462-
let mut encoder = SliceWriter::new(&mut buf);
463-
uint.encode(&mut encoder).unwrap();
462+
let mut writer = SliceWriter::new(&mut buf);
463+
uint.encode(&mut writer).unwrap();
464464

465-
let result = encoder.finish().unwrap();
465+
let result = writer.finish().unwrap();
466466
assert_eq!(example, result);
467467
}
468468
}

der/src/asn1/optional.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@ where
6161
}
6262
}
6363

64-
fn encode(&self, encoder: &mut impl Writer) -> Result<(), Error> {
64+
fn encode(&self, writer: &mut impl Writer) -> Result<(), Error> {
6565
match self {
66-
Some(encodable) => encodable.encode(encoder),
66+
Some(encodable) => encodable.encode(writer),
6767
None => Ok(()),
6868
}
6969
}

der/src/asn1/utc_time.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -252,8 +252,8 @@ mod tests {
252252
assert_eq!(utc_time.to_unix_duration().as_secs(), 673573540);
253253

254254
let mut buf = [0u8; 128];
255-
let mut encoder = SliceWriter::new(&mut buf);
256-
utc_time.encode(&mut encoder).unwrap();
257-
assert_eq!(example_bytes, encoder.finish().unwrap());
255+
let mut writer = SliceWriter::new(&mut buf);
256+
utc_time.encode(&mut writer).unwrap();
257+
assert_eq!(example_bytes, writer.finish().unwrap());
258258
}
259259
}

der/src/error.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ use crate::asn1::ObjectIdentifier;
1111
#[cfg(feature = "pem")]
1212
use crate::pem;
1313

14+
#[cfg(doc)]
15+
use crate::{Reader, Writer};
16+
1417
/// Result type.
1518
pub type Result<T> = core::result::Result<T, Error>;
1619

@@ -196,7 +199,7 @@ pub enum ErrorKind {
196199
EncodingRules,
197200

198201
/// This error indicates a previous DER parsing operation resulted in
199-
/// an error and tainted the state of a `Decoder` or `Encoder`.
202+
/// an error and tainted the state of a [`Reader`] or [`Writer`].
200203
///
201204
/// Once this occurs, the overall operation has failed and cannot be
202205
/// subsequently resumed.

der/src/lib.rs

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,8 @@
9595
//! // "heapless" usage when the `alloc` feature is disabled.
9696
//! use der::{
9797
//! asn1::{AnyRef, ObjectIdentifier},
98-
//! DecodeValue, Decode, SliceReader, Encode, Header, Reader, Sequence
98+
//! Decode, DecodeValue, Encode, EncodeValue, Header, Length,
99+
//! Reader, Sequence, SliceReader, Writer
99100
//! };
100101
//!
101102
//! /// X.509 `AlgorithmIdentifier`.
@@ -113,42 +114,34 @@
113114
//! type Error = der::Error;
114115
//!
115116
//! fn decode_value<R: Reader<'a>>(reader: &mut R, _header: Header) -> der::Result<Self> {
116-
//! // The `der::Decoder::Decode` method can be used to decode any
117+
//! // The `der::Decode::decode` method can be used to decode any
117118
//! // type which impls the `Decode` trait, which is impl'd for
118119
//! // all of the ASN.1 built-in types in the `der` crate.
119-
//! //
120-
//! // Note that if your struct's fields don't contain an ASN.1
121-
//! // built-in type specifically, there are also helper methods
122-
//! // for all of the built-in types supported by this library
123-
//! // which can be used to select a specific type.
124-
//! //
125-
//! // For example, another way of decoding this particular field,
126-
//! // which contains an ASN.1 `OBJECT IDENTIFIER`, is by calling
127-
//! // `decoder.oid()`. Similar methods are defined for other
128-
//! // ASN.1 built-in types.
129120
//! let algorithm = reader.decode()?;
130121
//!
131122
//! // This field contains an ASN.1 `OPTIONAL` type. The `der` crate
132123
//! // maps this directly to Rust's `Option` type and provides
133124
//! // impls of the `Decode` and `Encode` traits for `Option`.
134-
//! // To explicitly request an `OPTIONAL` type be decoded, use the
135-
//! // `decoder.optional()` method.
136125
//! let parameters = reader.decode()?;
137126
//!
138-
//! // The value returned from the provided `FnOnce` will be
139-
//! // returned from the `any.sequence(...)` call above.
127+
//! // The value returned from this `decode_value` will be
128+
//! // returned from the `AlgorithmIdentifier::decode` call, unchanged.
140129
//! // Note that the entire sequence body *MUST* be consumed
141130
//! // or an error will be returned.
142131
//! Ok(Self { algorithm, parameters })
143132
//! }
144133
//! }
145134
//!
146-
//! impl<'a> ::der::EncodeValue for AlgorithmIdentifier<'a> {
147-
//! fn value_len(&self) -> ::der::Result<::der::Length> {
135+
//! impl<'a> EncodeValue for AlgorithmIdentifier<'a> {
136+
//! fn value_len(&self) -> der::Result<Length> {
137+
//! // Length of the Value part in Tag-Length-Value structure
138+
//! // is calculated for every TLV header in the tree.
139+
//! // Therefore, in this example `AlgorithmIdentifier::value_len`
140+
//! // will be called once, originating from `Encode::to_der()`.
148141
//! self.algorithm.encoded_len()? + self.parameters.encoded_len()?
149142
//! }
150143
//!
151-
//! fn encode_value(&self, writer: &mut impl ::der::Writer) -> ::der::Result<()> {
144+
//! fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
152145
//! self.algorithm.encode(writer)?;
153146
//! self.parameters.encode(writer)?;
154147
//! Ok(())
@@ -171,15 +164,15 @@
171164
//! // which impls `Sequence` can be serialized by calling `Encode::to_der()`.
172165
//! //
173166
//! // If you would prefer to avoid allocations, you can create a byte array
174-
//! // as backing storage instead, pass that to `der::Encoder::new`, and then
175-
//! // encode the `parameters` value using `encoder.encode(parameters)`.
167+
//! // as backing storage instead, pass that to `der::SliceWriter::new`, and then
168+
//! // encode the `parameters` value using `writer.encode(parameters)`.
176169
//! let der_encoded_parameters = parameters.to_der().unwrap();
177170
//!
178171
//! let algorithm_identifier = AlgorithmIdentifier {
179172
//! // OID for `id-ecPublicKey`, if you're curious
180173
//! algorithm: "1.2.840.10045.2.1".parse().unwrap(),
181174
//!
182-
//! // `Any<'a>` impls `TryFrom<&'a [u8]>`, which parses the provided
175+
//! // `AnyRef<'a>` impls `TryFrom<&'a [u8]>`, which parses the provided
183176
//! // slice as an ASN.1 DER-encoded message.
184177
//! parameters: Some(der_encoded_parameters.as_slice().try_into().unwrap())
185178
//! };
@@ -188,14 +181,14 @@
188181
//! // allocating a `Vec<u8>` for storage.
189182
//! //
190183
//! // As mentioned earlier, if you don't have the `alloc` feature enabled you
191-
//! // can create a fix-sized array instead, then call `Encoder::new` with a
184+
//! // can create a fix-sized array instead, then call `SliceWriter::new` with a
192185
//! // reference to it, then encode the message using
193-
//! // `encoder.encode(algorithm_identifier)`, then finally `encoder.finish()`
186+
//! // `writer.encode(algorithm_identifier)`, then finally `writer.finish()`
194187
//! // to obtain a byte slice containing the encoded message.
195188
//! let der_encoded_algorithm_identifier = algorithm_identifier.to_der().unwrap();
196189
//!
197-
//! // Deserialize the `AlgorithmIdentifier` we just serialized from ASN.1 DER
198-
//! // using `der::Decode::from_bytes`.
190+
//! // Deserialize the `AlgorithmIdentifier` bytes we just serialized from ASN.1 DER
191+
//! // using `der::Decode::from_der`.
199192
//! let decoded_algorithm_identifier = AlgorithmIdentifier::from_der(
200193
//! &der_encoded_algorithm_identifier
201194
//! ).unwrap();

der/src/writer/slice.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ pub struct SliceWriter<'a> {
1919
}
2020

2121
impl<'a> SliceWriter<'a> {
22-
/// Create a new encoder with the given byte slice as a backing buffer.
22+
/// Create a new writer with the given byte slice as a backing buffer.
2323
pub fn new(bytes: &'a mut [u8]) -> Self {
2424
Self {
2525
bytes,
@@ -94,10 +94,10 @@ impl<'a> SliceWriter<'a> {
9494
{
9595
Header::new(Tag::Sequence, length).encode(self)?;
9696

97-
let mut nested_encoder = SliceWriter::new(self.reserve(length)?);
98-
f(&mut nested_encoder)?;
97+
let mut nested_writer = SliceWriter::new(self.reserve(length)?);
98+
f(&mut nested_writer)?;
9999

100-
if nested_encoder.finish()?.len() == usize::try_from(length)? {
100+
if nested_writer.finish()?.len() == usize::try_from(length)? {
101101
Ok(())
102102
} else {
103103
self.error(ErrorKind::Length { tag: Tag::Sequence })

der/tests/datetime.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ proptest! {
3131
let utc_time1 = UtcTime::try_from(datetime).unwrap();
3232

3333
let mut buf = [0u8; 128];
34-
let mut encoder = der::SliceWriter::new(&mut buf);
35-
utc_time1.encode(&mut encoder).unwrap();
36-
let der_bytes = encoder.finish().unwrap();
34+
let mut writer = der::SliceWriter::new(&mut buf);
35+
utc_time1.encode(&mut writer).unwrap();
36+
let der_bytes = writer.finish().unwrap();
3737

3838
let utc_time2 = UtcTime::from_der(der_bytes).unwrap();
3939
prop_assert_eq!(utc_time1, utc_time2);

0 commit comments

Comments
 (0)