Debian Codegraph @

src/traits.rs

raw ◀ ▶
1 Debian patch touch this file
1 use alloc::string::String;
2 use core::fmt::{self, Write};
3 use core::num;
4
5 use castaway::{match_type, LifetimeFree};
6
7 use super::repr::{IntoRepr, Repr};
8 use crate::{CompactString, ToCompactStringError, UnwrapWithMsg};
9
10 /// A trait for converting a value to a `CompactString`.
11 ///
12 /// This trait is automatically implemented for any type which implements the
13 /// [`fmt::Display`] trait. As such, [`ToCompactString`] shouldn't be implemented directly:
14 /// [`fmt::Display`] should be implemented instead, and you get the [`ToCompactString`]
15 /// implementation for free.
16 pub trait ToCompactString {
17 /// Converts the given value to a [`CompactString`].
18 ///
19 /// # Panics
20 ///
21 /// Panics if the system runs out of memory and it cannot hold the whole string,
22 /// or if [`Display::fmt()`][core::fmt::Display::fmt] returns an error.
23 ///
24 /// # Examples
25 ///
26 /// Basic usage:
27 ///
28 /// ```
29 /// use compact_str::ToCompactString;
30 /// # use compact_str::CompactString;
31 ///
32 /// let i = 5;
33 /// let five = CompactString::new("5");
34 ///
35 /// assert_eq!(i.to_compact_string(), five);
36 /// ```
37 #[inline]
38 #[track_caller]
39 fn to_compact_string(&self) -> CompactString {
40 self.try_to_compact_string().unwrap_with_msg()
41 }
42
43 /// Fallible version of [`ToCompactString::to_compact_string()`]
44 ///
45 /// This method won't panic if the system is out-of-memory, but return a
46 /// [`ReserveError`][crate::ReserveError].
47 /// Otherwise it behaves the same as [`ToCompactString::to_compact_string()`].
48 fn try_to_compact_string(&self) -> Result<CompactString, ToCompactStringError>;
49 }
50
51 /// # Safety
52 ///
53 /// * [`CompactString`] does not contain any lifetime
54 /// * [`CompactString`] is 'static
55 /// * [`CompactString`] is a container to `u8`, which is `LifetimeFree`.
56 unsafe impl LifetimeFree for CompactString {}
57 unsafe impl LifetimeFree for Repr {}
58
59 impl ToCompactString for str {
60 #[inline]
61 fn to_compact_string(&self) -> CompactString {
62 CompactString::new(self)
63 }
64
65 #[inline]
66 fn try_to_compact_string(&self) -> Result<CompactString, ToCompactStringError> {
67 Ok(CompactString(Repr::new(self)?))
68 }
69 }
70
71 /// # Panics
72 ///
73 /// In this implementation, the `to_compact_string` method panics if the `Display` implementation
74 /// returns an error. This indicates an incorrect `Display` implementation since
75 /// `std::fmt::Write for CompactString` never returns an error itself.
76 ///
77 /// # Note
78 ///
79 /// We use the [`castaway`] crate to provide zero-cost specialization for several types, those are:
80 /// * `u8`, `u16`, `u32`, `u64`, `u128`, `usize`
81 /// * `i8`, `i16`, `i32`, `i64`, `i128`, `isize`
82 /// * `NonZeroU*`, `NonZeroI*`
83 /// * `bool`
84 /// * `char`
85 /// * `String`, `CompactString`
86 /// * `f32`, `f64`
87 /// * For floats we use [`zmij`] crate which sometimes provides different formatting than [`std`]
88 impl<T: fmt::Display> ToCompactString for T {
89 #[inline]
90 fn try_to_compact_string(&self) -> Result<CompactString, ToCompactStringError> {
91 let repr = match_type!(self, {
92 &u8 as s => s.into_repr()?,
93 &i8 as s => s.into_repr()?,
94 &u16 as s => s.into_repr()?,
95 &i16 as s => s.into_repr()?,
96 &u32 as s => s.into_repr()?,
97 &i32 as s => s.into_repr()?,
98 &u64 as s => s.into_repr()?,
99 &i64 as s => s.into_repr()?,
100 &u128 as s => s.into_repr()?,
101 &i128 as s => s.into_repr()?,
102 &usize as s => s.into_repr()?,
103 &isize as s => s.into_repr()?,
104 &f32 as s => s.into_repr()?,
105 &f64 as s => s.into_repr()?,
106 &bool as s => s.into_repr()?,
107 &char as s => s.into_repr()?,
108 &String as s => Repr::new(s)?,
109 &CompactString as s => Repr::new(s)?,
110 &num::NonZeroU8 as s => s.into_repr()?,
111 &num::NonZeroI8 as s => s.into_repr()?,
112 &num::NonZeroU16 as s => s.into_repr()?,
113 &num::NonZeroI16 as s => s.into_repr()?,
114 &num::NonZeroU32 as s => s.into_repr()?,
115 &num::NonZeroI32 as s => s.into_repr()?,
116 &num::NonZeroU64 as s => s.into_repr()?,
117 &num::NonZeroI64 as s => s.into_repr()?,
118 &num::NonZeroUsize as s => s.into_repr()?,
119 &num::NonZeroIsize as s => s.into_repr()?,
120 &num::NonZeroU128 as s => s.into_repr()?,
121 &num::NonZeroI128 as s => s.into_repr()?,
122 s => {
123 let mut c = CompactString::const_new("");
124 write!(c, "{}", s)?;
125 return Ok(c);
126 }
127 });
128
129 Ok(CompactString(repr))
130 }
131 }
132
133 /// A trait that provides convenience methods for creating a [`CompactString`] from a collection of
134 /// items. It is implemented for all types that can be converted into an iterator, and that iterator
135 /// yields types that can be converted into a `str`.
136 ///
137 /// i.e. `C: IntoIterator<Item = AsRef<str>>`.
138 ///
139 /// # Concatenate and Join
140 /// Two methods that this trait provides are `concat_compact(...)` and `join_compact(...)`
141 /// ```
142 /// use compact_str::CompactStringExt;
143 ///
144 /// let words = vec!["☀️", "🌕", "🌑", "☀️"];
145 ///
146 /// // directly concatenate all the words together
147 /// let concat = words.iter().concat_compact();
148 /// assert_eq!(concat, "☀️🌕🌑☀️");
149 ///
150 /// // join the words, with a separator
151 /// let join = words.iter().join_compact(" ➡️ ");
152 /// assert_eq!(join, "☀️ ➡️ 🌕 ➡️ 🌑 ➡️ ☀️");
153 /// ```
154 pub trait CompactStringExt {
155 /// Concatenates all the items of a collection into a [`CompactString`]
156 ///
157 /// # Example
158 /// ```
159 /// use compact_str::CompactStringExt;
160 ///
161 /// let items = ["hello", " ", "world", "!"];
162 /// let compact = items.concat_compact();
163 ///
164 /// assert_eq!(compact, "hello world!");
165 /// ```
166 fn concat_compact(self) -> CompactString;
167
168 /// Joins all the items of a collection, placing a separator between them, forming a
169 /// [`CompactString`]
170 ///
171 /// # Example
172 /// ```
173 /// use compact_str::CompactStringExt;
174 ///
175 /// let fruits = vec!["apples", "oranges", "bananas"];
176 /// let compact = fruits.join_compact(", ");
177 ///
178 /// assert_eq!(compact, "apples, oranges, bananas");
179 /// ```
180 fn join_compact<S: AsRef<str>>(self, separator: S) -> CompactString;
181 }
182
183 impl<I, C> CompactStringExt for C
184 where
185 I: AsRef<str>,
186 C: IntoIterator<Item = I>,
187 {
188 fn concat_compact(self) -> CompactString {
189 self.into_iter()
190 .fold(CompactString::const_new(""), |mut s, item| {
191 s.push_str(item.as_ref());
192 s
193 })
194 }
195
196 fn join_compact<S: AsRef<str>>(self, separator: S) -> CompactString {
197 let mut compact_string = CompactString::const_new("");
198
199 let mut iter = self.into_iter().peekable();
200 let sep = separator.as_ref();
201
202 while let Some(item) = iter.next() {
203 compact_string.push_str(item.as_ref());
204 if iter.peek().is_some() {
205 compact_string.push_str(sep);
206 }
207 }
208
209 compact_string
210 }
211 }
212
•213 #[cfg(all(test, feature = "std"))]
214 mod tests {
215 use alloc::string::{String, ToString};
216 use alloc::vec::Vec;
217 use core::num;
218
219 use proptest::prelude::*;
220 use test_strategy::proptest;
221
222 use super::{CompactStringExt, ToCompactString};
223 use crate::CompactString;
224
225 #[test]
226 fn str_implements_to_compact_string() {
227 fn assert_impl<T: ToCompactString + ?Sized>() {}
228 assert_impl::<str>();
229 }
230
231 #[test]
232 fn test_join() {
233 let slice = ["hello", "world"];
234 let c1 = (&slice).join_compact(" ");
235 let c2 = slice.join_compact(" ");
236 assert_eq!(c1, "hello world");
237 assert_eq!(c2, "hello world");
238
239 let vector = vec!["🍎", "🍊", "🍌"];
240 let c = vector.join_compact(",");
241 assert_eq!(c, "🍎,🍊,🍌");
242
243 let owned_strings = ["foo".to_string(), "bar".to_string()];
244 let c = owned_strings.join_compact("/");
245 assert_eq!(c, "foo/bar");
246 }
247
248 #[test]
249 fn test_join_iter() {
250 let values = ["foo", "bar", "baz"];
251 let compact = values.iter().map(|x| x.to_string()).join_compact("/");
252 assert_eq!(compact, "foo/bar/baz");
253
254 let compact = values.into_iter().map(|x| x.trim()).join_compact("-");
255 assert_eq!(compact, "foo-bar-baz");
256
257 let compact = values
258 .into_iter()
259 .map(CompactString::from)
260 .join_compact("...");
261 assert_eq!(compact, "foo...bar...baz");
262 }
263
264 #[proptest]
265 #[cfg_attr(miri, ignore)]
266 fn proptest_join(items: Vec<String>, separator: String) {
267 let c: CompactString = items.iter().join_compact(&separator);
268 let s: String = items.join(&separator);
269 assert_eq!(c, s);
270 }
271
272 #[test]
273 fn test_concat() {
274 let items = vec!["hello", "world"];
275 let c = items.join_compact(" ");
276 assert_eq!(c, "hello world");
277
278 let vector = vec!["🍎", "🍊", "🍌"];
279 let c = vector.concat_compact();
280 assert_eq!(c, "🍎🍊🍌");
281 }
282
283 #[proptest]
284 #[cfg_attr(miri, ignore)]
285 fn proptest_concat(items: Vec<String>) {
286 let c: CompactString = items.iter().concat_compact();
287 let s: String = items.concat();
288 assert_eq!(c, s);
289 }
290
291 #[proptest]
292 #[cfg_attr(miri, ignore)]
293 fn proptest_to_compact_string_u8(val: u8) {
294 let compact = val.to_compact_string();
295 prop_assert_eq!(compact.as_str(), val.to_string());
296 }
297
298 #[proptest]
299 #[cfg_attr(miri, ignore)]
300 fn proptest_to_compact_string_i8(val: i8) {
301 let compact = val.to_compact_string();
302 prop_assert_eq!(compact.as_str(), val.to_string());
303 }
304
305 #[proptest]
306 #[cfg_attr(miri, ignore)]
307 fn proptest_to_compact_string_u16(val: u16) {
308 let compact = val.to_compact_string();
309 prop_assert_eq!(compact.as_str(), val.to_string());
310 }
311
312 #[proptest]
313 #[cfg_attr(miri, ignore)]
314 fn proptest_to_compact_string_i16(val: i16) {
315 let compact = val.to_compact_string();
316 prop_assert_eq!(compact.as_str(), val.to_string());
317 }
318 #[proptest]
319 #[cfg_attr(miri, ignore)]
320 fn proptest_to_compact_string_u32(val: u32) {
321 let compact = val.to_compact_string();
322 prop_assert_eq!(compact.as_str(), val.to_string());
323 }
324 #[proptest]
325 #[cfg_attr(miri, ignore)]
326 fn proptest_to_compact_string_i32(val: i32) {
327 let compact = val.to_compact_string();
328 prop_assert_eq!(compact.as_str(), val.to_string());
329 }
330 #[proptest]
331 #[cfg_attr(miri, ignore)]
332 fn proptest_to_compact_string_u64(val: u64) {
333 let compact = val.to_compact_string();
334 prop_assert_eq!(compact.as_str(), val.to_string());
335 }
336 #[proptest]
337 #[cfg_attr(miri, ignore)]
338 fn proptest_to_compact_string_i64(val: i64) {
339 let compact = val.to_compact_string();
340 prop_assert_eq!(compact.as_str(), val.to_string());
341 }
342 #[proptest]
343 #[cfg_attr(miri, ignore)]
344 fn proptest_to_compact_string_usize(val: usize) {
345 let compact = val.to_compact_string();
346 prop_assert_eq!(compact.as_str(), val.to_string());
347 }
348 #[proptest]
349 #[cfg_attr(miri, ignore)]
350 fn proptest_to_compact_string_isize(val: isize) {
351 let compact = val.to_compact_string();
352 prop_assert_eq!(compact.as_str(), val.to_string());
353 }
354 #[proptest]
355 #[cfg_attr(miri, ignore)]
356 fn proptest_to_compact_string_u128(val: u128) {
357 let compact = val.to_compact_string();
358 prop_assert_eq!(compact.as_str(), val.to_string());
359 }
360 #[proptest]
361 #[cfg_attr(miri, ignore)]
362 fn proptest_to_compact_string_i128(val: i128) {
363 let compact = val.to_compact_string();
364 prop_assert_eq!(compact.as_str(), val.to_string());
365 }
366
367 #[proptest]
368 #[cfg_attr(miri, ignore)]
369 fn proptest_to_compact_string_non_zero_u8(
370 #[strategy((1..=u8::MAX).prop_map(|x| unsafe { num::NonZeroU8::new_unchecked(x)} ))]
371 val: num::NonZeroU8,
372 ) {
373 let compact = val.to_compact_string();
374 prop_assert_eq!(compact.as_str(), val.to_string());
375 }
376
377 #[proptest]
378 #[cfg_attr(miri, ignore)]
379 fn proptest_to_compact_string_non_zero_u16(
380 #[strategy((1..=u16::MAX).prop_map(|x| unsafe { num::NonZeroU16::new_unchecked(x)} ))]
381 val: num::NonZeroU16,
382 ) {
383 let compact = val.to_compact_string();
384 prop_assert_eq!(compact.as_str(), val.to_string());
385 }
386
387 #[proptest]
388 #[cfg_attr(miri, ignore)]
389 fn proptest_to_compact_string_non_zero_u32(
390 #[strategy((1..=u32::MAX).prop_map(|x| unsafe { num::NonZeroU32::new_unchecked(x)} ))]
391 val: num::NonZeroU32,
392 ) {
393 let compact = val.to_compact_string();
394 prop_assert_eq!(compact.as_str(), val.to_string());
395 }
396
397 #[proptest]
398 #[cfg_attr(miri, ignore)]
399 fn proptest_to_compact_string_non_zero_u64(
400 #[strategy((1..=u64::MAX).prop_map(|x| unsafe { num::NonZeroU64::new_unchecked(x)} ))]
401 val: num::NonZeroU64,
402 ) {
403 let compact = val.to_compact_string();
404 prop_assert_eq!(compact.as_str(), val.to_string());
405 }
406
407 #[proptest]
408 #[cfg_attr(miri, ignore)]
409 fn proptest_to_compact_string_non_zero_u128(
410 #[strategy((1..=u128::MAX).prop_map(|x| unsafe { num::NonZeroU128::new_unchecked(x)} ))]
411 val: num::NonZeroU128,
412 ) {
413 let compact = val.to_compact_string();
414 prop_assert_eq!(compact.as_str(), val.to_string());
415 }
416
417 #[proptest]
418 #[cfg_attr(miri, ignore)]
419 fn proptest_to_compact_string_non_zero_usize(
420 #[strategy((1..=usize::MAX).prop_map(|x| unsafe { num::NonZeroUsize::new_unchecked(x)} ))]
421 val: num::NonZeroUsize,
422 ) {
423 let compact = val.to_compact_string();
424 prop_assert_eq!(compact.as_str(), val.to_string());
425 }
426
427 #[proptest]
428 #[cfg_attr(miri, ignore)]
429 fn proptest_to_compact_string_non_zero_i8(
430 #[strategy((1..=u8::MAX).prop_map(|x| unsafe { num::NonZeroI8::new_unchecked(x as i8)} ))]
431 val: num::NonZeroI8,
432 ) {
433 let compact = val.to_compact_string();
434 prop_assert_eq!(compact.as_str(), val.to_string());
435 }
436
437 #[proptest]
438 #[cfg_attr(miri, ignore)]
439 fn proptest_to_compact_string_non_zero_i16(
440 #[strategy((1..=u16::MAX).prop_map(|x| unsafe { num::NonZeroI16::new_unchecked(x as i16)} ))]
441 val: num::NonZeroI16,
442 ) {
443 let compact = val.to_compact_string();
444 prop_assert_eq!(compact.as_str(), val.to_string());
445 }
446
447 #[proptest]
448 #[cfg_attr(miri, ignore)]
449 fn proptest_to_compact_string_non_zero_i32(
450 #[strategy((1..=u32::MAX).prop_map(|x| unsafe { num::NonZeroI32::new_unchecked(x as i32)} ))]
451 val: num::NonZeroI32,
452 ) {
453 let compact = val.to_compact_string();
454 prop_assert_eq!(compact.as_str(), val.to_string());
455 }
456
457 #[proptest]
458 #[cfg_attr(miri, ignore)]
459 fn proptest_to_compact_string_non_zero_i64(
460 #[strategy((1..=u64::MAX).prop_map(|x| unsafe { num::NonZeroI64::new_unchecked(x as i64)} ))]
461 val: num::NonZeroI64,
462 ) {
463 let compact = val.to_compact_string();
464 prop_assert_eq!(compact.as_str(), val.to_string());
465 }
466
467 #[proptest]
468 #[cfg_attr(miri, ignore)]
469 fn proptest_to_compact_string_non_zero_i128(
470 #[strategy((1..=u128::MAX).prop_map(|x| unsafe { num::NonZeroI128::new_unchecked(x as i128)} ))]
471 val: num::NonZeroI128,
472 ) {
473 let compact = val.to_compact_string();
474 prop_assert_eq!(compact.as_str(), val.to_string());
475 }
476
477 #[proptest]
478 #[cfg_attr(miri, ignore)]
479 fn proptest_to_compact_string_non_zero_isize(
480 #[strategy((1..=usize::MAX).prop_map(|x| unsafe { num::NonZeroIsize::new_unchecked(x as isize)} ))]
481 val: num::NonZeroIsize,
482 ) {
483 let compact = val.to_compact_string();
484 prop_assert_eq!(compact.as_str(), val.to_string());
485 }
486 }