use crate::{BinRead, BinResult, VecArgs};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::fmt;
pub struct Punctuated<T: BinRead, P: BinRead> {
data: Vec<T>,
pub separators: Vec<P>,
}
impl<T, P> Punctuated<T, P>
where
T: BinRead,
P: for<'a> BinRead<Args<'a> = ()>,
{
#[crate::parser(reader, endian)]
pub fn separated<'a>(args: VecArgs<T::Args<'a>>, _: ...) -> BinResult<Self>
where
T::Args<'a>: Clone,
{
let mut data = Vec::with_capacity(args.count);
let mut separators = Vec::with_capacity(args.count.max(1) - 1);
for i in 0..args.count {
data.push(T::read_options(reader, endian, args.inner.clone())?);
if i + 1 != args.count {
separators.push(P::read_options(reader, endian, ())?);
}
}
Ok(Self { data, separators })
}
#[crate::parser(reader, endian)]
pub fn separated_trailing<'a>(args: VecArgs<T::Args<'a>>, _: ...) -> BinResult<Self>
where
T::Args<'a>: Clone,
{
let mut data = Vec::with_capacity(args.count);
let mut separators = Vec::with_capacity(args.count);
for _ in 0..args.count {
data.push(T::read_options(reader, endian, args.inner.clone())?);
separators.push(P::read_options(reader, endian, ())?);
}
Ok(Self { data, separators })
}
#[must_use]
pub fn into_values(self) -> Vec<T> {
self.data
}
}
impl<T: BinRead + fmt::Debug, P: BinRead> fmt::Debug for Punctuated<T, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.data.fmt(f)
}
}
impl<T: BinRead, P: BinRead> core::ops::Deref for Punctuated<T, P> {
type Target = Vec<T>;
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<T: BinRead, P: BinRead> core::ops::DerefMut for Punctuated<T, P> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.data
}
}