Skip to content

Commit 9572368

Browse files
authored
deer: implement Deserialize for &[u8] (#2389)
* feat: import from #1875 * test: byte-string
1 parent 69f39b3 commit 9572368

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

libs/deer/src/impls/core.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
mod array;
22
mod bool;
3+
mod bytes;
34
mod cell;
45
mod cmp;
56
mod floating;

libs/deer/src/impls/core/bytes.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
use core::marker::PhantomData;
2+
3+
use error_stack::ResultExt;
4+
5+
use crate::{
6+
error::{DeserializeError, VisitorError},
7+
Deserialize, Deserializer, Document, Reflection, Schema, Visitor,
8+
};
9+
10+
struct BytesVisitor<'de>(PhantomData<fn() -> &'de ()>);
11+
12+
impl<'de> Visitor<'de> for BytesVisitor<'de> {
13+
type Value = &'de [u8];
14+
15+
fn expecting(&self) -> Document {
16+
Self::Value::reflection()
17+
}
18+
19+
fn visit_borrowed_bytes(self, v: &'de [u8]) -> error_stack::Result<Self::Value, VisitorError> {
20+
Ok(v)
21+
}
22+
}
23+
24+
impl Reflection for [u8] {
25+
fn schema(_: &mut Document) -> Schema {
26+
// this type does not really exist in json-schema :/
27+
// TODO: correct valid schema?
28+
Schema::new("bytes")
29+
}
30+
}
31+
32+
impl<'de> Deserialize<'de> for &'de [u8] {
33+
type Reflection = [u8];
34+
35+
fn deserialize<D: Deserializer<'de>>(de: D) -> error_stack::Result<Self, DeserializeError> {
36+
de.deserialize_bytes(BytesVisitor(PhantomData))
37+
.change_context(DeserializeError)
38+
}
39+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
use deer_desert::{assert_tokens, Token};
2+
3+
// cannot use proptest because tokenizer does not yet support borrowed data
4+
#[test]
5+
fn bytes_ok() {
6+
const EXPECTED: &[u8] = b"This is an example sentence";
7+
8+
assert_tokens(&EXPECTED, &[Token::BorrowedBytes(EXPECTED)]);
9+
}

0 commit comments

Comments
 (0)