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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| use std::{fmt, ops::Deref, str};
const INLINE_STRING_MAX_LEN: usize = 30;
struct InlineString { len: u8, data: [u8; INLINE_STRING_MAX_LEN], }
impl InlineString { fn new(input: impl AsRef<str>) -> Self { let bytes = input.as_ref().as_bytes(); let len = bytes.len(); let mut data = [0u8; INLINE_STRING_MAX_LEN]; data[..len].copy_from_slice(bytes); Self { len: len as u8, data, } } }
impl Deref for InlineString { type Target = str; fn deref(&self) -> &Self::Target { str::from_utf8(&self.data[..self.len as usize]).unwrap() } }
impl fmt::Debug for InlineString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.deref()) } }
#[derive(Debug)] enum SmartString { Inline(InlineString), Standard(String), }
impl Deref for SmartString { type Target = str;
fn deref(&self) -> &Self::Target { match *self { SmartString::Inline(ref v) => v.deref(), SmartString::Standard(ref v) => v.deref(), } } }
impl From<&str> for SmartString { fn from(s: &str) -> Self { match s.len() > INLINE_STRING_MAX_LEN { true => SmartString::Standard(s.to_owned()), _ => SmartString::Inline(InlineString::new(s)), } } }
impl fmt::Display for SmartString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.deref()) } }
fn main() { let len1 = std::mem::size_of::<SmartString>(); let len2 = std::mem::size_of::<InlineString>(); println!("Len: SmartString {}, InlineString: {}", len1, len2);
let s1: SmartString = "hello world".into(); let s2 = SmartString::from("这是一个超过了三十个字节的很长很长的字符串"); println!("s1: {:?}, s2: {:?}", s1, s2);
println!( "s1: {}({} bytes, {} chars), s2: {}({} bytes, {} chars)", s1, s1.len(), s1.chars().count(), s2, s2.len(), s2.chars().count() );
assert!(s1.ends_with("world")); assert!(s2.starts_with("这")); }
|