rspamd_client/backend/
traits.rs1use crate::error::RspamdError;
2use bytes::Bytes;
3use std::collections::HashMap;
4#[cfg(feature = "async")]
5use std::pin::Pin;
6#[cfg(feature = "async")]
7use tokio_stream::Stream;
8
9#[cfg(feature = "async")]
10pub type StreamItem = Result<Bytes, RspamdError>;
11
12#[cfg(feature = "async")]
13pub type DataStream = Pin<Box<dyn Stream<Item = StreamItem> + Send>>;
14#[cfg(feature = "async")]
15pub struct ResponseDataStream {
16 pub bytes: DataStream,
17 pub status_code: u16,
18}
19
20#[derive(Debug)]
22pub struct ResponseData {
23 bytes: Bytes,
24 status_code: u16,
25 headers: HashMap<String, String>,
26}
27
28#[cfg(feature = "async")]
29impl ResponseDataStream {
30 pub fn bytes(&mut self) -> &mut DataStream {
31 &mut self.bytes
32 }
33}
34
35impl From<ResponseData> for Vec<u8> {
36 fn from(data: ResponseData) -> Vec<u8> {
37 data.to_vec()
38 }
39}
40
41impl ResponseData {
42 pub fn new(bytes: Bytes, status_code: u16, headers: HashMap<String, String>) -> ResponseData {
43 ResponseData {
44 bytes,
45 status_code,
46 headers,
47 }
48 }
49
50 pub fn as_slice(&self) -> &[u8] {
51 &self.bytes
52 }
53
54 pub fn to_vec(self) -> Vec<u8> {
55 self.bytes.to_vec()
56 }
57
58 pub fn bytes(&self) -> &Bytes {
59 &self.bytes
60 }
61
62 pub fn bytes_mut(&mut self) -> &mut Bytes {
63 &mut self.bytes
64 }
65
66 pub fn into_bytes(self) -> Bytes {
67 self.bytes
68 }
69
70 pub fn status_code(&self) -> u16 {
71 self.status_code
72 }
73
74 pub fn as_str(&self) -> Result<&str, std::str::Utf8Error> {
75 std::str::from_utf8(self.as_slice())
76 }
77
78 pub fn to_string(&self) -> Result<String, std::str::Utf8Error> {
79 std::str::from_utf8(self.as_slice()).map(|s| s.to_string())
80 }
81
82 pub fn headers(&self) -> HashMap<String, String> {
83 self.headers.clone()
84 }
85}
86
87use std::fmt;
88
89impl fmt::Display for ResponseData {
90 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
91 write!(
92 f,
93 "Status code: {}\n Data: {}",
94 self.status_code(),
95 self.to_string()
96 .unwrap_or_else(|_| "Data could not be cast to UTF string".to_string())
97 )
98 }
99}
100
101#[maybe_async::maybe_async]
103pub trait Request {
104 type Body;
105 type HeaderMap;
106
107 async fn response(self) -> Result<(Self::HeaderMap, Self::Body), RspamdError>;
109}