reader.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // SPDX-License-Identifier: AGPL-3.0-or-later
  2. //! This module contains the [Reader] trait which enables zero-copy deserialization over
  3. //! different input types.
  4. use crate::{error::MapError, Error, Result};
  5. use std::{io::Read, ops::DerefMut};
  6. pub trait Reader<'de> {
  7. /// Reads exactly enough bytes to fill the given buffer or returns an error.
  8. fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>;
  9. /// Returns true if the `borrow_bytes` method is supported by this instance.
  10. fn can_borrow() -> bool;
  11. /// Borrows the given number of bytes from this [Reader] starting at the current position.
  12. fn borrow_bytes(&mut self, len: usize) -> Result<&'de [u8]>;
  13. }
  14. impl<'de, R: ?Sized + Reader<'de>, P: DerefMut<Target = R>> Reader<'de> for P {
  15. fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
  16. self.deref_mut().read_exact(buf)
  17. }
  18. fn can_borrow() -> bool {
  19. R::can_borrow()
  20. }
  21. fn borrow_bytes(&mut self, len: usize) -> Result<&'de [u8]> {
  22. self.deref_mut().borrow_bytes(len)
  23. }
  24. }
  25. /// An adapter over an implementation of the standard library [Read] trait.
  26. pub struct ReadAdapter<R>(R);
  27. impl<R> ReadAdapter<R> {
  28. pub fn new(read: R) -> Self {
  29. Self(read)
  30. }
  31. }
  32. impl<'de, R: Read> Reader<'de> for ReadAdapter<R> {
  33. fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
  34. self.0.read_exact(buf).map_error()
  35. }
  36. fn can_borrow() -> bool {
  37. false
  38. }
  39. fn borrow_bytes(&mut self, _len: usize) -> Result<&'de [u8]> {
  40. Err(Error::NotSupported("borrowing from a ReadAdapter"))
  41. }
  42. }
  43. /// An adapter for reading out of a slice of bytes.
  44. pub struct SliceAdapter<'a>(&'a [u8]);
  45. impl<'a> SliceAdapter<'a> {
  46. pub fn new(slice: &'a [u8]) -> Self {
  47. Self(slice)
  48. }
  49. fn assert_longer_than(&self, buf_len: usize) -> Result<()> {
  50. if self.0.len() >= buf_len {
  51. Ok(())
  52. } else {
  53. Err(Error::Eof)
  54. }
  55. }
  56. }
  57. impl<'de> Reader<'de> for SliceAdapter<'de> {
  58. fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
  59. let buf_len = buf.len();
  60. self.assert_longer_than(buf_len)?;
  61. buf.copy_from_slice(&self.0[..buf_len]);
  62. self.0 = &self.0[buf_len..];
  63. Ok(())
  64. }
  65. fn can_borrow() -> bool {
  66. true
  67. }
  68. fn borrow_bytes(&mut self, len: usize) -> Result<&'de [u8]> {
  69. self.assert_longer_than(len)?;
  70. let borrow = &self.0[..len];
  71. self.0 = &self.0[len..];
  72. Ok(borrow)
  73. }
  74. }