// SPDX-License-Identifier: GPL-2.012use core::ops::Deref;34use kernel::prelude::*;56/// A buffer abstraction for discontiguous byte slices.7///8/// This allows you to treat multiple non-contiguous `&mut [u8]` slices9/// of the same length as a single stream-like read/write buffer.10///11/// # Examples12///13/// ```14// let mut buf1 = [0u8; 5];15/// let mut buf2 = [0u8; 5];16/// let mut sbuffer = SBufferIter::new_writer([&mut buf1[..], &mut buf2[..]]);17///18/// let data = b"hi world!";19/// sbuffer.write_all(data)?;20/// drop(sbuffer);21///22/// assert_eq!(buf1, *b"hi wo");23/// assert_eq!(buf2, *b"rld!\0");24///25/// # Ok::<(), Error>(())26/// ```27pub(crate) struct SBufferIter<I: Iterator> {28// [`Some`] if we are not at the end of the data yet.29cur_slice: Option<I::Item>,30// All the slices remaining after `cur_slice`.31slices: I,32}3334impl<'a, I> SBufferIter<I>35where36I: Iterator,37{38/// Creates a reader buffer for a discontiguous set of byte slices.39///40/// # Examples41///42/// ```43/// let buf1: [u8; 5] = [0, 1, 2, 3, 4];44/// let buf2: [u8; 5] = [5, 6, 7, 8, 9];45/// let sbuffer = SBufferIter::new_reader([&buf1[..], &buf2[..]]);46/// let sum: u8 = sbuffer.sum();47/// assert_eq!(sum, 45);48/// ```49pub(crate) fn new_reader(slices: impl IntoIterator<IntoIter = I>) -> Self50where51I: Iterator<Item = &'a [u8]>,52{53Self::new(slices)54}5556/// Creates a writeable buffer for a discontiguous set of byte slices.57///58/// # Examples59///60/// ```61/// let mut buf1 = [0u8; 5];62/// let mut buf2 = [0u8; 5];63/// let mut sbuffer = SBufferIter::new_writer([&mut buf1[..], &mut buf2[..]]);64/// sbuffer.write_all(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9][..])?;65/// drop(sbuffer);66/// assert_eq!(buf1, [0, 1, 2, 3, 4]);67/// assert_eq!(buf2, [5, 6, 7, 8, 9]);68///69/// ```70pub(crate) fn new_writer(slices: impl IntoIterator<IntoIter = I>) -> Self71where72I: Iterator<Item = &'a mut [u8]>,73{74Self::new(slices)75}7677fn new(slices: impl IntoIterator<IntoIter = I>) -> Self78where79I::Item: Deref<Target = [u8]>,80{81let mut slices = slices.into_iter();8283Self {84// Skip empty slices.85cur_slice: slices.find(|s| !s.deref().is_empty()),86slices,87}88}8990/// Returns a slice of at most `len` bytes, or [`None`] if we are at the end of the data.91///92/// If a slice shorter than `len` bytes has been returned, the caller can call this method93/// again until it returns [`None`] to try and obtain the remainder of the data.94///95/// The closure `f` should split the slice received in it's first parameter96/// at the position given in the second parameter.97fn get_slice_internal(98&mut self,99len: usize,100mut f: impl FnMut(I::Item, usize) -> (I::Item, I::Item),101) -> Option<I::Item>102where103I::Item: Deref<Target = [u8]>,104{105match self.cur_slice.take() {106None => None,107Some(cur_slice) => {108if len >= cur_slice.len() {109// Caller requested more data than is in the current slice, return it entirely110// and prepare the following slice for being used. Skip empty slices to avoid111// trouble.112self.cur_slice = self.slices.find(|s| !s.is_empty());113114Some(cur_slice)115} else {116// The current slice can satisfy the request, split it and return a slice of117// the requested size.118let (ret, next) = f(cur_slice, len);119self.cur_slice = Some(next);120121Some(ret)122}123}124}125}126127/// Returns whether this buffer still has data available.128pub(crate) fn is_empty(&self) -> bool {129self.cur_slice.is_none()130}131}132133/// Provides a way to get non-mutable slices of data to read from.134impl<'a, I> SBufferIter<I>135where136I: Iterator<Item = &'a [u8]>,137{138/// Returns a slice of at most `len` bytes, or [`None`] if we are at the end of the data.139///140/// If a slice shorter than `len` bytes has been returned, the caller can call this method141/// again until it returns [`None`] to try and obtain the remainder of the data.142fn get_slice(&mut self, len: usize) -> Option<&'a [u8]> {143self.get_slice_internal(len, |s, pos| s.split_at(pos))144}145146/// Ideally we would implement `Read`, but it is not available in `core`.147/// So mimic `std::io::Read::read_exact`.148#[expect(unused)]149pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result {150while !dst.is_empty() {151match self.get_slice(dst.len()) {152None => return Err(EINVAL),153Some(src) => {154let dst_slice;155(dst_slice, dst) = dst.split_at_mut(src.len());156dst_slice.copy_from_slice(src);157}158}159}160161Ok(())162}163164/// Read all the remaining data into a [`KVec`].165///166/// `self` will be empty after this operation.167pub(crate) fn flush_into_kvec(&mut self, flags: kernel::alloc::Flags) -> Result<KVec<u8>> {168let mut buf = KVec::<u8>::new();169170if let Some(slice) = core::mem::take(&mut self.cur_slice) {171buf.extend_from_slice(slice, flags)?;172}173for slice in &mut self.slices {174buf.extend_from_slice(slice, flags)?;175}176177Ok(buf)178}179}180181/// Provides a way to get mutable slices of data to write into.182impl<'a, I> SBufferIter<I>183where184I: Iterator<Item = &'a mut [u8]>,185{186/// Returns a mutable slice of at most `len` bytes, or [`None`] if we are at the end of the187/// data.188///189/// If a slice shorter than `len` bytes has been returned, the caller can call this method190/// again until it returns `None` to try and obtain the remainder of the data.191fn get_slice_mut(&mut self, len: usize) -> Option<&'a mut [u8]> {192self.get_slice_internal(len, |s, pos| s.split_at_mut(pos))193}194195/// Ideally we would implement [`Write`], but it is not available in `core`.196/// So mimic `std::io::Write::write_all`.197pub(crate) fn write_all(&mut self, mut src: &[u8]) -> Result {198while !src.is_empty() {199match self.get_slice_mut(src.len()) {200None => return Err(ETOOSMALL),201Some(dst) => {202let src_slice;203(src_slice, src) = src.split_at(dst.len());204dst.copy_from_slice(src_slice);205}206}207}208209Ok(())210}211}212213impl<'a, I> Iterator for SBufferIter<I>214where215I: Iterator<Item = &'a [u8]>,216{217type Item = u8;218219fn next(&mut self) -> Option<Self::Item> {220// Returned slices are guaranteed to not be empty so we can safely index the first entry.221self.get_slice(1).map(|s| s[0])222}223}224225226