Skip to content

Commit

Permalink
deer: implement Deserialize for core::marker (#2379)
Browse files Browse the repository at this point in the history
* chore: convert from #1875

* test: `PhantomData`
  • Loading branch information
indietyp authored Apr 13, 2023
1 parent 7633fdd commit eac71ae
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions libs/deer/src/impls/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod bool;
mod cmp;
mod floating;
mod integral;
mod marker;
mod mem;
mod non_zero;
mod option;
Expand Down
45 changes: 45 additions & 0 deletions libs/deer/src/impls/core/marker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use core::marker::PhantomData;

use error_stack::{Result, ResultExt};

use crate::{
error::{DeserializeError, VisitorError},
Deserialize, Deserializer, Document, Reflection, Schema, Visitor,
};

struct PhantomDataVisitor<T: ?Sized>(PhantomData<T>);

impl<'de, T: ?Sized> Visitor<'de> for PhantomDataVisitor<T> {
type Value = PhantomData<T>;

fn expecting(&self) -> Document {
Self::Value::reflection()
}

fn visit_none(self) -> Result<Self::Value, VisitorError> {
Ok(PhantomData)
}

fn visit_null(self) -> Result<Self::Value, VisitorError> {
Ok(PhantomData)
}
}

pub struct PhantomDataReflection;

impl Reflection for PhantomDataReflection {
fn schema(_: &mut Document) -> Schema {
// TODO: this is also optional (none)
// currently we're unable to express that constraint (something for 0.2)
Schema::new("null")
}
}

impl<'de, T: ?Sized> Deserialize<'de> for PhantomData<T> {
type Reflection = PhantomDataReflection;

fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, DeserializeError> {
de.deserialize_null(PhantomDataVisitor(Self))
.change_context(DeserializeError)
}
}
8 changes: 8 additions & 0 deletions libs/deer/tests/test_impls_core_marker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use core::marker::PhantomData;

use deer_desert::{assert_tokens, Token};

#[test]
fn phantom_data_ok() {
assert_tokens::<PhantomData<u64>>(&PhantomData, &[Token::Null]);
}

0 comments on commit eac71ae

Please sign in to comment.