| 1 | use std::str::from_utf8; |
| 2 | |
| 3 | use bytes::{Buf, Bytes}; |
| 4 | use memchr::memchr; |
| 5 | |
| 6 | use crate::error::Error; |
| 7 | |
| 8 | pub trait BufExt: Buf { |
| 9 | // Read a nul-terminated byte sequence |
| 10 | fn get_bytes_nul(&mut self) -> Result<Bytes, Error>; |
| 11 | |
| 12 | // Read a byte sequence of the exact length |
| 13 | fn get_bytes(&mut self, len: usize) -> Bytes; |
| 14 | |
| 15 | // Read a nul-terminated string |
| 16 | fn get_str_nul(&mut self) -> Result<String, Error>; |
| 17 | |
| 18 | // Read a string of the exact length |
| 19 | fn get_str(&mut self, len: usize) -> Result<String, Error>; |
| 20 | } |
| 21 | |
| 22 | impl BufExt for Bytes { |
| 23 | fn get_bytes_nul(&mut self) -> Result<Bytes, Error> { |
| 24 | let nul = |
| 25 | memchr(b'\0', self).ok_or_else(|| err_protocol!("expected NUL in byte sequence"))?; |
| 26 | |
| 27 | let v = self.slice(0..nul); |
| 28 | |
| 29 | self.advance(nul + 1); |
| 30 | |
| 31 | Ok(v) |
| 32 | } |
| 33 | |
| 34 | fn get_bytes(&mut self, len: usize) -> Bytes { |
| 35 | let v = self.slice(..len); |
| 36 | self.advance(len); |
| 37 | |
| 38 | v |
| 39 | } |
| 40 | |
| 41 | fn get_str_nul(&mut self) -> Result<String, Error> { |
| 42 | self.get_bytes_nul().and_then(|bytes| { |
| 43 | from_utf8(&bytes) |
| 44 | .map(ToOwned::to_owned) |
| 45 | .map_err(|err| err_protocol!("{}", err)) |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | fn get_str(&mut self, len: usize) -> Result<String, Error> { |
| 50 | let v = from_utf8(&self[..len]) |
| 51 | .map_err(|err| err_protocol!("{}", err)) |
| 52 | .map(ToOwned::to_owned)?; |
| 53 | |
| 54 | self.advance(len); |
| 55 | |
| 56 | Ok(v) |
| 57 | } |
| 58 | } |