Skip to content

Commit ce9de1c

Browse files
committed
Encode string and bytes slices
1 parent 63c0024 commit ce9de1c

File tree

1 file changed

+11
-27
lines changed

1 file changed

+11
-27
lines changed

src/encoding.rs

Lines changed: 11 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -794,13 +794,15 @@ macro_rules! length_delimited {
794794
pub mod string {
795795
use super::*;
796796

797-
pub fn encode<B>(tag: u32, value: &String, buf: &mut B)
797+
pub fn encode<S, B>(tag: u32, value: &S, buf: &mut B)
798798
where
799+
S: AsRef<str>,
799800
B: BufMut,
800801
{
802+
let slice = value.as_ref();
801803
encode_key(tag, WireType::LengthDelimited, buf);
802-
encode_varint(value.len() as u64, buf);
803-
buf.put_slice(value.as_bytes());
804+
encode_varint(slice.len() as u64, buf);
805+
buf.put_slice(slice.as_bytes());
804806
}
805807
pub fn merge<B>(
806808
wire_type: WireType,
@@ -876,21 +878,16 @@ pub mod string {
876878
pub trait BytesAdapter: sealed::BytesAdapter {}
877879

878880
mod sealed {
879-
use super::{Buf, BufMut};
881+
use super::Buf;
880882

881-
pub trait BytesAdapter: Default + Sized + 'static {
883+
pub trait BytesAdapter: Default + Sized + AsRef<[u8]> + 'static {
882884
fn len(&self) -> usize;
883885

884886
/// Replace contents of this buffer with the contents of another buffer.
885887
fn replace_with<B>(&mut self, buf: B)
886888
where
887889
B: Buf;
888890

889-
/// Appends this buffer to the (contents of) other buffer.
890-
fn append_to<B>(&self, buf: &mut B)
891-
where
892-
B: BufMut;
893-
894891
fn is_empty(&self) -> bool {
895892
self.len() == 0
896893
}
@@ -910,13 +907,6 @@ impl sealed::BytesAdapter for Bytes {
910907
{
911908
*self = buf.copy_to_bytes(buf.remaining());
912909
}
913-
914-
fn append_to<B>(&self, buf: &mut B)
915-
where
916-
B: BufMut,
917-
{
918-
buf.put(self.clone())
919-
}
920910
}
921911

922912
impl BytesAdapter for Vec<u8> {}
@@ -934,26 +924,20 @@ impl sealed::BytesAdapter for Vec<u8> {
934924
self.reserve(buf.remaining());
935925
self.put(buf);
936926
}
937-
938-
fn append_to<B>(&self, buf: &mut B)
939-
where
940-
B: BufMut,
941-
{
942-
buf.put(self.as_slice())
943-
}
944927
}
945928

946929
pub mod bytes {
947930
use super::*;
948931

949932
pub fn encode<A, B>(tag: u32, value: &A, buf: &mut B)
950933
where
951-
A: BytesAdapter,
934+
A: AsRef<[u8]>,
952935
B: BufMut,
953936
{
937+
let slice = value.as_ref();
954938
encode_key(tag, WireType::LengthDelimited, buf);
955-
encode_varint(value.len() as u64, buf);
956-
value.append_to(buf);
939+
encode_varint(slice.len() as u64, buf);
940+
buf.put_slice(slice);
957941
}
958942

959943
pub fn merge<A, B>(

0 commit comments

Comments
 (0)