reader.rs 2.4 KB

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