From 6f47e2eb8bce2451cad33e872ea32998c894e7d4 Mon Sep 17 00:00:00 2001 From: Levi Morrison Date: Mon, 5 Feb 2024 15:03:53 -0700 Subject: [PATCH] feat: add str encoding helper This allows users to encode types like `&str`, `Box`. This can be more efficient than creating a String just for the purpose of encoding it. --- src/encoding.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/encoding.rs b/src/encoding.rs index e4d2aa274..b7609319d 100644 --- a/src/encoding.rs +++ b/src/encoding.rs @@ -9,7 +9,7 @@ use alloc::format; use alloc::string::String; use alloc::vec::Vec; use core::cmp::min; -use core::convert::TryFrom; +use core::convert::{AsRef, TryFrom}; use core::mem; use core::str; use core::u32; @@ -794,14 +794,20 @@ macro_rules! length_delimited { pub mod string { use super::*; + pub fn encode_ref(tag: u32, value: impl AsRef, buf: &mut impl BufMut) { + let str = value.as_ref(); + encode_key(tag, WireType::LengthDelimited, buf); + encode_varint(str.len() as u64, buf); + buf.put_slice(str.as_bytes()); + } + pub fn encode(tag: u32, value: &String, buf: &mut B) where B: BufMut, { - encode_key(tag, WireType::LengthDelimited, buf); - encode_varint(value.len() as u64, buf); - buf.put_slice(value.as_bytes()); + encode_ref(tag, value, buf) } + pub fn merge( wire_type: WireType, value: &mut String,