rspamd_client/backend/
traits.rs

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