Skip to content

Commit

Permalink
feat: add str encoding helper
Browse files Browse the repository at this point in the history
This allows users to encode types like `&str`, `Box<str>`. This can
be more efficient than creating a String just for the purpose of
encoding it.
  • Loading branch information
morrisonlevi committed Feb 5, 2024
1 parent 63c0024 commit 6f47e2e
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -794,14 +794,20 @@ macro_rules! length_delimited {
pub mod string {
use super::*;

pub fn encode_ref(tag: u32, value: impl AsRef<str>, 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<B>(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<B>(
wire_type: WireType,
value: &mut String,
Expand Down

0 comments on commit 6f47e2e

Please sign in to comment.