Skip to content

Commit b717fbf

Browse files
committed
der: docs: add DecodeValue trait example
1 parent 8da3b40 commit b717fbf

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

der/src/decode.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,36 @@ impl<T: DecodeOwned<Error = Error> + PemLabel> DecodePem for T {
158158
///
159159
/// As opposed to [`Decode`], implementer is expected to read the inner content only,
160160
/// without the [`Header`], which was decoded beforehand.
161+
///
162+
/// ## Example
163+
/// ```
164+
/// use der::{Decode, DecodeValue, ErrorKind, FixedTag, Header, Length, Reader, Tag};
165+
///
166+
/// /// 4-digit year
167+
/// struct MyStringYear(u16);
168+
///
169+
/// impl<'a> DecodeValue<'a> for MyStringYear {
170+
/// type Error = der::Error;
171+
///
172+
/// fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
173+
/// let slice = reader.read_slice(Length::new(4))?;
174+
/// let year = std::str::from_utf8(slice).ok().and_then(|s| s.parse::<u16>().ok());
175+
/// if let Some(year) = year {
176+
/// Ok(Self(year))
177+
/// } else {
178+
/// Err(reader.error(ErrorKind::DateTime))
179+
/// }
180+
/// }
181+
/// }
182+
///
183+
/// impl FixedTag for MyStringYear {
184+
/// const TAG: Tag = Tag::Utf8String;
185+
/// }
186+
///
187+
/// let year = MyStringYear::from_der(b"\x0C\x041670").expect("year to decode");
188+
///
189+
/// assert_eq!(year.0, 1670);
190+
/// ```
161191
pub trait DecodeValue<'a>: Sized {
162192
/// Type returned in the event of a decoding error.
163193
type Error: From<Error> + 'static;

der/src/tag.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ impl<T: FixedTag + ?Sized> Tagged for T {
8686
/// if let Some(year) = year {
8787
/// Ok(Self(year))
8888
/// } else {
89-
/// Err(ErrorKind::DateTime.into())
89+
/// Err(reader.error(ErrorKind::DateTime))
9090
/// }
9191
/// }
9292
/// }

0 commit comments

Comments
 (0)