use serde::{Deserialize, Serialize};
use crate::request::Request;
use crate::response::Response;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Message {
Request(Request),
Response(Response),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Batch(Vec<Message>);
impl Batch {
pub fn new() -> Self {
Batch(Vec::new())
}
pub fn with_capacity(capacity: usize) -> Self {
Batch(Vec::with_capacity(capacity))
}
pub fn add_request(&mut self, request: Request) {
self.0.push(Message::Request(request));
}
pub fn add_response(&mut self, response: Response) {
self.0.push(Message::Response(response));
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn as_vec(&self) -> &Vec<Message> {
&self.0
}
pub fn as_vec_mut(&mut self) -> &mut Vec<Message> {
&mut self.0
}
}
impl Message {
pub fn is_request(&self) -> bool {
matches!(self, Message::Request(_))
}
pub fn is_response(&self) -> bool {
matches!(self, Message::Response(_))
}
pub fn as_request(&self) -> Option<&Request> {
match self {
Message::Request(req) => Some(req),
Message::Response(_) => None,
}
}
pub fn as_response(&self) -> Option<&Response> {
match self {
Message::Request(_) => None,
Message::Response(res) => Some(res),
}
}
}
impl std::ops::Deref for Batch {
type Target = Vec<Message>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for Batch {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl IntoIterator for Batch {
type Item = Message;
type IntoIter = std::vec::IntoIter<Message>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> IntoIterator for &'a Batch {
type Item = &'a Message;
type IntoIter = std::slice::Iter<'a, Message>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl<'a> IntoIterator for &'a mut Batch {
type Item = &'a mut Message;
type IntoIter = std::slice::IterMut<'a, Message>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter_mut()
}
}
impl From<Vec<Message>> for Batch {
fn from(vec: Vec<Message>) -> Self {
Batch(vec)
}
}