server_fn/codec/
postcard.rs1use crate::{
2 codec::{Patch, Post, Put},
3 ContentType, Decodes, Encodes, Format, FormatType,
4};
5use bytes::Bytes;
6use serde::{de::DeserializeOwned, Serialize};
7
8pub struct PostcardEncoding;
10
11impl ContentType for PostcardEncoding {
12 const CONTENT_TYPE: &'static str = "application/x-postcard";
13}
14
15impl FormatType for PostcardEncoding {
16 const FORMAT_TYPE: Format = Format::Binary;
17}
18
19impl<T> Encodes<T> for PostcardEncoding
20where
21 T: Serialize,
22{
23 type Error = postcard::Error;
24
25 fn encode(value: &T) -> Result<Bytes, Self::Error> {
26 postcard::to_allocvec(value).map(Bytes::from)
27 }
28}
29
30impl<T> Decodes<T> for PostcardEncoding
31where
32 T: DeserializeOwned,
33{
34 type Error = postcard::Error;
35
36 fn decode(bytes: Bytes) -> Result<T, Self::Error> {
37 postcard::from_bytes(&bytes)
38 }
39}
40
41pub type Postcard = Post<PostcardEncoding>;
43
44pub type PatchPostcard = Patch<PostcardEncoding>;
48
49pub type PutPostcard = Put<PostcardEncoding>;