Skip to content

Commit 993e442

Browse files
committed
der: add Decode and Encode impls for PhantomData
Allows `PhantomData` fields to be used with custom derive
1 parent 8c29e12 commit 993e442

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

der/src/decode.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Trait definition for [`Decode`].
22
33
use crate::{FixedTag, Header, Reader, Result, SliceReader};
4+
use core::marker::PhantomData;
45

56
#[cfg(feature = "pem")]
67
use crate::{pem::PemLabel, PemReader};
@@ -38,6 +39,18 @@ where
3839
}
3940
}
4041

42+
impl<'a, T> Decode<'a> for PhantomData<T>
43+
where
44+
T: ?Sized,
45+
{
46+
fn decode<R: Reader<'a>>(_reader: &mut R) -> Result<PhantomData<T>> {
47+
Ok(PhantomData)
48+
}
49+
}
50+
51+
/// Dummy implementation for [`PhantomData`] which allows deriving
52+
/// implementations on structs with phantom fields.
53+
4154
/// Marker trait for data structures that can be decoded from DER without
4255
/// borrowing any data from the decoder.
4356
///

der/src/encode.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Trait definition for [`Encode`].
22
33
use crate::{Header, Length, Result, SliceWriter, Tagged, Writer};
4+
use core::marker::PhantomData;
45

56
#[cfg(feature = "alloc")]
67
use {alloc::boxed::Box, alloc::vec::Vec, core::iter};
@@ -82,6 +83,19 @@ where
8283
}
8384
}
8485

86+
impl<T> Encode for PhantomData<T>
87+
where
88+
T: ?Sized,
89+
{
90+
fn encoded_len(&self) -> Result<Length> {
91+
Ok(Length::ZERO)
92+
}
93+
94+
fn encode(&self, _writer: &mut impl Writer) -> Result<()> {
95+
Ok(())
96+
}
97+
}
98+
8599
/// PEM encoding trait.
86100
///
87101
/// This trait is automatically impl'd for any type which impls both

der/tests/derive.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ mod enumerated {
200200
/// Custom derive test cases for the `Sequence` macro.
201201
#[cfg(feature = "oid")]
202202
mod sequence {
203+
use core::marker::PhantomData;
203204
use der::{
204205
asn1::{AnyRef, ObjectIdentifier, SetOf},
205206
Decode, Encode, Sequence, ValueOrd,
@@ -266,6 +267,9 @@ mod sequence {
266267
tag_mode = "IMPLICIT"
267268
)]
268269
pub only_contains_attribute_certs: bool,
270+
271+
/// Test handling of PhantomData.
272+
pub phantom: PhantomData<()>,
269273
}
270274

271275
// Extension as defined in [RFC 5280 Section 4.1.2.9].

0 commit comments

Comments
 (0)