| 1 |
use core::str::Utf8Error; |
| 2 |
|
| 3 |
use bytes::Buf; |
| 4 |
|
| 5 |
use super::{Repr, MAX_SIZE}; |
| 6 |
use crate::UnwrapWithMsg; |
| 7 |
|
| 8 |
impl Repr { |
| 9 |
/// Converts a [`Buf`] of bytes to a [`Repr`], checking that the provided bytes are valid UTF-8 |
| 10 |
pub(crate) fn from_utf8_buf<B: Buf>(buf: &mut B) -> Result<Self, Utf8Error> { |
| 11 |
// SAFETY: We check below to make sure the provided buffer is valid UTF-8 |
| 12 |
let (repr, bytes_written) = unsafe { Self::collect_buf(buf) }; |
| 13 |
|
| 14 |
// Check to make sure the provided bytes are valid UTF-8, return the Repr if they are! |
| 15 |
match core::str::from_utf8(&repr.as_slice()[..bytes_written]) { |
| 16 |
Ok(_) => Ok(repr), |
| 17 |
Err(e) => Err(e), |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
/// Converts a [`Buf`] of bytes to a [`Repr`], without checking for valid UTF-8 |
| 22 |
/// |
| 23 |
/// # Safety |
| 24 |
/// * The provided buffer must be valid UTF-8 |
| 25 |
pub(crate) unsafe fn from_utf8_buf_unchecked<B: Buf>(buf: &mut B) -> Self { |
| 26 |
let (repr, _bytes_written) = Self::collect_buf(buf); |
| 27 |
repr |
| 28 |
} |
| 29 |
|
| 30 |
/// Collects the bytes from a [`Buf`] into a [`Repr`] |
| 31 |
/// |
| 32 |
/// # Safety |
| 33 |
/// * The caller must guarantee that `buf` is valid UTF-8 |
| 34 |
unsafe fn collect_buf<B: Buf>(buf: &mut B) -> (Self, usize) { |
| 35 |
// Get an empty Repr we can write into |
| 36 |
let mut repr = super::EMPTY; |
| 37 |
let mut bytes_written = 0; |
| 38 |
|
| 39 |
debug_assert_eq!(repr.len(), bytes_written); |
| 40 |
|
| 41 |
while buf.has_remaining() { |
| 42 |
let chunk = buf.chunk(); |
| 43 |
let chunk_len = chunk.len(); |
| 44 |
|
| 45 |
// There's an edge case where the final byte of this buffer == `HEAP_MASK`, which is |
| 46 |
// invalid UTF-8, but would result in us creating an inline variant, that identifies as |
| 47 |
// a heap variant. If a user ever tried to reference the data at all, we'd incorrectly |
| 48 |
// try and read data from an invalid memory address, causing undefined behavior. |
| 49 |
if bytes_written < MAX_SIZE && bytes_written + chunk_len == MAX_SIZE { |
| 50 |
let last_byte = chunk[chunk_len - 1]; |
| 51 |
// If we hit the edge case, reserve additional space to make the repr becomes heap |
| 52 |
// allocated, which prevents us from writing this last byte inline |
| 53 |
if last_byte >= 0b11000000 { |
| 54 |
repr.reserve(MAX_SIZE + 1).unwrap_with_msg(); |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
// reserve at least enough space to fit this chunk |
| 59 |
repr.reserve(chunk_len).unwrap_with_msg(); |
| 60 |
|
| 61 |
// Write the chunk into the spare capacity without first creating a reference to the |
| 62 |
// uninitialized memory. |
| 63 |
// |
| 64 |
// SAFETY: |
| 65 |
// * `reserve` guarantees at least `bytes_written + chunk_len` bytes of capacity. |
| 66 |
// * `chunk` is valid for reads of `chunk_len` bytes. |
| 67 |
// * `chunk` belongs to `buf`, so it cannot overlap `repr`. |
| 68 |
repr.as_mut_ptr() |
| 69 |
.add(bytes_written) |
| 70 |
.copy_from_nonoverlapping(chunk.as_ptr(), chunk_len); |
| 71 |
|
| 72 |
// Set the length of the Repr |
| 73 |
// SAFETY: We just wrote an additional `chunk_len` bytes into the Repr |
| 74 |
bytes_written += chunk_len; |
| 75 |
repr.set_len(bytes_written); |
| 76 |
|
| 77 |
// advance the pointer of the buffer |
| 78 |
buf.advance(chunk_len); |
| 79 |
} |
| 80 |
|
| 81 |
(repr, bytes_written) |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
#[cfg(test)] |
| 86 |
mod test { |
| 87 |
#[cfg(feature = "std")] |
| 88 |
use std::io::Cursor; |
| 89 |
|
| 90 |
use test_case::test_case; |
| 91 |
|
| 92 |
use super::Repr; |
| 93 |
|
| 94 |
#[test_case(""; "empty")] |
| 95 |
#[test_case("hello world"; "short")] |
| 96 |
#[test_case("hello, this is a long string which should be heap allocated"; "long")] |
| 97 |
fn test_from_utf8_buf(word: &'static str) { |
| 98 |
let mut buf = Cursor::new(word.as_bytes()); |
| 99 |
let repr = Repr::from_utf8_buf(&mut buf).unwrap(); |
| 100 |
|
| 101 |
assert_eq!(repr.as_str(), word); |
| 102 |
assert_eq!(repr.len(), word.len()); |
| 103 |
} |
| 104 |
|
| 105 |
#[test] |
| 106 |
fn test_from_utf8_packed() { |
| 107 |
cfg_if::cfg_if! { |
| 108 |
if #[cfg(target_pointer_width = "64")] { |
| 109 |
let packed = "this string is 24 chars!"; |
| 110 |
} else if #[cfg(target_pointer_width = "32")] { |
| 111 |
let packed = "i am 12 char"; |
| 112 |
} else { |
| 113 |
compile_error!("unsupported architecture!") |
| 114 |
} |
| 115 |
} |
| 116 |
let mut buf = Cursor::new(packed.as_bytes()); |
| 117 |
|
| 118 |
let repr = Repr::from_utf8_buf(&mut buf).unwrap(); |
| 119 |
assert_eq!(repr.as_str(), packed); |
| 120 |
|
| 121 |
// This repr should __not__ be heap allocated |
| 122 |
assert!(!repr.is_heap_allocated()); |
| 123 |
} |
| 124 |
|
| 125 |
#[test] |
| 126 |
fn test_fuzz_panic() { |
| 127 |
let bytes = &[ |
| 128 |
255, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 12, 0, 0, 96, |
| 129 |
]; |
| 130 |
let mut buf: Cursor<&[u8]> = Cursor::new(bytes); |
| 131 |
|
| 132 |
assert!(Repr::from_utf8_buf(&mut buf).is_err()); |
| 133 |
} |
| 134 |
|
| 135 |
#[test] |
| 136 |
fn test_valid_repr_but_invalid_utf8() { |
| 137 |
let bytes = &[ |
| 138 |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, |
| 139 |
]; |
| 140 |
let mut buf: Cursor<&[u8]> = Cursor::new(bytes); |
| 141 |
|
| 142 |
assert!(Repr::from_utf8_buf(&mut buf).is_err()); |
| 143 |
} |
| 144 |
|
| 145 |
#[test] |
| 146 |
fn test_fake_heap_variant() { |
| 147 |
let bytes = &[ |
| 148 |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, |
| 149 |
]; |
| 150 |
let mut buf: Cursor<&[u8]> = Cursor::new(bytes); |
| 151 |
|
| 152 |
assert!(Repr::from_utf8_buf(&mut buf).is_err()); |
| 153 |
} |
| 154 |
|
| 155 |
#[test] |
| 156 |
fn test_from_non_contiguous() { |
| 157 |
let data = [ |
| 158 |
211, 247, 211, 247, 121, 135, 151, 255, 126, 205, 255, 204, 211, 51, 51, 0, 52, 55, |
| 159 |
247, 204, 45, 37, 44, 210, 132, 50, 206, 121, 135, 151, 255, 126, 205, 255, 204, 211, |
| 160 |
51, 51, 0, 52, 55, 247, 204, 45, 44, 210, 132, 50, 206, 51, |
| 161 |
]; |
| 162 |
let (front, back) = data.split_at(data.len() / 2 + 1); |
| 163 |
let mut queue = alloc::collections::VecDeque::with_capacity(data.len()); |
| 164 |
|
| 165 |
// create a non-contiguous slice of memory in queue |
| 166 |
front.iter().copied().for_each(|x| queue.push_back(x)); |
| 167 |
back.iter().copied().for_each(|x| queue.push_front(x)); |
| 168 |
|
| 169 |
// make sure it's non-contiguous |
| 170 |
let (a, b) = queue.as_slices(); |
| 171 |
assert!(data.is_empty() || !a.is_empty()); |
| 172 |
assert!(data.is_empty() || !b.is_empty()); |
| 173 |
|
| 174 |
assert_eq!(data.len(), queue.len()); |
| 175 |
assert!(Repr::from_utf8_buf(&mut queue).is_err()); |
| 176 |
} |
| 177 |
|
| 178 |
#[test] |
| 179 |
#[should_panic(expected = "Utf8Error")] |
| 180 |
fn test_invalid_utf8() { |
| 181 |
let invalid = &[0, 159]; |
| 182 |
let mut buf: Cursor<&[u8]> = Cursor::new(invalid); |
| 183 |
|
| 184 |
Repr::from_utf8_buf(&mut buf).unwrap(); |
| 185 |
} |
| 186 |
} |