| 1 |
#![cfg_attr(docsrs, doc(cfg(feature = "borsh")))] |
| 2 |
|
| 3 |
use alloc::string::String; |
| 4 |
use alloc::vec::Vec; |
| 5 |
use core::str; |
| 6 |
|
| 7 |
use borsh::io::{Error, ErrorKind, Read, Result, Write}; |
| 8 |
use borsh::{BorshDeserialize, BorshSerialize}; |
| 9 |
|
| 10 |
use crate::repr::MAX_SIZE; |
| 11 |
use crate::CompactString; |
| 12 |
|
| 13 |
impl BorshSerialize for CompactString { |
| 14 |
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> { |
| 15 |
self.as_str().serialize(writer) |
| 16 |
} |
| 17 |
} |
| 18 |
|
| 19 |
impl BorshDeserialize for CompactString { |
| 20 |
fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self> { |
| 21 |
let len = u32::deserialize_reader(&mut *reader)? as usize; |
| 22 |
|
| 23 |
if len <= MAX_SIZE { |
| 24 |
let mut buf = [0u8; MAX_SIZE]; |
| 25 |
reader.read_exact(&mut buf[..len])?; |
| 26 |
let s = str::from_utf8(&buf[..len]) |
| 27 |
.map_err(|err| Error::new(ErrorKind::InvalidData, err))?; |
| 28 |
Ok(CompactString::from(s)) |
| 29 |
} else { |
| 30 |
// We can't just deserialize `Vec` because we have already read the length |
| 31 |
// TODO: replace with `read_buf` when (if) it stabilizes |
| 32 |
let buf = vec_from_reader(len, reader)?; |
| 33 |
let s = |
| 34 |
String::from_utf8(buf).map_err(|err| Error::new(ErrorKind::InvalidData, err))?; |
| 35 |
Ok(CompactString::from(s)) |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
// A copy of hidden `u8::vec_from_reader`(https://docs.rs/borsh/1.5.1/src/borsh/de/mod.rs.html#156-184) |
| 41 |
fn vec_from_reader<R: Read>(len: usize, reader: &mut R) -> Result<Vec<u8>> { |
| 42 |
// Avoid OOM by limiting the size of allocation. This makes the read |
| 43 |
// less efficient (since we need to loop and reallocate) but it protects |
| 44 |
// us from someone sending us [0xff, 0xff, 0xff, 0xff] and forcing us to |
| 45 |
// allocate 4GiB of memory. |
| 46 |
let mut vec = alloc::vec![0u8; len.min(1024 * 1024)]; |
| 47 |
let mut pos = 0; |
| 48 |
while pos < len { |
| 49 |
if pos == vec.len() { |
| 50 |
vec.resize(vec.len().saturating_mul(2).min(len), 0) |
| 51 |
} |
| 52 |
// TODO(mina86): Convert this to read_buf once that stabilises. |
| 53 |
match reader.read(&mut vec.as_mut_slice()[pos..])? { |
| 54 |
0 => { |
| 55 |
return Err(Error::new( |
| 56 |
ErrorKind::InvalidData, |
| 57 |
"Unexpected length of input", |
| 58 |
)) |
| 59 |
} |
| 60 |
read => { |
| 61 |
pos += read; |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
Ok(vec) |
| 66 |
} |
| 67 |
|
| •68 |
#[cfg(all(test, feature = "std"))] |
| 69 |
mod tests { |
| 70 |
use alloc::string::String; |
| 71 |
|
| 72 |
use test_strategy::proptest; |
| 73 |
|
| 74 |
use crate::repr::{HEAP_MASK, MAX_SIZE}; |
| 75 |
use crate::CompactString; |
| 76 |
|
| 77 |
fn assert_roundtrip(s: &str) { |
| 78 |
let bytes_compact = borsh::to_vec(&CompactString::from(s)).unwrap(); |
| 79 |
let bytes_control = borsh::to_vec(&String::from(s)).unwrap(); |
| 80 |
assert_eq!(&*bytes_compact, &*bytes_control); |
| 81 |
|
| 82 |
let compact: CompactString = borsh::from_slice(&bytes_compact).unwrap(); |
| 83 |
let control: String = borsh::from_slice(&bytes_control).unwrap(); |
| 84 |
assert_eq!(compact, s); |
| 85 |
assert_eq!(control, s); |
| 86 |
} |
| 87 |
|
| 88 |
#[test] |
| 89 |
fn test_deserialize_invalid_utf8() { |
| 90 |
let bytes = borsh::to_vec(&[HEAP_MASK; MAX_SIZE] as &[u8]).unwrap(); |
| 91 |
borsh::from_slice::<CompactString>(&bytes).unwrap_err(); |
| 92 |
} |
| 93 |
|
| 94 |
#[test] |
| 95 |
fn test_deserialize_unexpected_eof() { |
| 96 |
let s = core::str::from_utf8(&[b'a'; 55]).unwrap(); |
| 97 |
let mut bytes = borsh::to_vec(s).unwrap(); |
| 98 |
bytes.pop(); |
| 99 |
borsh::from_slice::<CompactString>(&bytes).unwrap_err(); |
| 100 |
} |
| 101 |
|
| 102 |
#[test] |
| 103 |
fn test_roundtrip() { |
| 104 |
assert_roundtrip("Hello, 🌍!"); |
| 105 |
} |
| 106 |
|
| 107 |
#[cfg_attr(miri, ignore)] |
| 108 |
#[proptest] |
| 109 |
fn proptest_roundtrip(s: String) { |
| 110 |
assert_roundtrip(&s); |
| 111 |
} |
| 112 |
} |