Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add borsh support #393

Merged
merged 7 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion compact_str/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ keywords = ["string", "compact", "small", "memory", "mutable"]
categories = ["encoding", "parsing", "memory-management", "text-processing"]

[features]
default = ["std"]
default = ["std", "borsh"]
std = []

arbitrary = ["dep:arbitrary"]
borsh = ["dep:borsh"]
bytes = ["dep:bytes"]
diesel = ["dep:diesel"]
markup = ["dep:markup"]
Expand All @@ -31,6 +32,7 @@ sqlx-sqlite = ["sqlx", "sqlx/sqlite"]

[dependencies]
arbitrary = { version = "1", optional = true, default-features = false }
borsh = { version = "1", optional = true }
bytes = { version = "1", optional = true }
diesel = { version = "2", optional = true, default-features = false }
markup = { version = "0.13", optional = true, default-features = false }
Expand Down
94 changes: 94 additions & 0 deletions compact_str/src/features/borsh.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#![cfg_attr(docsrs, doc(cfg(feature = "borsh")))]

use alloc::string::String;
use alloc::vec::Vec;
use core::str;

use borsh::io::{
Error,
ErrorKind,
Read,
Result,
Write,
};
use borsh::{
BorshDeserialize,
BorshSerialize,
};

use crate::repr::MAX_SIZE;
use crate::CompactString;

impl BorshSerialize for CompactString {
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> {
self.as_str().serialize(writer)
}
}

impl BorshDeserialize for CompactString {
fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self> {
let len = u32::deserialize_reader(&mut *reader)? as usize;

if len <= MAX_SIZE {
let mut buf = [0u8; MAX_SIZE];
reader.read_exact(&mut buf[..len])?;
let s = str::from_utf8(&buf[..len])
.map_err(|err| Error::new(ErrorKind::InvalidData, err))?;
Ok(CompactString::from(s))
} else {
let mut buf = Vec::new();
buf.try_reserve_exact(len)?;
buf.resize(len, 0u8);
reader.read_exact(&mut buf[..])?;
let s =
String::from_utf8(buf).map_err(|err| Error::new(ErrorKind::InvalidData, err))?;
Ok(CompactString::from(s))
}
}
}

#[cfg(test)]
mod tests {
use alloc::string::String;

use test_strategy::proptest;

use crate::repr::{
HEAP_MASK,
MAX_SIZE,
};
use crate::CompactString;

#[test]
fn test_roundtrip() {
const VALUE: &str = "Hello, 🌍!";

let bytes_compact = borsh::to_vec(&CompactString::from(VALUE)).unwrap();
let bytes_control = borsh::to_vec(&String::from(VALUE)).unwrap();
assert_eq!(&*bytes_compact, &*bytes_control);

let compact: CompactString = borsh::from_slice(&bytes_compact).unwrap();
let control: String = borsh::from_slice(&bytes_control).unwrap();
assert_eq!(compact, VALUE);
assert_eq!(control, VALUE);
}

#[test]
fn test_deserialize_invalid_utf8() {
let bytes = borsh::to_vec(&[HEAP_MASK; MAX_SIZE] as &[u8]).unwrap();
borsh::from_slice::<CompactString>(&bytes).unwrap_err();
}

#[cfg_attr(miri, ignore)]
#[proptest]
fn proptest_roundtrip(s: String) {
let bytes_compact = borsh::to_vec(&CompactString::from(&s)).unwrap();
let bytes_control = borsh::to_vec(&String::from(&s)).unwrap();
assert_eq!(&*bytes_compact, &*bytes_control);

let compact: CompactString = borsh::from_slice(&bytes_compact).unwrap();
let control: String = borsh::from_slice(&bytes_control).unwrap();
assert_eq!(compact, s);
assert_eq!(control, s);
}
}
2 changes: 2 additions & 0 deletions compact_str/src/features/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#[cfg(feature = "arbitrary")]
mod arbitrary;
#[cfg(feature = "borsh")]
mod borsh;
#[cfg(feature = "bytes")]
mod bytes;
#[cfg(feature = "diesel")]
Expand Down
Loading