sbuffer.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // SPDX-License-Identifier: GPL-2.0
  2. use core::ops::Deref;
  3. use kernel::prelude::*;
  4. /// A buffer abstraction for discontiguous byte slices.
  5. ///
  6. /// This allows you to treat multiple non-contiguous `&mut [u8]` slices
  7. /// of the same length as a single stream-like read/write buffer.
  8. ///
  9. /// # Examples
  10. ///
  11. /// ```
  12. // let mut buf1 = [0u8; 5];
  13. /// let mut buf2 = [0u8; 5];
  14. /// let mut sbuffer = SBufferIter::new_writer([&mut buf1[..], &mut buf2[..]]);
  15. ///
  16. /// let data = b"hi world!";
  17. /// sbuffer.write_all(data)?;
  18. /// drop(sbuffer);
  19. ///
  20. /// assert_eq!(buf1, *b"hi wo");
  21. /// assert_eq!(buf2, *b"rld!\0");
  22. ///
  23. /// # Ok::<(), Error>(())
  24. /// ```
  25. pub(crate) struct SBufferIter<I: Iterator> {
  26. // [`Some`] if we are not at the end of the data yet.
  27. cur_slice: Option<I::Item>,
  28. // All the slices remaining after `cur_slice`.
  29. slices: I,
  30. }
  31. impl<'a, I> SBufferIter<I>
  32. where
  33. I: Iterator,
  34. {
  35. /// Creates a reader buffer for a discontiguous set of byte slices.
  36. ///
  37. /// # Examples
  38. ///
  39. /// ```
  40. /// let buf1: [u8; 5] = [0, 1, 2, 3, 4];
  41. /// let buf2: [u8; 5] = [5, 6, 7, 8, 9];
  42. /// let sbuffer = SBufferIter::new_reader([&buf1[..], &buf2[..]]);
  43. /// let sum: u8 = sbuffer.sum();
  44. /// assert_eq!(sum, 45);
  45. /// ```
  46. pub(crate) fn new_reader(slices: impl IntoIterator<IntoIter = I>) -> Self
  47. where
  48. I: Iterator<Item = &'a [u8]>,
  49. {
  50. Self::new(slices)
  51. }
  52. /// Creates a writeable buffer for a discontiguous set of byte slices.
  53. ///
  54. /// # Examples
  55. ///
  56. /// ```
  57. /// let mut buf1 = [0u8; 5];
  58. /// let mut buf2 = [0u8; 5];
  59. /// let mut sbuffer = SBufferIter::new_writer([&mut buf1[..], &mut buf2[..]]);
  60. /// sbuffer.write_all(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9][..])?;
  61. /// drop(sbuffer);
  62. /// assert_eq!(buf1, [0, 1, 2, 3, 4]);
  63. /// assert_eq!(buf2, [5, 6, 7, 8, 9]);
  64. ///
  65. /// ```
  66. pub(crate) fn new_writer(slices: impl IntoIterator<IntoIter = I>) -> Self
  67. where
  68. I: Iterator<Item = &'a mut [u8]>,
  69. {
  70. Self::new(slices)
  71. }
  72. fn new(slices: impl IntoIterator<IntoIter = I>) -> Self
  73. where
  74. I::Item: Deref<Target = [u8]>,
  75. {
  76. let mut slices = slices.into_iter();
  77. Self {
  78. // Skip empty slices.
  79. cur_slice: slices.find(|s| !s.deref().is_empty()),
  80. slices,
  81. }
  82. }
  83. /// Returns a slice of at most `len` bytes, or [`None`] if we are at the end of the data.
  84. ///
  85. /// If a slice shorter than `len` bytes has been returned, the caller can call this method
  86. /// again until it returns [`None`] to try and obtain the remainder of the data.
  87. ///
  88. /// The closure `f` should split the slice received in it's first parameter
  89. /// at the position given in the second parameter.
  90. fn get_slice_internal(
  91. &mut self,
  92. len: usize,
  93. mut f: impl FnMut(I::Item, usize) -> (I::Item, I::Item),
  94. ) -> Option<I::Item>
  95. where
  96. I::Item: Deref<Target = [u8]>,
  97. {
  98. match self.cur_slice.take() {
  99. None => None,
  100. Some(cur_slice) => {
  101. if len >= cur_slice.len() {
  102. // Caller requested more data than is in the current slice, return it entirely
  103. // and prepare the following slice for being used. Skip empty slices to avoid
  104. // trouble.
  105. self.cur_slice = self.slices.find(|s| !s.is_empty());
  106. Some(cur_slice)
  107. } else {
  108. // The current slice can satisfy the request, split it and return a slice of
  109. // the requested size.
  110. let (ret, next) = f(cur_slice, len);
  111. self.cur_slice = Some(next);
  112. Some(ret)
  113. }
  114. }
  115. }
  116. }
  117. /// Returns whether this buffer still has data available.
  118. pub(crate) fn is_empty(&self) -> bool {
  119. self.cur_slice.is_none()
  120. }
  121. }
  122. /// Provides a way to get non-mutable slices of data to read from.
  123. impl<'a, I> SBufferIter<I>
  124. where
  125. I: Iterator<Item = &'a [u8]>,
  126. {
  127. /// Returns a slice of at most `len` bytes, or [`None`] if we are at the end of the data.
  128. ///
  129. /// If a slice shorter than `len` bytes has been returned, the caller can call this method
  130. /// again until it returns [`None`] to try and obtain the remainder of the data.
  131. fn get_slice(&mut self, len: usize) -> Option<&'a [u8]> {
  132. self.get_slice_internal(len, |s, pos| s.split_at(pos))
  133. }
  134. /// Ideally we would implement `Read`, but it is not available in `core`.
  135. /// So mimic `std::io::Read::read_exact`.
  136. #[expect(unused)]
  137. pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result {
  138. while !dst.is_empty() {
  139. match self.get_slice(dst.len()) {
  140. None => return Err(EINVAL),
  141. Some(src) => {
  142. let dst_slice;
  143. (dst_slice, dst) = dst.split_at_mut(src.len());
  144. dst_slice.copy_from_slice(src);
  145. }
  146. }
  147. }
  148. Ok(())
  149. }
  150. /// Read all the remaining data into a [`KVec`].
  151. ///
  152. /// `self` will be empty after this operation.
  153. pub(crate) fn flush_into_kvec(&mut self, flags: kernel::alloc::Flags) -> Result<KVec<u8>> {
  154. let mut buf = KVec::<u8>::new();
  155. if let Some(slice) = core::mem::take(&mut self.cur_slice) {
  156. buf.extend_from_slice(slice, flags)?;
  157. }
  158. for slice in &mut self.slices {
  159. buf.extend_from_slice(slice, flags)?;
  160. }
  161. Ok(buf)
  162. }
  163. }
  164. /// Provides a way to get mutable slices of data to write into.
  165. impl<'a, I> SBufferIter<I>
  166. where
  167. I: Iterator<Item = &'a mut [u8]>,
  168. {
  169. /// Returns a mutable slice of at most `len` bytes, or [`None`] if we are at the end of the
  170. /// data.
  171. ///
  172. /// If a slice shorter than `len` bytes has been returned, the caller can call this method
  173. /// again until it returns `None` to try and obtain the remainder of the data.
  174. fn get_slice_mut(&mut self, len: usize) -> Option<&'a mut [u8]> {
  175. self.get_slice_internal(len, |s, pos| s.split_at_mut(pos))
  176. }
  177. /// Ideally we would implement [`Write`], but it is not available in `core`.
  178. /// So mimic `std::io::Write::write_all`.
  179. pub(crate) fn write_all(&mut self, mut src: &[u8]) -> Result {
  180. while !src.is_empty() {
  181. match self.get_slice_mut(src.len()) {
  182. None => return Err(ETOOSMALL),
  183. Some(dst) => {
  184. let src_slice;
  185. (src_slice, src) = src.split_at(dst.len());
  186. dst.copy_from_slice(src_slice);
  187. }
  188. }
  189. }
  190. Ok(())
  191. }
  192. }
  193. impl<'a, I> Iterator for SBufferIter<I>
  194. where
  195. I: Iterator<Item = &'a [u8]>,
  196. {
  197. type Item = u8;
  198. fn next(&mut self) -> Option<Self::Item> {
  199. // Returned slices are guaranteed to not be empty so we can safely index the first entry.
  200. self.get_slice(1).map(|s| s[0])
  201. }
  202. }