From 8db525dab49593d92689cdda7878117c9d475170 Mon Sep 17 00:00:00 2001 From: Nick Mathewson Date: Sat, 5 Sep 2020 10:06:58 -0400 Subject: [PATCH] tor-bytes: Add initial support for the bytes crate --- tor-bytes/Cargo.toml | 1 + tor-bytes/src/impls.rs | 7 +++++++ tor-bytes/src/reader.rs | 9 +++++++++ 3 files changed, 17 insertions(+) diff --git a/tor-bytes/Cargo.toml b/tor-bytes/Cargo.toml index eb7b39e4d..409e3bc7a 100644 --- a/tor-bytes/Cargo.toml +++ b/tor-bytes/Cargo.toml @@ -14,6 +14,7 @@ generic-array = "0.14.4" crypto-mac = "0.9.1" thiserror = "1.0.20" signature = "1.2.2" +bytes = "*" [dev-dependencies] hex-literal = "0.3.1" diff --git a/tor-bytes/src/impls.rs b/tor-bytes/src/impls.rs index 40463d4b3..1271982d0 100644 --- a/tor-bytes/src/impls.rs +++ b/tor-bytes/src/impls.rs @@ -5,6 +5,7 @@ //! this is where I'm putting them. use super::*; +use bytes; use generic_array::GenericArray; // ---------------------------------------------------------------------- @@ -25,6 +26,12 @@ impl Writer for Vec { } } +impl Writer for bytes::BytesMut { + fn write_all(&mut self, bytes: &[u8]) { + self.extend_from_slice(bytes); + } +} + // ---------------------------------------------------------------------- impl<'a> Writeable for [u8] { diff --git a/tor-bytes/src/reader.rs b/tor-bytes/src/reader.rs index 8ef96a821..9f6c298cd 100644 --- a/tor-bytes/src/reader.rs +++ b/tor-bytes/src/reader.rs @@ -1,5 +1,6 @@ use crate::{Error, Readable, Result}; use arrayref::array_ref; +use bytes; /// A type for reading messages from a slice of bytes. /// @@ -54,6 +55,14 @@ impl<'a> Reader<'a> { pub fn from_slice(slice: &'a [u8]) -> Self { Reader { b: slice, off: 0 } } + /// Construct a new Reader from a 'Bytes' object. + pub fn from_bytes(b: &'a bytes::Bytes) -> Self { + Self::from_slice(b.as_ref()) + } + /// Construct a new Reader from a 'BytesMut' object + pub fn from_bytes_mut(b: &'a bytes::BytesMut) -> Self { + Self::from_slice(b.as_ref()) + } /// Return the total length of the slice in this reader, including /// consumed bytes and remaining bytes. pub fn total_len(&self) -> usize {