use crate::anyvec::AnyVec;
use crate::coding::encoder::{PacketLenIter, TopicsIter, U16Iter, U8Iter, Unit};
use crate::coding::length::Length;
use crate::coding::{Decoder, Encoder};
use crate::err;
use crate::error::{Data, DecoderError, MemoryError};
use crate::packets::TryFromIterator;
use core::iter::Chain;
use core::marker::PhantomData;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unsubscribe<Seq, Bytes> {
packet_id: u16,
topics: Seq,
_vec: PhantomData<Bytes>,
}
impl<Seq, Bytes> Unsubscribe<Seq, Bytes>
where
Seq: AnyVec<Bytes>,
Bytes: AnyVec<u8>,
{
pub const TYPE: u8 = 10;
pub fn new<S, T>(packet_id: u16, topics: S) -> Result<Self, MemoryError>
where
S: IntoIterator<Item = T>,
T: AsRef<[u8]>,
{
let mut topics_ = Seq::default();
for topic in topics {
let topic = Bytes::new(topic.as_ref())?;
topics_.push(topic)?;
}
Ok(Self { packet_id, topics: topics_, _vec: PhantomData })
}
pub fn packet_id(&self) -> u16 {
self.packet_id
}
pub fn topics(&self) -> &Seq {
&self.topics
}
}
impl<Seq, Bytes> TryFromIterator for Unsubscribe<Seq, Bytes>
where
Seq: AnyVec<Bytes>,
Bytes: AnyVec<u8>,
{
fn try_from_iter<T>(iter: T) -> Result<Self, DecoderError>
where
T: IntoIterator<Item = u8>,
{
let mut decoder = Decoder::new(iter);
let (Self::TYPE, [false, false, true, false]) = decoder.header()? else {
return Err(err!(Data::SpecViolation, "invalid packet type/header"))?;
};
let len = decoder.packetlen()?;
let mut decoder = decoder.limit(len).peekable();
let packet_id = decoder.u16()?;
let topics = decoder.topics()?;
Ok(Self { packet_id, topics, _vec: PhantomData })
}
}
impl<Seq, Bytes> IntoIterator for Unsubscribe<Seq, Bytes>
where
Seq: AnyVec<Bytes>,
Bytes: AnyVec<u8>,
{
type Item = u8;
#[rustfmt::skip]
type IntoIter =
Chain<Chain<Chain<Chain<
Unit, U8Iter>,
PacketLenIter>,
U16Iter>,
TopicsIter<Seq, Bytes>>;
fn into_iter(self) -> Self::IntoIter {
#[rustfmt::skip]
let len = Length::new()
.u16(&self.packet_id)
.topics(&self.topics)
.into();
Encoder::default()
.header(Self::TYPE, [false, false, true, false])
.packetlen(len)
.u16(self.packet_id)
.topics(self.topics)
.into_iter()
}
}