poem_openapi/types/
binary.rs1use std::{
2 borrow::Cow,
3 ops::{Deref, DerefMut},
4};
5
6use bytes::Bytes;
7use poem::web::Field;
8
9use crate::{
10 registry::{MetaSchema, MetaSchemaRef},
11 types::{ParseError, ParseFromMultipartField, ParseResult, Type},
12};
13
14#[derive(Debug, Clone, Eq, PartialEq, Hash)]
16pub struct Binary<T>(pub T);
17
18impl<T> Deref for Binary<T> {
19 type Target = T;
20
21 fn deref(&self) -> &Self::Target {
22 &self.0
23 }
24}
25
26impl<T> DerefMut for Binary<T> {
27 fn deref_mut(&mut self) -> &mut Self::Target {
28 &mut self.0
29 }
30}
31
32impl<T: AsRef<[u8]> + Send + Sync> Type for Binary<T> {
33 const IS_REQUIRED: bool = true;
34
35 type RawValueType = Self;
36
37 type RawElementValueType = Self;
38
39 fn name() -> Cow<'static, str> {
40 "string_binary".into()
41 }
42
43 fn schema_ref() -> MetaSchemaRef {
44 MetaSchemaRef::Inline(Box::new(MetaSchema::new_with_format("string", "binary")))
45 }
46
47 fn as_raw_value(&self) -> Option<&Self::RawValueType> {
48 Some(self)
49 }
50
51 fn raw_element_iter<'a>(
52 &'a self,
53 ) -> Box<dyn Iterator<Item = &'a Self::RawElementValueType> + 'a> {
54 Box::new(self.as_raw_value().into_iter())
55 }
56
57 fn is_empty(&self) -> bool {
58 self.0.as_ref().is_empty()
59 }
60}
61
62impl ParseFromMultipartField for Binary<Vec<u8>> {
63 async fn parse_from_multipart(field: Option<Field>) -> ParseResult<Self> {
64 match field {
65 Some(field) => Ok(Self(field.bytes().await.map_err(ParseError::custom)?)),
66 None => Err(ParseError::expected_input()),
67 }
68 }
69}
70
71impl ParseFromMultipartField for Binary<Bytes> {
72 async fn parse_from_multipart(field: Option<Field>) -> ParseResult<Self> {
73 match field {
74 Some(field) => Ok(Self(
75 field
76 .bytes()
77 .await
78 .map(Into::into)
79 .map_err(ParseError::custom)?,
80 )),
81 None => Err(ParseError::expected_input()),
82 }
83 }
84}