| 1 |
use super::{Repr, LENGTH_MASK, MAX_SIZE}; |
| 2 |
|
| 3 |
/// A buffer stored on the stack whose size is equal to the stack size of `String` |
| 4 |
#[cfg(target_pointer_width = "64")] |
| 5 |
#[repr(C, align(8))] |
| 6 |
pub(crate) struct InlineBuffer(pub(crate) [u8; MAX_SIZE]); |
| 7 |
|
| 8 |
#[cfg(target_pointer_width = "32")] |
| 9 |
#[repr(C, align(4))] |
| 10 |
pub(crate) struct InlineBuffer(pub(crate) [u8; MAX_SIZE]); |
| 11 |
|
| 12 |
static_assertions::assert_eq_size!(InlineBuffer, Repr); |
| 13 |
static_assertions::assert_eq_align!(InlineBuffer, Repr); |
| 14 |
|
| 15 |
impl InlineBuffer { |
| 16 |
/// Construct a new [`InlineString`]. A string that lives in a small buffer on the stack |
| 17 |
/// |
| 18 |
/// SAFETY: |
| 19 |
/// * The caller must guarantee that the length of `text` is less than [`MAX_SIZE`] |
| 20 |
#[inline] |
| 21 |
#[cfg(all(target_pointer_width = "64", target_endian = "little"))] |
| 22 |
pub(crate) unsafe fn new(text: &str) -> Self { |
| 23 |
debug_assert!(text.len() <= MAX_SIZE); |
| 24 |
|
| 25 |
use core::ptr::read_unaligned as load; |
| 26 |
|
| 27 |
let len = text.len(); |
| 28 |
let src = text.as_ptr(); |
| 29 |
|
| 30 |
// Note(parker): This implementation builds an `InlineBuffer` entirely in |
| 31 |
// registers. It solves a long standing performance issue `compact_str` has had |
| 32 |
// since it's creation. |
| 33 |
// The simple implementation is to copy the string into a stack buffer of |
| 34 |
// MAX_SIZE. Via our `copy_small` helper or libc's `memcpy` function, it is |
| 35 |
// executed as two overlapping stores. |
| 36 |
// |
| 37 |
// For example, the string "hello world" is copied as two 8-byte ops: |
| 38 |
// |
| 39 |
// 1. "hello wo" into [0, 7] |
| 40 |
// 2. "lo world" into [3, 10] |
| 41 |
// |
| 42 |
// Then we have do a _third_ store to the final byte for the length. |
| 43 |
// |
| 44 |
// ( Note: we also need to consider the stores that zero the original buffer, but |
| 45 |
// for illustrative purposes considering just "hello world" is enough ) |
| 46 |
// |
| 47 |
// Immediately after, the stack buffer gets moved, returned as a Repr and then to |
| 48 |
// the user as a CompactString. These consumers read the data as _whole aligned words_. |
| 49 |
// At this point the data is in the CPU's store buffer, not yet written out to |
| 50 |
// the L1 cache. |
| 51 |
// |
| 52 |
// Enter the ~~SPOOKY ZONE~~ of micro-architectures. |
| 53 |
// |
| 54 |
// On Intel, the CPU can forward a load from the store buffer __if the load is |
| 55 |
// fully contained within a single store__. Our issue is that the first word/8-bytes |
| 56 |
// _overlaps two stores_ and thus causes a pipeline hazard |
| 57 |
// Apple's `aarch64` can forward multi-store loads, so this is less of a problem |
| 58 |
// there. |
| 59 |
// |
| 60 |
// |
| 61 |
// Below, we build an `InlineBuffer` in registers, replacing the overlapping |
| 62 |
// stores. Afterwards, the buffer is materialized with at most three aligned |
| 63 |
// non-overlapping stores, or kept in registers entirely. |
| 64 |
|
| 65 |
let last_byte = (len as u64 | LENGTH_MASK as u64) << 56; |
| 66 |
|
| 67 |
let (w0, w1, w2); |
| 68 |
if len >= 16 { |
| 69 |
// SAFETY: `len >= 16` means `src` is valid for 16 bytes. and `src + len - 8` |
| 70 |
// is valid for 8 bytes because `len <= text.len()`. |
| 71 |
w0 = load(src as *const u64); |
| 72 |
w1 = load(src.add(8) as *const u64); |
| 73 |
// N.B. For any length < MAX_SIZE, this is an overlaping read of `w1` and the |
| 74 |
// tail of the string. |
| 75 |
let tail = load(src.add(len - 8) as *const u64); |
| 76 |
|
| 77 |
// bytes `[16, len)` of the string are the top `len - 16` bytes of `tail`. |
| 78 |
let data = if len == 16 { |
| 79 |
0 |
| 80 |
} else { |
| 81 |
tail >> ((MAX_SIZE - len) * 8) |
| 82 |
}; |
| 83 |
w2 = if len == MAX_SIZE { |
| 84 |
data |
| 85 |
} else { |
| 86 |
data | last_byte |
| 87 |
}; |
| 88 |
} else if len >= 8 { |
| 89 |
// SAFETY: `src` is valid for `len >= 8` bytes. |
| 90 |
w0 = load(src as *const u64); |
| 91 |
// N.B. Overlapping load with w0 for the tail of the string. |
| 92 |
let tail = load(src.add(len - 8) as *const u64); |
| 93 |
|
| 94 |
// bytes `[8, len)` of the string are the top `len - 8` bytes of `tail` |
| 95 |
w1 = if len == 8 { |
| 96 |
0 |
| 97 |
} else { |
| 98 |
tail >> ((16 - len) * 8) |
| 99 |
}; |
| 100 |
w2 = last_byte; |
| 101 |
} else if len >= 4 { |
| 102 |
// SAFETY: `src` is valid for `len >= 4` bytes. |
| 103 |
let head = load(src as *const u32) as u64; |
| 104 |
let tail = load(src.add(len - 4) as *const u32) as u64; |
| 105 |
w0 = head | (tail << ((len - 4) * 8)); |
| 106 |
w1 = 0; |
| 107 |
w2 = last_byte; |
| 108 |
} else if len >= 2 { |
| 109 |
// SAFETY: `src` is valid for `len >= 2` bytes. |
| 110 |
let head = load(src as *const u16) as u64; |
| 111 |
let tail = load(src.add(len - 2) as *const u16) as u64; |
| 112 |
w0 = head | (tail << ((len - 2) * 8)); |
| 113 |
w1 = 0; |
| 114 |
w2 = last_byte; |
| 115 |
} else if len == 1 { |
| 116 |
w0 = *src as u64; |
| 117 |
w1 = 0; |
| 118 |
w2 = last_byte; |
| 119 |
} else { |
| 120 |
w0 = 0; |
| 121 |
w1 = 0; |
| 122 |
w2 = last_byte; |
| 123 |
} |
| 124 |
|
| 125 |
// SAFETY: `[u64; 3]` and `InlineBuffer` have the same size, and on little-endian |
| 126 |
// the byte order of the words matches the byte order of the buffer. |
| 127 |
core::mem::transmute([w0, w1, w2]) |
| 128 |
} |
| 129 |
|
| 130 |
/// Construct a new [`InlineString`]. A string that lives in a small buffer on the stack |
| 131 |
/// |
| 132 |
/// SAFETY: |
| 133 |
/// * The caller must guarantee that the length of `text` is less than [`MAX_SIZE`] |
| 134 |
#[inline] |
| 135 |
#[cfg(not(all(target_pointer_width = "64", target_endian = "little")))] |
| 136 |
pub(crate) unsafe fn new(text: &str) -> Self { |
| 137 |
debug_assert!(text.len() <= MAX_SIZE); |
| 138 |
|
| 139 |
let len = text.len(); |
| 140 |
let mut buffer = InlineBuffer([0u8; MAX_SIZE]); |
| 141 |
|
| 142 |
// set the length in the last byte |
| 143 |
buffer.0[MAX_SIZE - 1] = len as u8 | LENGTH_MASK; |
| 144 |
|
| 145 |
// copy the string into our buffer |
| 146 |
// |
| 147 |
// note: in the case where len == MAX_SIZE, we'll overwrite the len, but that's okay because |
| 148 |
// when reading the length we can detect that the last byte is part of UTF-8 and return a |
| 149 |
// length of MAX_SIZE |
| 150 |
// |
| 151 |
// SAFETY: |
| 152 |
// * src (`text`) is valid for `len` bytes because `len` comes from `text` |
| 153 |
// * dst (`buffer`) is valid for `len` bytes because we assert src is less than MAX_SIZE |
| 154 |
// * src and dst don't overlap because we created dst |
| 155 |
// |
| 156 |
super::copy_small(text.as_ptr(), buffer.0.as_mut_ptr(), len); |
| 157 |
|
| 158 |
buffer |
| 159 |
} |
| 160 |
|
| 161 |
#[inline] |
| 162 |
pub(crate) const fn new_const(text: &str) -> Self { |
| 163 |
if text.len() > MAX_SIZE { |
| 164 |
panic!("Provided string has a length greater than our MAX_SIZE"); |
| 165 |
} |
| 166 |
|
| 167 |
let len = text.len(); |
| 168 |
let mut buffer = [0u8; MAX_SIZE]; |
| 169 |
|
| 170 |
// set the length |
| 171 |
buffer[MAX_SIZE - 1] = len as u8 | LENGTH_MASK; |
| 172 |
|
| 173 |
// Note: for loops aren't allowed in `const fn`, hence the while. |
| 174 |
// Note: Iterating forward results in badly optimized code, because the compiler tries to |
| 175 |
// unroll the loop. |
| 176 |
let text = text.as_bytes(); |
| 177 |
let mut i = len; |
| 178 |
while i > 0 { |
| 179 |
buffer[i - 1] = text[i - 1]; |
| 180 |
i -= 1; |
| 181 |
} |
| 182 |
|
| 183 |
InlineBuffer(buffer) |
| 184 |
} |
| 185 |
|
| 186 |
/// Returns an empty [`InlineBuffer`] |
| 187 |
#[inline(always)] |
| 188 |
pub(crate) const fn empty() -> Self { |
| 189 |
Self::new_const("") |
| 190 |
} |
| 191 |
|
| 192 |
/// Consumes the [`InlineBuffer`] returning the entire underlying array and the length of the |
| 193 |
/// string that it contains |
| 194 |
#[inline] |
| 195 |
#[cfg(feature = "smallvec")] |
| 196 |
pub(crate) fn into_array(self) -> ([u8; MAX_SIZE], usize) { |
| 197 |
let mut buffer = self.0; |
| 198 |
|
| 199 |
let length = core::cmp::min( |
| 200 |
(buffer[MAX_SIZE - 1].wrapping_sub(LENGTH_MASK)) as usize, |
| 201 |
MAX_SIZE, |
| 202 |
); |
| 203 |
|
| 204 |
let last_byte_ref = &mut buffer[MAX_SIZE - 1]; |
| 205 |
|
| 206 |
// unset the last byte of the buffer if it's just storing the length of the string |
| 207 |
// |
| 208 |
// Note: we should never add an `else` statement here, keeping the conditional simple allows |
| 209 |
// the compiler to optimize this to a conditional-move instead of a branch |
| 210 |
if length < MAX_SIZE { |
| 211 |
*last_byte_ref = 0; |
| 212 |
} |
| 213 |
|
| 214 |
(buffer, length) |
| 215 |
} |
| 216 |
|
| 217 |
/// Set's the length of the content for this [`InlineBuffer`] |
| 218 |
/// |
| 219 |
/// # SAFETY: |
| 220 |
/// * The caller must guarantee that `len` bytes in the buffer are valid UTF-8 |
| 221 |
#[inline] |
| 222 |
pub(crate) unsafe fn set_len(&mut self, len: usize) { |
| 223 |
debug_assert!(len <= MAX_SIZE); |
| 224 |
|
| 225 |
// If `length` == MAX_SIZE, then we infer the length to be the capacity of the buffer. We |
| 226 |
// can infer this because the way we encode length doesn't overlap with any valid UTF-8 |
| 227 |
// bytes |
| 228 |
if len < MAX_SIZE { |
| 229 |
self.0[MAX_SIZE - 1] = len as u8 | LENGTH_MASK; |
| 230 |
} |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
#[cfg(test)] |
| 235 |
mod tests { |
| 236 |
#[test] |
| 237 |
#[ignore] // we run this in CI, but unless you're compiling in release, this takes a while |
| 238 |
fn test_unused_utf8_bytes() { |
| 239 |
use rayon::prelude::*; |
| 240 |
|
| 241 |
// test to validate for all char the first and last bytes are never within a specified range |
| 242 |
// note: according to the UTF-8 spec it shouldn't be, but we double check that here |
| 243 |
(0..u32::MAX).into_par_iter().for_each(|i| { |
| 244 |
if let Ok(c) = char::try_from(i) { |
| 245 |
let mut buf = [0_u8; 4]; |
| 246 |
c.encode_utf8(&mut buf); |
| 247 |
|
| 248 |
// check ranges for first byte |
| 249 |
match buf[0] { |
| 250 |
x @ 128..=191 => panic!("first byte within 128..=191, {}", x), |
| 251 |
x @ 248..=255 => panic!("first byte within 248..=255, {}", x), |
| 252 |
_ => (), |
| 253 |
} |
| 254 |
|
| 255 |
// check ranges for last byte |
| 256 |
if let x @ 192..=255 = buf[c.len_utf8() - 1] { |
| 257 |
panic!("last byte within 192..=255, {}", x) |
| 258 |
} |
| 259 |
} |
| 260 |
}) |
| 261 |
} |
| 262 |
|
| 263 |
#[cfg(feature = "smallvec")] |
| 264 |
mod smallvec { |
| 265 |
use alloc::string::String; |
| 266 |
|
| 267 |
use quickcheck_macros::quickcheck; |
| 268 |
|
| 269 |
use crate::repr::{InlineBuffer, MAX_SIZE}; |
| 270 |
|
| 271 |
#[test] |
| 272 |
fn test_into_array() { |
| 273 |
let s = "hello world!"; |
| 274 |
|
| 275 |
let inline = unsafe { InlineBuffer::new(s) }; |
| 276 |
let (array, length) = inline.into_array(); |
| 277 |
|
| 278 |
assert_eq!(s.len(), length); |
| 279 |
|
| 280 |
// all bytes after the length should be 0 |
| 281 |
assert!(array[length..].iter().all(|b| *b == 0)); |
| 282 |
|
| 283 |
// taking a string slice should give back the same string as the original |
| 284 |
let ex_s = unsafe { core::str::from_utf8_unchecked(&array[..length]) }; |
| 285 |
assert_eq!(s, ex_s); |
| 286 |
} |
| 287 |
|
| 288 |
#[quickcheck] |
| 289 |
#[cfg_attr(miri, ignore)] |
| 290 |
fn quickcheck_into_array(s: String) { |
| 291 |
let mut total_length = 0; |
| 292 |
let s: String = s |
| 293 |
.chars() |
| 294 |
.take_while(|c| { |
| 295 |
total_length += c.len_utf8(); |
| 296 |
total_length < MAX_SIZE |
| 297 |
}) |
| 298 |
.collect(); |
| 299 |
|
| 300 |
let inline = unsafe { InlineBuffer::new(&s) }; |
| 301 |
let (array, length) = inline.into_array(); |
| 302 |
assert_eq!(s.len(), length); |
| 303 |
|
| 304 |
// all bytes after the length should be 0 |
| 305 |
assert!(array[length..].iter().all(|b| *b == 0)); |
| 306 |
|
| 307 |
// taking a string slice should give back the same string as the original |
| 308 |
let ex_s = unsafe { core::str::from_utf8_unchecked(&array[..length]) }; |
| 309 |
assert_eq!(s, ex_s); |
| 310 |
} |
| 311 |
} |
| 312 |
} |