1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::fmt;
#[allow(unused)]
const TAG_SIZE: usize = std::mem::size_of::<u8>();
#[allow(unused)]
const MAX_CAPACITY: usize = std::mem::size_of::<crate::string::StdString>() - TAG_SIZE - TAG_SIZE;
#[allow(unused)]
const ALIGNED_CAPACITY: usize = std::mem::size_of::<crate::string::OwnedStr>() - TAG_SIZE;
#[cfg(feature = "max_inline")]
pub(crate) const CAPACITY: usize = MAX_CAPACITY;
#[cfg(not(feature = "max_inline"))]
pub(crate) const CAPACITY: usize = ALIGNED_CAPACITY;
#[derive(Copy, Clone)]
pub(crate) struct InlineString {
len: u8,
array: [u8; CAPACITY],
}
impl InlineString {
#[inline]
pub(crate) fn new(s: &str) -> Self {
let len = s.as_bytes().len();
debug_assert!(len <= CAPACITY);
let mut array = [0; CAPACITY];
array[..len].copy_from_slice(&s.as_bytes());
Self {
len: len as u8,
array,
}
}
#[inline]
pub(crate) fn to_boxed_str(&self) -> Box<str> {
Box::from(self.as_str())
}
#[inline]
pub(crate) fn as_str(&self) -> &str {
let len = self.len as usize;
unsafe {
let slice = self.array.get_unchecked(..len);
std::str::from_utf8_unchecked(slice)
}
}
}
impl fmt::Debug for InlineString {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), f)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_size() {
println!("InlineString: {}", std::mem::size_of::<InlineString>());
}
}