use crate::{
io::{Read, Seek},
BinRead, BinResult, ReadOptions, VecArgs,
};
use alloc::vec::Vec;
use core::fmt;
pub struct Punctuated<T: BinRead, P: BinRead> {
data: Vec<T>,
pub separators: Vec<P>,
}
impl<T: BinRead, P: BinRead<Args = ()>> Punctuated<T, P> {
#[allow(clippy::needless_pass_by_value)]
pub fn separated<R: Read + Seek>(
reader: &mut R,
options: &ReadOptions,
args: VecArgs<T::Args>,
) -> BinResult<Self> {
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, options, args.inner.clone())?);
if i + 1 != args.count {
separators.push(P::read_options(reader, options, ())?);
}
}
Ok(Self { data, separators })
}
#[allow(clippy::needless_pass_by_value)]
pub fn separated_trailing<R: Read + Seek>(
reader: &mut R,
options: &ReadOptions,
args: VecArgs<T::Args>,
) -> BinResult<Self> {
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, options, args.inner.clone())?);
separators.push(P::read_options(reader, options, ())?);
}
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
}
}