|
| 1 | +//! String primitives built around `FuriString`. |
| 2 | +
|
| 3 | +use core::{ |
| 4 | + cmp::Ordering, |
| 5 | + convert::Infallible, |
| 6 | + ffi::{c_char, CStr}, |
| 7 | + fmt, |
| 8 | +}; |
| 9 | + |
| 10 | +#[cfg(feature = "alloc")] |
| 11 | +use alloc::{borrow::Cow, boxed::Box, ffi::CString}; |
| 12 | + |
| 13 | +use flipperzero_sys as sys; |
| 14 | + |
| 15 | +/// A Furi string. |
| 16 | +/// |
| 17 | +/// This is similar to Rust's [`CString`] in that it represents an owned, C-compatible, |
| 18 | +/// nul-terminated string with no nul bytes in the middle. It also has additional methods |
| 19 | +/// to provide the flexibility of Rust's [`String`]. It is used in various APIs of the |
| 20 | +/// Flipper Zero SDK. |
| 21 | +/// |
| 22 | +/// This type does not requre the `alloc` feature flag, because it does not use the Rust |
| 23 | +/// allocator. Very short strings (7 bytes or fewer) are stored directly inside the |
| 24 | +/// `FuriString` struct (which is stored on the heap), while longer strings are allocated |
| 25 | +/// on the heap by the Flipper Zero firmware. |
| 26 | +#[derive(Eq)] |
| 27 | +pub struct String(*mut sys::FuriString); |
| 28 | + |
| 29 | +impl Drop for String { |
| 30 | + fn drop(&mut self) { |
| 31 | + unsafe { sys::furi_string_free(self.0) }; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +// Implementations matching `std::string::String`. |
| 36 | +impl String { |
| 37 | + /// Creates a new empty `String`. |
| 38 | + #[inline] |
| 39 | + #[must_use] |
| 40 | + pub fn new() -> Self { |
| 41 | + String(unsafe { sys::furi_string_alloc() }) |
| 42 | + } |
| 43 | + |
| 44 | + /// Creates a new empty `String` with at least the specified capacity. |
| 45 | + #[inline] |
| 46 | + #[must_use] |
| 47 | + pub fn with_capacity(capacity: usize) -> Self { |
| 48 | + let s = Self::new(); |
| 49 | + // The size passed to `sys::furi_string_reserve` needs to include the nul |
| 50 | + // terminator. |
| 51 | + unsafe { sys::furi_string_reserve(s.0, capacity + 1) }; |
| 52 | + s |
| 53 | + } |
| 54 | + |
| 55 | + /// Extracts a `CStr` containing the entire string slice, with nul termination. |
| 56 | + #[inline] |
| 57 | + #[must_use] |
| 58 | + pub fn as_c_str(&self) -> &CStr { |
| 59 | + unsafe { CStr::from_ptr(sys::furi_string_get_cstr(self.0)) } |
| 60 | + } |
| 61 | + |
| 62 | + /// Appends a given `String` onto the end of this `String`. |
| 63 | + #[inline] |
| 64 | + pub fn push_string(&mut self, string: &String) { |
| 65 | + unsafe { sys::furi_string_cat(self.0, string.0) } |
| 66 | + } |
| 67 | + |
| 68 | + /// Appends a given Rust `str` onto the end of this `String`. |
| 69 | + #[inline] |
| 70 | + pub fn push_rust_str(&mut self, string: &str) { |
| 71 | + self.extend(string.chars()); |
| 72 | + } |
| 73 | + |
| 74 | + /// Appends a given `CStr` onto the end of this `String`. |
| 75 | + #[inline] |
| 76 | + pub fn push_c_str(&mut self, string: &CStr) { |
| 77 | + unsafe { sys::furi_string_cat_str(self.0, string.as_ptr()) } |
| 78 | + } |
| 79 | + |
| 80 | + /// Reserves capacity for at least `additional` bytes more than the current length. |
| 81 | + #[inline] |
| 82 | + pub fn reserve(&mut self, additional: usize) { |
| 83 | + // `self.len()` counts the number of bytes excluding the terminating nul, but the |
| 84 | + // size passed to `sys::furi_string_reserve` needs to include the nul terminator. |
| 85 | + unsafe { sys::furi_string_reserve(self.0, self.len() + additional + 1) }; |
| 86 | + } |
| 87 | + |
| 88 | + /// Appends the given [`char`] to the end of this `String`. |
| 89 | + #[inline] |
| 90 | + pub fn push(&mut self, ch: char) { |
| 91 | + match ch.len_utf8() { |
| 92 | + 1 => unsafe { sys::furi_string_push_back(self.0, ch as c_char) }, |
| 93 | + _ => unsafe { sys::furi_string_utf8_push(self.0, ch as u32) }, |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + /// Returns a byte slice of this `String`'s contents. |
| 98 | + /// |
| 99 | + /// The returned slice will **not** contain the trailing nul terminator that the |
| 100 | + /// underlying C string has. |
| 101 | + #[inline] |
| 102 | + #[must_use] |
| 103 | + pub fn to_bytes(&self) -> &[u8] { |
| 104 | + self.as_c_str().to_bytes() |
| 105 | + } |
| 106 | + |
| 107 | + /// Returns a byte slice of this `String`'s contents with the trailing nul byte. |
| 108 | + /// |
| 109 | + /// This function is the equivalent of [`String::to_bytes`] except that it will retain |
| 110 | + /// the trailing nul terminator instead of chopping it off. |
| 111 | + #[inline] |
| 112 | + #[must_use] |
| 113 | + pub fn to_bytes_with_nul(&self) -> &[u8] { |
| 114 | + self.as_c_str().to_bytes_with_nul() |
| 115 | + } |
| 116 | + |
| 117 | + /// Shortens this `String` to the specified length. |
| 118 | + /// |
| 119 | + /// If `new_len` is greater than the string's current length, this has no effect. |
| 120 | + #[inline] |
| 121 | + pub fn truncate(&mut self, new_len: usize) { |
| 122 | + unsafe { sys::furi_string_left(self.0, new_len) }; |
| 123 | + } |
| 124 | + |
| 125 | + /// Returns the length of this `String`. |
| 126 | + /// |
| 127 | + /// This length is in bytes, not [`char`]s or graphemes. In other words, it might not |
| 128 | + /// be what a human considers the length of the string. |
| 129 | + #[inline] |
| 130 | + #[must_use] |
| 131 | + pub fn len(&self) -> usize { |
| 132 | + unsafe { sys::furi_string_size(self.0) } |
| 133 | + } |
| 134 | + |
| 135 | + /// Returns `true` if this `String` has a length of zero, and `false` otherwise. |
| 136 | + #[inline] |
| 137 | + #[must_use] |
| 138 | + pub fn is_empty(&self) -> bool { |
| 139 | + unsafe { sys::furi_string_empty(self.0) } |
| 140 | + } |
| 141 | + |
| 142 | + /// Splits the string into two at the given byte index. |
| 143 | + /// |
| 144 | + /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and the |
| 145 | + /// returned `String` contains bytes `[at, len)`. |
| 146 | + /// |
| 147 | + /// Note that the capacity of `self` does not change. |
| 148 | + /// |
| 149 | + /// # Panics |
| 150 | + /// |
| 151 | + /// Panics if `at` is beyond the last byte of the string. |
| 152 | + #[inline] |
| 153 | + #[must_use = "use `.truncate()` if you don't need the other half"] |
| 154 | + pub fn split_off(&mut self, at: usize) -> String { |
| 155 | + // SAFETY: Trimming the beginning of a C string results in a valid C string, as |
| 156 | + // long as the nul byte is not trimmed. |
| 157 | + assert!(at <= self.len()); |
| 158 | + let ret = |
| 159 | + String(unsafe { sys::furi_string_alloc_set_str(self.as_c_str().as_ptr().add(at)) }); |
| 160 | + self.truncate(at); |
| 161 | + ret |
| 162 | + } |
| 163 | + |
| 164 | + /// Truncates this `String`, removing all contents. |
| 165 | + /// |
| 166 | + /// While this means the `String` will have a length of zero, it does not touch its |
| 167 | + /// capacity. |
| 168 | + #[inline] |
| 169 | + pub fn clear(&mut self) { |
| 170 | + unsafe { sys::furi_string_reset(self.0) }; |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +impl Clone for String { |
| 175 | + fn clone(&self) -> Self { |
| 176 | + Self(unsafe { sys::furi_string_alloc_set(self.0) }) |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +impl Default for String { |
| 181 | + fn default() -> Self { |
| 182 | + Self::new() |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +impl AsRef<CStr> for String { |
| 187 | + #[inline] |
| 188 | + fn as_ref(&self) -> &CStr { |
| 189 | + self.as_c_str() |
| 190 | + } |
| 191 | +} |
| 192 | + |
| 193 | +impl Extend<String> for String { |
| 194 | + fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) { |
| 195 | + iter.into_iter().for_each(move |s| self.push_string(&s)); |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +impl Extend<char> for String { |
| 200 | + fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) { |
| 201 | + let iterator = iter.into_iter(); |
| 202 | + let (lower_bound, _) = iterator.size_hint(); |
| 203 | + self.reserve(lower_bound); |
| 204 | + iterator.for_each(move |c| self.push(c)); |
| 205 | + } |
| 206 | +} |
| 207 | + |
| 208 | +impl<'a> Extend<&'a char> for String { |
| 209 | + fn extend<T: IntoIterator<Item = &'a char>>(&mut self, iter: T) { |
| 210 | + self.extend(iter.into_iter().cloned()); |
| 211 | + } |
| 212 | +} |
| 213 | + |
| 214 | +impl<'a> Extend<&'a str> for String { |
| 215 | + fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) { |
| 216 | + iter.into_iter().for_each(move |s| self.push_rust_str(s)); |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +#[cfg(feature = "alloc")] |
| 221 | +impl Extend<Box<str>> for String { |
| 222 | + fn extend<T: IntoIterator<Item = Box<str>>>(&mut self, iter: T) { |
| 223 | + iter.into_iter().for_each(move |s| self.push_rust_str(&s)); |
| 224 | + } |
| 225 | +} |
| 226 | + |
| 227 | +#[cfg(feature = "alloc")] |
| 228 | +impl<'a> Extend<Cow<'a, str>> for String { |
| 229 | + fn extend<T: IntoIterator<Item = Cow<'a, str>>>(&mut self, iter: T) { |
| 230 | + iter.into_iter().for_each(move |s| self.push_rust_str(&s)); |
| 231 | + } |
| 232 | +} |
| 233 | + |
| 234 | +impl FromIterator<String> for String { |
| 235 | + fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self { |
| 236 | + let mut iterator = iter.into_iter(); |
| 237 | + |
| 238 | + // Because we're iterating over `String`s, we can avoid at least one allocation by |
| 239 | + // getting the first string from the iterator and appending to it all the |
| 240 | + // subsequent strings. |
| 241 | + match iterator.next() { |
| 242 | + None => String::new(), |
| 243 | + Some(mut buf) => { |
| 244 | + buf.extend(iterator); |
| 245 | + buf |
| 246 | + } |
| 247 | + } |
| 248 | + } |
| 249 | +} |
| 250 | + |
| 251 | +impl FromIterator<char> for String { |
| 252 | + fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self { |
| 253 | + let mut buf = String::new(); |
| 254 | + buf.extend(iter); |
| 255 | + buf |
| 256 | + } |
| 257 | +} |
| 258 | + |
| 259 | +impl<'a> FromIterator<&'a char> for String { |
| 260 | + fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self { |
| 261 | + let mut buf = String::new(); |
| 262 | + buf.extend(iter); |
| 263 | + buf |
| 264 | + } |
| 265 | +} |
| 266 | + |
| 267 | +impl<'a> FromIterator<&'a str> for String { |
| 268 | + fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self { |
| 269 | + let mut buf = String::new(); |
| 270 | + buf.extend(iter); |
| 271 | + buf |
| 272 | + } |
| 273 | +} |
| 274 | + |
| 275 | +#[cfg(feature = "alloc")] |
| 276 | +impl FromIterator<Box<str>> for String { |
| 277 | + fn from_iter<T: IntoIterator<Item = Box<str>>>(iter: T) -> Self { |
| 278 | + let mut buf = String::new(); |
| 279 | + buf.extend(iter); |
| 280 | + buf |
| 281 | + } |
| 282 | +} |
| 283 | + |
| 284 | +#[cfg(feature = "alloc")] |
| 285 | +impl<'a> FromIterator<Cow<'a, str>> for String { |
| 286 | + fn from_iter<T: IntoIterator<Item = Cow<'a, str>>>(iter: T) -> Self { |
| 287 | + let mut buf = String::new(); |
| 288 | + buf.extend(iter); |
| 289 | + buf |
| 290 | + } |
| 291 | +} |
| 292 | + |
| 293 | +impl PartialEq for String { |
| 294 | + fn eq(&self, other: &Self) -> bool { |
| 295 | + unsafe { sys::furi_string_equal(self.0, other.0) } |
| 296 | + } |
| 297 | +} |
| 298 | + |
| 299 | +impl PartialEq<CStr> for String { |
| 300 | + fn eq(&self, other: &CStr) -> bool { |
| 301 | + unsafe { sys::furi_string_equal_str(self.0, other.as_ptr()) } |
| 302 | + } |
| 303 | +} |
| 304 | + |
| 305 | +impl PartialEq<String> for CStr { |
| 306 | + fn eq(&self, other: &String) -> bool { |
| 307 | + other.eq(self) |
| 308 | + } |
| 309 | +} |
| 310 | + |
| 311 | +#[cfg(feature = "alloc")] |
| 312 | +impl PartialEq<CString> for String { |
| 313 | + fn eq(&self, other: &CString) -> bool { |
| 314 | + self.eq(other.as_c_str()) |
| 315 | + } |
| 316 | +} |
| 317 | + |
| 318 | +#[cfg(feature = "alloc")] |
| 319 | +impl PartialEq<String> for CString { |
| 320 | + fn eq(&self, other: &String) -> bool { |
| 321 | + other.eq(self.as_c_str()) |
| 322 | + } |
| 323 | +} |
| 324 | + |
| 325 | +impl Ord for String { |
| 326 | + fn cmp(&self, other: &Self) -> Ordering { |
| 327 | + match unsafe { sys::furi_string_cmp(self.0, other.0) } { |
| 328 | + ..=-1 => Ordering::Less, |
| 329 | + 0 => Ordering::Equal, |
| 330 | + 1.. => Ordering::Greater, |
| 331 | + } |
| 332 | + } |
| 333 | +} |
| 334 | + |
| 335 | +impl PartialOrd for String { |
| 336 | + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
| 337 | + Some(self.cmp(other)) |
| 338 | + } |
| 339 | +} |
| 340 | + |
| 341 | +impl fmt::Write for String { |
| 342 | + fn write_str(&mut self, s: &str) -> fmt::Result { |
| 343 | + self.push_rust_str(s); |
| 344 | + Ok(()) |
| 345 | + } |
| 346 | + |
| 347 | + fn write_char(&mut self, c: char) -> fmt::Result { |
| 348 | + self.push(c); |
| 349 | + Ok(()) |
| 350 | + } |
| 351 | +} |
| 352 | + |
| 353 | +impl ufmt::uWrite for String { |
| 354 | + type Error = Infallible; |
| 355 | + |
| 356 | + fn write_str(&mut self, s: &str) -> Result<(), Self::Error> { |
| 357 | + self.push_rust_str(s); |
| 358 | + Ok(()) |
| 359 | + } |
| 360 | + |
| 361 | + fn write_char(&mut self, c: char) -> Result<(), Self::Error> { |
| 362 | + self.push(c); |
| 363 | + Ok(()) |
| 364 | + } |
| 365 | +} |
0 commit comments