reader.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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;
  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: Reader<'de>> Reader<'de> for &mut R {
  15. fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
  16. (*self).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).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(
  41. "borrowing from a ReadAdapter is not supported",
  42. ))
  43. }
  44. }
  45. /// An adapter for reading out of a slice of bytes.
  46. pub struct SliceAdapter<'a>(&'a [u8]);
  47. impl<'a> SliceAdapter<'a> {
  48. pub fn new(slice: &'a [u8]) -> Self {
  49. Self(slice)
  50. }
  51. fn assert_longer_than(&self, buf_len: usize) -> Result<()> {
  52. if self.0.len() >= buf_len {
  53. Ok(())
  54. } else {
  55. Err(Error::Eof)
  56. }
  57. }
  58. }
  59. impl<'de> Reader<'de> for SliceAdapter<'de> {
  60. fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
  61. let buf_len = buf.len();
  62. self.assert_longer_than(buf_len)?;
  63. buf.copy_from_slice(&self.0[..buf_len]);
  64. self.0 = &self.0[buf_len..];
  65. Ok(())
  66. }
  67. fn can_borrow() -> bool {
  68. true
  69. }
  70. fn borrow_bytes(&mut self, len: usize) -> Result<&'de [u8]> {
  71. self.assert_longer_than(len)?;
  72. let borrow = &self.0[..len];
  73. self.0 = &self.0[len..];
  74. Ok(borrow)
  75. }
  76. }