| 1 |
use smallvec::SmallVec; |
| 2 |
|
| 3 |
use super::{Repr, MAX_SIZE}; |
| 4 |
|
| 5 |
impl Repr { |
| 6 |
/// Consumes the [`Repr`] returning a byte vector in a [`SmallVec`] |
| 7 |
/// |
| 8 |
/// Note: both for the inlined case and the heap case, the buffers are re-used |
| 9 |
#[inline] |
| 10 |
pub(crate) fn into_bytes(self) -> SmallVec<[u8; MAX_SIZE]> { |
| 11 |
if let Some(s) = self.as_static_str() { |
| 12 |
SmallVec::from(s.as_bytes()) |
| 13 |
} else if self.is_heap_allocated() { |
| 14 |
let string = self.into_string(); |
| 15 |
let bytes = string.into_bytes(); |
| 16 |
SmallVec::from_vec(bytes) |
| 17 |
} else { |
| 18 |
// SAFETY: We just checked the discriminant to make sure we're an InlineBuffer |
| 19 |
let inline = unsafe { self.into_inline() }; |
| 20 |
let (array, length) = inline.into_array(); |
| 21 |
SmallVec::from_buf_and_len(array, length) |
| 22 |
} |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
#[cfg(test)] |
| 27 |
mod tests { |
| 28 |
use test_case::test_case; |
| 29 |
|
| 30 |
use crate::CompactString; |
| 31 |
|
| 32 |
#[test_case("" ; "empty")] |
| 33 |
#[test_case("abc" ; "short")] |
| 34 |
#[test_case("I am a long string 😊😊😊😊😊" ; "long")] |
| 35 |
fn proptest_roundtrip(s: &'static str) { |
| 36 |
let og_compact = CompactString::from(s); |
| 37 |
assert_eq!(og_compact, s); |
| 38 |
|
| 39 |
let bytes = og_compact.into_bytes(); |
| 40 |
|
| 41 |
let ex_compact = CompactString::from_utf8(bytes).unwrap(); |
| 42 |
assert_eq!(ex_compact, s); |
| 43 |
|
| 44 |
// test `StaticStr` variant |
| 45 |
let og_compact = CompactString::const_new(s); |
| 46 |
assert_eq!(og_compact, s); |
| 47 |
|
| 48 |
let bytes = og_compact.into_bytes(); |
| 49 |
|
| 50 |
let ex_compact = CompactString::from_utf8(bytes).unwrap(); |
| 51 |
assert_eq!(ex_compact, s); |
| 52 |
} |
| 53 |
} |