| 1 | use bytes::{BufMut, BytesMut}; |
| 2 | |
| 3 | /// An extension for [`BufMut`] for getting a writeable buffer in safe code. |
| 4 | pub trait ReadBuf: BufMut { |
| 5 | /// Get the full capacity of this buffer as a safely initialized slice. |
| 6 | fn init_mut(&mut self) -> &mut [u8]; |
| 7 | } |
| 8 | |
| 9 | impl ReadBuf for &'_ mut [u8] { |
| 10 | #[inline(always)] |
| 11 | fn init_mut(&mut self) -> &mut [u8] { |
| 12 | self |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | impl ReadBuf for BytesMut { |
| 17 | #[inline(always)] |
| 18 | fn init_mut(&mut self) -> &mut [u8] { |
| 19 | // `self.remaining_mut()` returns `usize::MAX - self.len()` |
| 20 | let remaining = self.capacity() - self.len(); |
| 21 | |
| 22 | // I'm hoping for most uses that this operation is elided by the optimizer. |
| 23 | self.put_bytes(0, remaining); |
| 24 | |
| 25 | self |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | #[test] |
| 30 | fn test_read_buf_bytes_mut() { |
| 31 | let mut buf = BytesMut::with_capacity(8); |
| 32 | buf.put_u32(0x12345678); |
| 33 | |
| 34 | assert_eq!(buf.init_mut(), [0x12, 0x34, 0x56, 0x78, 0, 0, 0, 0]); |
| 35 | } |