// SPDX-License-Identifier: GPL-2.012use core::ops::Deref;34use kernel::{5alloc::KVec,6prelude::*, //7};89/// A buffer abstraction for discontiguous byte slices.10///11/// This allows you to treat multiple non-contiguous `&mut [u8]` slices12/// of the same length as a single stream-like read/write buffer.13///14/// # Examples15///16/// ```17// let mut buf1 = [0u8; 5];18/// let mut buf2 = [0u8; 5];19/// let mut sbuffer = SBufferIter::new_writer([&mut buf1[..], &mut buf2[..]]);20///21/// let data = b"hi world!";22/// sbuffer.write_all(data)?;23/// drop(sbuffer);24///25/// assert_eq!(buf1, *b"hi wo");26/// assert_eq!(buf2, *b"rld!\0");27///28/// # Ok::<(), Error>(())29/// ```30pub(crate) struct SBufferIter<I: Iterator> {31// [`Some`] if we are not at the end of the data yet.32cur_slice: Option<I::Item>,33// All the slices remaining after `cur_slice`.34slices: I,35}3637impl<'a, I> SBufferIter<I>38where39I: Iterator,40{41/// Creates a reader buffer for a discontiguous set of byte slices.42///43/// # Examples44///45/// ```46/// let buf1: [u8; 5] = [0, 1, 2, 3, 4];47/// let buf2: [u8; 5] = [5, 6, 7, 8, 9];48/// let sbuffer = SBufferIter::new_reader([&buf1[..], &buf2[..]]);49/// let sum: u8 = sbuffer.sum();50/// assert_eq!(sum, 45);51/// ```52pub(crate) fn new_reader(slices: impl IntoIterator<IntoIter = I>) -> Self53where54I: Iterator<Item = &'a [u8]>,55{56Self::new(slices)57}5859/// Creates a writeable buffer for a discontiguous set of byte slices.60///61/// # Examples62///63/// ```64/// let mut buf1 = [0u8; 5];65/// let mut buf2 = [0u8; 5];66/// let mut sbuffer = SBufferIter::new_writer([&mut buf1[..], &mut buf2[..]]);67/// sbuffer.write_all(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9][..])?;68/// drop(sbuffer);69/// assert_eq!(buf1, [0, 1, 2, 3, 4]);70/// assert_eq!(buf2, [5, 6, 7, 8, 9]);71///72/// ```73pub(crate) fn new_writer(slices: impl IntoIterator<IntoIter = I>) -> Self74where75I: Iterator<Item = &'a mut [u8]>,76{77Self::new(slices)78}7980fn new(slices: impl IntoIterator<IntoIter = I>) -> Self81where82I::Item: Deref<Target = [u8]>,83{84let mut slices = slices.into_iter();8586Self {87// Skip empty slices.88cur_slice: slices.find(|s| !s.deref().is_empty()),89slices,90}91}9293/// Returns a slice of at most `len` bytes, or [`None`] if we are at the end of the data.94///95/// If a slice shorter than `len` bytes has been returned, the caller can call this method96/// again until it returns [`None`] to try and obtain the remainder of the data.97///98/// The closure `f` should split the slice received in it's first parameter99/// at the position given in the second parameter.100fn get_slice_internal(101&mut self,102len: usize,103mut f: impl FnMut(I::Item, usize) -> (I::Item, I::Item),104) -> Option<I::Item>105where106I::Item: Deref<Target = [u8]>,107{108match self.cur_slice.take() {109None => None,110Some(cur_slice) => {111if len >= cur_slice.len() {112// Caller requested more data than is in the current slice, return it entirely113// and prepare the following slice for being used. Skip empty slices to avoid114// trouble.115self.cur_slice = self.slices.find(|s| !s.is_empty());116117Some(cur_slice)118} else {119// The current slice can satisfy the request, split it and return a slice of120// the requested size.121let (ret, next) = f(cur_slice, len);122self.cur_slice = Some(next);123124Some(ret)125}126}127}128}129130/// Returns whether this buffer still has data available.131pub(crate) fn is_empty(&self) -> bool {132self.cur_slice.is_none()133}134}135136/// Provides a way to get non-mutable slices of data to read from.137impl<'a, I> SBufferIter<I>138where139I: Iterator<Item = &'a [u8]>,140{141/// Returns a slice of at most `len` bytes, or [`None`] if we are at the end of the data.142///143/// If a slice shorter than `len` bytes has been returned, the caller can call this method144/// again until it returns [`None`] to try and obtain the remainder of the data.145fn get_slice(&mut self, len: usize) -> Option<&'a [u8]> {146self.get_slice_internal(len, |s, pos| s.split_at(pos))147}148149/// Ideally we would implement `Read`, but it is not available in `core`.150/// So mimic `std::io::Read::read_exact`.151#[expect(unused)]152pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result {153while !dst.is_empty() {154match self.get_slice(dst.len()) {155None => return Err(EINVAL),156Some(src) => {157let dst_slice;158(dst_slice, dst) = dst.split_at_mut(src.len());159dst_slice.copy_from_slice(src);160}161}162}163164Ok(())165}166167/// Read all the remaining data into a [`KVec`].168///169/// `self` will be empty after this operation.170pub(crate) fn flush_into_kvec(&mut self, flags: kernel::alloc::Flags) -> Result<KVec<u8>> {171let mut buf = KVec::<u8>::new();172173if let Some(slice) = core::mem::take(&mut self.cur_slice) {174buf.extend_from_slice(slice, flags)?;175}176for slice in &mut self.slices {177buf.extend_from_slice(slice, flags)?;178}179180Ok(buf)181}182}183184/// Provides a way to get mutable slices of data to write into.185impl<'a, I> SBufferIter<I>186where187I: Iterator<Item = &'a mut [u8]>,188{189/// Returns a mutable slice of at most `len` bytes, or [`None`] if we are at the end of the190/// data.191///192/// If a slice shorter than `len` bytes has been returned, the caller can call this method193/// again until it returns `None` to try and obtain the remainder of the data.194fn get_slice_mut(&mut self, len: usize) -> Option<&'a mut [u8]> {195self.get_slice_internal(len, |s, pos| s.split_at_mut(pos))196}197198/// Ideally we would implement [`Write`], but it is not available in `core`.199/// So mimic `std::io::Write::write_all`.200pub(crate) fn write_all(&mut self, mut src: &[u8]) -> Result {201while !src.is_empty() {202match self.get_slice_mut(src.len()) {203None => return Err(ETOOSMALL),204Some(dst) => {205let src_slice;206(src_slice, src) = src.split_at(dst.len());207dst.copy_from_slice(src_slice);208}209}210}211212Ok(())213}214}215216impl<'a, I> Iterator for SBufferIter<I>217where218I: Iterator<Item = &'a [u8]>,219{220type Item = u8;221222fn next(&mut self) -> Option<Self::Item> {223// Returned slices are guaranteed to not be empty so we can safely index the first entry.224self.get_slice(1).map(|s| s[0])225}226}227228229