|
| 1 | +/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 | + |
| 5 | +use std::borrow::{Borrow, Cow}; |
| 6 | +use std::cmp; |
| 7 | +use std::fmt; |
| 8 | +use std::hash; |
| 9 | +use std::marker::PhantomData; |
| 10 | +use std::mem; |
| 11 | +use std::ops::Deref; |
| 12 | +use std::slice; |
| 13 | +use std::str; |
| 14 | + |
| 15 | +// All bits set except the highest |
| 16 | +const MAX_LEN: usize = !0 >> 1; |
| 17 | + |
| 18 | +// Only the highest bit |
| 19 | +const OWNED_TAG: usize = MAX_LEN + 1; |
| 20 | + |
| 21 | +/// Like `Cow<'a, str>`, but with smaller `std::mem::size_of`. (Two words instead of four.) |
| 22 | +pub struct CompactCowStr<'a> { |
| 23 | + // `tagged_len` is a tag in its highest bit, and the string length in the rest of the bits. |
| 24 | + // |
| 25 | + // * If the tag is 1, the memory pointed to by `ptr` is owned |
| 26 | + // and the lifetime parameter is irrelevant. |
| 27 | + // `ptr` and `len` are the components of a `Box<str>`. |
| 28 | + // |
| 29 | + // * If the tag is 0, the memory is borrowed. |
| 30 | + // `ptr` and `len` are the components of a `&'a str`. |
| 31 | + |
| 32 | + // FIXME: https://github.com/rust-lang/rust/issues/27730 use NonZero or Shared |
| 33 | + ptr: *const u8, |
| 34 | + tagged_len: usize, |
| 35 | + phantom: PhantomData<&'a str>, |
| 36 | +} |
| 37 | + |
| 38 | +impl<'a> From<&'a str> for CompactCowStr<'a> { |
| 39 | + #[inline] |
| 40 | + fn from(s: &'a str) -> Self { |
| 41 | + let len = s.len(); |
| 42 | + assert!(len <= MAX_LEN); |
| 43 | + CompactCowStr { |
| 44 | + ptr: s.as_ptr(), |
| 45 | + tagged_len: len, |
| 46 | + phantom: PhantomData, |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl<'a> From<Box<str>> for CompactCowStr<'a> { |
| 52 | + #[inline] |
| 53 | + fn from(s: Box<str>) -> Self { |
| 54 | + let ptr = s.as_ptr(); |
| 55 | + let len = s.len(); |
| 56 | + assert!(len <= MAX_LEN); |
| 57 | + mem::forget(s); |
| 58 | + CompactCowStr { |
| 59 | + ptr: ptr, |
| 60 | + tagged_len: len | OWNED_TAG, |
| 61 | + phantom: PhantomData, |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +impl<'a> CompactCowStr<'a> { |
| 67 | + /// Whether this string refers to borrowed memory |
| 68 | + /// (as opposed to owned, which would be freed when `CompactCowStr` goes out of scope). |
| 69 | + #[inline] |
| 70 | + pub fn is_borrowed(&self) -> bool { |
| 71 | + (self.tagged_len & OWNED_TAG) == 0 |
| 72 | + } |
| 73 | + |
| 74 | + /// The length of this string |
| 75 | + #[inline] |
| 76 | + pub fn len(&self) -> usize { |
| 77 | + self.tagged_len & !OWNED_TAG |
| 78 | + } |
| 79 | + |
| 80 | + // Intentionally private since it is easy to use incorrectly. |
| 81 | + #[inline] |
| 82 | + fn as_raw_str(&self) -> *const str { |
| 83 | + unsafe { |
| 84 | + str::from_utf8_unchecked(slice::from_raw_parts(self.ptr, self.len())) |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + /// If this string is borrowed, return a slice with the original lifetime, |
| 89 | + /// not borrowing `self`. |
| 90 | + /// |
| 91 | + /// (`Deref` is implemented unconditionally, but returns a slice with a shorter lifetime.) |
| 92 | + #[inline] |
| 93 | + pub fn as_str(&self) -> Option<&'a str> { |
| 94 | + if self.is_borrowed() { |
| 95 | + Some(unsafe { &*self.as_raw_str() }) |
| 96 | + } else { |
| 97 | + None |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + /// Convert into `String`, re-using the memory allocation if it was already owned. |
| 102 | + #[inline] |
| 103 | + pub fn into_owned(self) -> String { |
| 104 | + unsafe { |
| 105 | + let raw = self.as_raw_str(); |
| 106 | + let is_borrowed = self.is_borrowed(); |
| 107 | + mem::forget(self); |
| 108 | + if is_borrowed { |
| 109 | + String::from(&*raw) |
| 110 | + } else { |
| 111 | + Box::from_raw(raw as *mut str).into_string() |
| 112 | + } |
| 113 | + } |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +impl<'a> Clone for CompactCowStr<'a> { |
| 118 | + #[inline] |
| 119 | + fn clone(&self) -> Self { |
| 120 | + if self.is_borrowed() { |
| 121 | + CompactCowStr { ..*self } |
| 122 | + } else { |
| 123 | + Self::from(String::from(&**self).into_boxed_str()) |
| 124 | + } |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +impl<'a> Drop for CompactCowStr<'a> { |
| 129 | + #[inline] |
| 130 | + fn drop(&mut self) { |
| 131 | + if !self.is_borrowed() { |
| 132 | + unsafe { |
| 133 | + Box::from_raw(self.as_raw_str() as *mut str); |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +impl<'a> Deref for CompactCowStr<'a> { |
| 140 | + type Target = str; |
| 141 | + |
| 142 | + #[inline] |
| 143 | + fn deref(&self) -> &str { |
| 144 | + unsafe { |
| 145 | + &*self.as_raw_str() |
| 146 | + } |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +impl<'a> From<CompactCowStr<'a>> for Cow<'a, str> { |
| 151 | + #[inline] |
| 152 | + fn from(cow: CompactCowStr<'a>) -> Self { |
| 153 | + unsafe { |
| 154 | + let raw = cow.as_raw_str(); |
| 155 | + if cow.is_borrowed() { |
| 156 | + Cow::Borrowed(&*raw) |
| 157 | + } else { |
| 158 | + Cow::Owned(Box::from_raw(raw as *mut str).into_string()) |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +impl<'a> From<String> for CompactCowStr<'a> { |
| 165 | + #[inline] |
| 166 | + fn from(s: String) -> Self { |
| 167 | + Self::from(s.into_boxed_str()) |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +impl<'a> From<Cow<'a, str>> for CompactCowStr<'a> { |
| 172 | + #[inline] |
| 173 | + fn from(s: Cow<'a, str>) -> Self { |
| 174 | + match s { |
| 175 | + Cow::Borrowed(s) => Self::from(s), |
| 176 | + Cow::Owned(s) => Self::from(s), |
| 177 | + } |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +impl<'a> AsRef<str> for CompactCowStr<'a> { |
| 182 | + #[inline] |
| 183 | + fn as_ref(&self) -> &str { |
| 184 | + self |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +impl<'a> Borrow<str> for CompactCowStr<'a> { |
| 189 | + #[inline] |
| 190 | + fn borrow(&self) -> &str { |
| 191 | + self |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +impl<'a> Default for CompactCowStr<'a> { |
| 196 | + #[inline] |
| 197 | + fn default() -> Self { |
| 198 | + Self::from("") |
| 199 | + } |
| 200 | +} |
| 201 | + |
| 202 | +impl<'a> hash::Hash for CompactCowStr<'a> { |
| 203 | + #[inline] |
| 204 | + fn hash<H: hash::Hasher>(&self, hasher: &mut H) { |
| 205 | + str::hash(self, hasher) |
| 206 | + } |
| 207 | +} |
| 208 | + |
| 209 | +impl<'a, T: AsRef<str>> PartialEq<T> for CompactCowStr<'a> { |
| 210 | + #[inline] |
| 211 | + fn eq(&self, other: &T) -> bool { |
| 212 | + str::eq(self, other.as_ref()) |
| 213 | + } |
| 214 | +} |
| 215 | + |
| 216 | +impl<'a, T: AsRef<str>> PartialOrd<T> for CompactCowStr<'a> { |
| 217 | + #[inline] |
| 218 | + fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> { |
| 219 | + str::partial_cmp(self, other.as_ref()) |
| 220 | + } |
| 221 | +} |
| 222 | + |
| 223 | +impl<'a> Eq for CompactCowStr<'a> {} |
| 224 | + |
| 225 | +impl<'a> Ord for CompactCowStr<'a> { |
| 226 | + #[inline] |
| 227 | + fn cmp(&self, other: &Self) -> cmp::Ordering { |
| 228 | + str::cmp(self, other) |
| 229 | + } |
| 230 | +} |
| 231 | + |
| 232 | +impl<'a> fmt::Display for CompactCowStr<'a> { |
| 233 | + #[inline] |
| 234 | + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 235 | + str::fmt(self, formatter) |
| 236 | + } |
| 237 | +} |
| 238 | + |
| 239 | +impl<'a> fmt::Debug for CompactCowStr<'a> { |
| 240 | + #[inline] |
| 241 | + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 242 | + str::fmt(self, formatter) |
| 243 | + } |
| 244 | +} |
0 commit comments