Skip to main content

server_fn/codec/
postcard.rs

1use crate::{
2    codec::{Patch, Post, Put},
3    ContentType, Decodes, Encodes, Format, FormatType,
4};
5use bytes::Bytes;
6use serde::{de::DeserializeOwned, Serialize};
7
8/// A codec for Postcard.
9pub 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
41/// Pass arguments and receive responses with postcard in a `POST` request.
42pub type Postcard = Post<PostcardEncoding>;
43
44/// Pass arguments and receive responses with postcard in a `PATCH` request.
45/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
46/// Consider using a `POST` request if functionality without JS/WASM is required.
47pub type PatchPostcard = Patch<PostcardEncoding>;
48
49/// Pass arguments and receive responses with postcard in a `PUT` request.
50/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
51/// Consider using a `POST` request if functionality without JS/WASM is required.
52pub type PutPostcard = Put<PostcardEncoding>;