Skip to content

Commit 86baf66

Browse files
authored
der: add Decode and Encode impls for PhantomData (#1009)
Allows `PhantomData` fields to be used with custom derive
1 parent 5063989 commit 86baf66

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

der/src/decode.rs

Lines changed: 12 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,17 @@ where
3839
}
3940
}
4041

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

der/src/encode.rs

Lines changed: 16 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,21 @@ where
8283
}
8384
}
8485

86+
/// Dummy implementation for [`PhantomData`] which allows deriving
87+
/// implementations on structs with phantom fields.
88+
impl<T> Encode for PhantomData<T>
89+
where
90+
T: ?Sized,
91+
{
92+
fn encoded_len(&self) -> Result<Length> {
93+
Ok(Length::ZERO)
94+
}
95+
96+
fn encode(&self, _writer: &mut impl Writer) -> Result<()> {
97+
Ok(())
98+
}
99+
}
100+
85101
/// PEM encoding trait.
86102
///
87103
/// 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)