moos 0.3.0

Memory-Optimized Objects and Strings (MOOS)
Documentation
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
use alloc::borrow::Borrow;
use alloc::borrow::BorrowMut;
use alloc::borrow::Cow;
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::string::ToString;
use core::convert::AsMut;
use core::convert::AsRef;
use core::convert::From;
use core::convert::Into;
use core::fmt;
use core::fmt::Display;
use core::hash::Hash;
use core::hash::Hasher;
use core::mem::transmute_copy;
use core::ops::Deref;
use core::ops::DerefMut;
use core::str;
use core::str::FromStr;

use crate::inline_str::*;

/// Copy-on-write string that can be owned, borrowed, or inlined.
///
/// # Variants
///
/// 1. [`Owned`](CowStr::Owned): Boxed string slice that owns the data. No
///    lifetime parameter is needed here, since the data is owned by the
///    `CowStr` instance itself.
/// 2. [`Borrowed`](CowStr::Borrowed): Borrowed string slice. Does not own the
///    data, so it must specify the lifetime parameter `'i` to indicate how long
///    the data will live for.
/// 3. [`Inlined`](CowStr::Inlined): Short inline string stored on the stack
///    using the [`InlineStr`] type. Must be [`MAX_INLINE_STR_LEN`] bytes or
///    less in length (typically 22 bytes on 64-bit systems).
///
/// # Examples
///
/// ```rust
/// # use moos::CowStr;
///
/// # fn main() -> Result<(), moos::inline_str::StringTooLongError> {
/// let owned = CowStr::Owned("This is an owned string.".into());
/// // this is a fallible conversion, thus `From<&str>` is not implemented.
/// let inlined = CowStr::Inlined("smol str!".parse()?);
/// let borrowed = CowStr::Borrowed("This is a borrowed string.");
///
/// // checking if a CowStr is inlined, owned, or borrowed
/// assert!(owned.is_owned(), "Expected an owned CowStr!");
/// assert!(inlined.is_inlined(), "Expected an inlined CowStr!");
/// assert!(borrowed.is_borrowed(), "Expected a borrowed CowStr!");
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Eq)]
#[cfg_attr(feature = "is_variant", derive(derive_more::IsVariant))]
pub enum CowStr<'i> {
  /// An immutable boxed string slice that owns the data. This is the
  /// default variant for owned strings (i.e. [`String`] instances), which
  /// are always stored on the heap.
  Owned(Box<str>),
  /// A short inline string stored on the stack using [`InlineStr`].
  ///
  /// This is useful for optimizing memory usage in scenarios where you
  /// expect to frequently work with small strings. Only supports string
  /// lengths up to [`MAX_INLINE_STR_LEN`].
  Inlined(InlineStr),
  /// A borrowed string slice that does not own the data. This is the
  /// default variant for borrowed `&str` references, which are stored on
  /// the stack in most cases. Must specify the lifetime parameter `'i` to
  /// indicate the lifetime of the data being borrowed.
  Borrowed(&'i str),
}

impl<'i> CowStr<'i> {
  #[inline(always)]
  pub fn as_str(&self) -> &str {
    match self {
      CowStr::Owned(b) => b,
      CowStr::Borrowed(b) => b,
      CowStr::Inlined(s) => s.deref(),
    }
  }

  /// Returns a mutable reference to the string as a slice.
  ///
  /// # Safety
  ///
  /// The caller must ensure that the mutable reference does not violate any
  /// aliasing rules, i.e., there are no other references to the same data while
  /// this mutable reference is in use. This is especially important for the
  /// `Borrowed` variant, as modifying the data could lead to undefined behavior
  /// if there are other references to the same data. Use with caution and
  /// discretion.
  #[inline(always)]
  pub unsafe fn as_mut_str(&mut self) -> &mut str {
    unsafe {
      match self {
        CowStr::Owned(b) => b,
        CowStr::Borrowed(b) => transmute_copy(&b.to_owned().as_bytes_mut()),
        CowStr::Inlined(s) => s.as_mut_str_unchecked(),
      }
    }
  }

  #[inline(always)]
  pub fn as_bytes(&self) -> &[u8] {
    match self {
      CowStr::Owned(b) => b.as_bytes(),
      CowStr::Borrowed(b) => b.as_bytes(),
      CowStr::Inlined(s) => s.as_bytes(),
    }
  }

  /// Returns a mutable byte slice of the string's contents.
  ///
  /// # Safety
  ///
  /// The caller must ensure that the underlying data is not aliased while the
  /// mutable byte slice is in use. This is particularly important for the
  /// [`CowStr::Borrowed`] variant - modifying the data while there are existing
  /// references to it is undefined behavior. Use with caution.
  #[inline(always)]
  pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
    unsafe {
      match *self {
        CowStr::Owned(ref mut b) => b.as_bytes_mut(),
        CowStr::Borrowed(b) => transmute_copy(&b.to_owned().as_bytes_mut()),
        CowStr::Inlined(ref mut s) => s.as_bytes_mut(),
      }
    }
  }

  /// Returns the length of the `CowStr` in bytes.
  #[inline(always)]
  pub fn len(&self) -> usize {
    self.as_bytes().len()
  }

  /// Returns `true` if the `CowStr` is empty.
  #[inline(always)]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }

  #[deprecated(since = "0.2.0", note = "use `into_string` instead")]
  #[inline(always)]
  pub fn into_owned(self) -> String {
    match self {
      CowStr::Owned(s) => s.into(),
      CowStr::Borrowed(s) => s.to_owned(),
      CowStr::Inlined(s) => s.deref().to_owned(),
    }
  }

  /// Converts the `CowStr` into an owned `String`, cloning the data if
  /// necessary.
  #[inline(always)]
  pub fn into_string(self) -> String {
    match self {
      CowStr::Owned(b) => b.into(),
      CowStr::Borrowed(b) => b.to_owned(),
      CowStr::Inlined(s) => s.deref().to_owned(),
    }
  }
}

impl<'i> FromStr for CowStr<'i> {
  type Err = ();

  #[inline(always)]
  fn from_str(s: &str) -> Result<Self, Self::Err> {
    match InlineStr::try_from(s) {
      Ok(inline) => Ok(CowStr::Inlined(inline)),
      Err(_) => Ok(CowStr::Owned(s.to_string().into_boxed_str())),
    }
  }
}

impl<'i> Display for CowStr<'i> {
  #[inline(always)]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{}", self.deref())
  }
}

impl<'i> Default for CowStr<'i> {
  #[inline(always)]
  fn default() -> Self {
    CowStr::Borrowed("")
  }
}

impl<'i> Hash for CowStr<'i> {
  #[inline(always)]
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.deref().hash(state);
  }
}

impl<'i> Clone for CowStr<'i> {
  #[inline]
  fn clone(&self) -> Self {
    match self {
      CowStr::Owned(s) => match InlineStr::try_from(&**s) {
        Ok(inline) => CowStr::Inlined(inline),
        Err(_) => CowStr::Owned(s.clone()),
      },
      CowStr::Borrowed(s) => CowStr::Borrowed(s),
      CowStr::Inlined(s) => CowStr::Inlined(*s),
    }
  }
}

impl<'i> Deref for CowStr<'i> {
  type Target = str;

  #[inline(always)]
  fn deref(&self) -> &Self::Target {
    self.as_str()
  }
}

impl<'i> DerefMut for CowStr<'i> {
  #[inline(always)]
  fn deref_mut(&mut self) -> &mut str {
    unsafe { self.as_mut_str() }
  }
}

impl<'i> AsRef<str> for CowStr<'i> {
  #[inline(always)]
  fn as_ref(&self) -> &str {
    self.deref()
  }
}

impl<'i> AsMut<str> for CowStr<'i> {
  #[inline(always)]
  fn as_mut(&mut self) -> &mut str {
    self.deref_mut()
  }
}

impl<'i> Borrow<str> for CowStr<'i> {
  fn borrow(&self) -> &str {
    self.deref()
  }
}

impl<'i> BorrowMut<str> for CowStr<'i> {
  fn borrow_mut(&mut self) -> &mut str {
    self.deref_mut()
  }
}

impl<'i> PartialEq for CowStr<'i> {
  #[inline(always)]
  fn eq(&self, other: &Self) -> bool {
    self.deref() == other.deref()
  }
}

impl<'i> PartialEq<str> for CowStr<'i> {
  #[inline(always)]
  fn eq(&self, other: &str) -> bool {
    self.deref() == other
  }
}

impl<'i> PartialEq<&'i str> for CowStr<'i> {
  #[inline(always)]
  fn eq(&self, other: &&'i str) -> bool {
    self.deref() == *other
  }
}

impl<'i> PartialEq<Cow<'i, str>> for CowStr<'i> {
  #[inline(always)]
  fn eq(&self, other: &Cow<'i, str>) -> bool {
    self.deref() == other.deref()
  }
}

impl<'i> PartialEq<CowStr<'i>> for str {
  #[inline(always)]
  fn eq(&self, other: &CowStr<'_>) -> bool {
    self == other.deref()
  }
}

impl<'i> PartialEq<CowStr<'i>> for &'i str {
  #[inline(always)]
  fn eq(&self, other: &CowStr<'_>) -> bool {
    other.deref() == *self
  }
}

impl<'i> PartialEq<CowStr<'i>> for Cow<'i, str> {
  #[inline(always)]
  fn eq(&self, other: &CowStr<'_>) -> bool {
    self.deref() == other.deref()
  }
}

impl<'i> PartialEq<String> for CowStr<'i> {
  #[inline(always)]
  fn eq(&self, other: &String) -> bool {
    self.deref() == other.deref()
  }
}

impl<'i> PartialEq<CowStr<'i>> for String {
  #[inline(always)]
  fn eq(&self, other: &CowStr<'_>) -> bool {
    self.deref() == other.deref()
  }
}

impl<'i> PartialOrd<CowStr<'i>> for CowStr<'i> {
  #[inline(always)]
  fn partial_cmp(&self, other: &CowStr<'_>) -> Option<core::cmp::Ordering> {
    self.deref().partial_cmp(other.deref())
  }
}

impl<'i> PartialOrd<str> for CowStr<'i> {
  #[inline(always)]
  fn partial_cmp(&self, other: &str) -> Option<core::cmp::Ordering> {
    self.deref().partial_cmp(other)
  }
}

impl<'i> PartialOrd<&'i str> for CowStr<'i> {
  #[inline(always)]
  fn partial_cmp(&self, other: &&'i str) -> Option<core::cmp::Ordering> {
    self.deref().partial_cmp(*other)
  }
}

impl<'i> PartialOrd<Cow<'i, str>> for CowStr<'i> {
  #[inline(always)]
  fn partial_cmp(&self, other: &Cow<'i, str>) -> Option<core::cmp::Ordering> {
    self.deref().partial_cmp(other.deref())
  }
}

impl<'i> PartialOrd<CowStr<'i>> for str {
  #[inline(always)]
  fn partial_cmp(&self, other: &CowStr<'_>) -> Option<core::cmp::Ordering> {
    self.partial_cmp(other.deref())
  }
}

impl<'i> From<&'i str> for CowStr<'i> {
  #[inline(always)]
  fn from(s: &'i str) -> Self {
    CowStr::Borrowed(s)
  }
}

impl<'i> From<String> for CowStr<'i> {
  #[inline(always)]
  fn from(s: String) -> Self {
    CowStr::Owned(s.into_boxed_str())
  }
}

impl<'i> From<char> for CowStr<'i> {
  #[inline(always)]
  fn from(c: char) -> Self {
    CowStr::Inlined(c.into())
  }
}

impl<'i> From<Cow<'i, str>> for CowStr<'i> {
  #[inline(always)]
  fn from(s: Cow<'i, str>) -> Self {
    match s {
      Cow::Borrowed(s) => CowStr::Borrowed(s),
      Cow::Owned(s) => CowStr::Owned(s.into_boxed_str()),
    }
  }
}

impl<'i> From<CowStr<'i>> for Cow<'i, str> {
  #[inline(always)]
  fn from(s: CowStr<'i>) -> Self {
    match s {
      CowStr::Owned(s) => Cow::Owned(s.to_string()),
      CowStr::Inlined(s) => Cow::Owned(s.to_string()),
      CowStr::Borrowed(s) => Cow::Borrowed(s),
    }
  }
}

impl<'i> From<Cow<'i, char>> for CowStr<'i> {
  #[inline(always)]
  fn from(s: Cow<'i, char>) -> Self {
    CowStr::Inlined(InlineStr::from(*s.deref()))
  }
}

impl<'i> From<CowStr<'i>> for String {
  #[inline(always)]
  fn from(s: CowStr<'i>) -> Self {
    s.into_string()
  }
}

#[cfg(not(feature = "is_variant"))]
impl<'i> CowStr<'i> {
  /// Returns `true` if the `CowStr` is the `Owned` variant.
  #[inline(always)]
  pub const fn is_owned(&self) -> bool {
    matches!(self, CowStr::Owned(_))
  }

  /// Returns `true` if the `CowStr` is the `Inlined` variant.
  #[inline(always)]
  pub const fn is_inlined(&self) -> bool {
    matches!(self, CowStr::Inlined(_))
  }

  /// Returns `true` if the `CowStr` is the `Borrowed` variant.
  #[inline(always)]
  pub const fn is_borrowed(&self) -> bool {
    matches!(self, CowStr::Borrowed(_))
  }
}

impl CowStr<'_> {
  /// Attempts to create an inline `CowStr` from a value that can be converted
  /// to a string slice via an `AsRef<str>` impl.
  ///
  /// Returns an error if the string is too long to be inlined.
  #[inline(always)]
  pub fn try_inline<'i, T: 'i + AsRef<str>>(
    s: T,
  ) -> Result<CowStr<'i>, StringTooLongError> {
    let inline = InlineStr::try_from(s.as_ref())?;
    Ok(CowStr::Inlined(inline))
  }

  /// Creates an inline `CowStr` from a value that can be converted to a string
  /// slice via an `AsRef<str>` impl, panicking if the string is too long to be
  /// inlined.
  ///
  /// # Panics
  ///
  /// Panics if the string length exceeds [`MAX_INLINE_STR_LEN`].
  #[inline(always)]
  pub fn inline<'i, T: 'i + AsRef<str>>(s: T) -> CowStr<'i> {
    let inline =
      InlineStr::try_from(s.as_ref()).expect("String too long to inline!");
    CowStr::Inlined(inline)
  }

  /// Forcibly creates an inline `CowStr` from a given value that can be
  /// converted to a string slice via an `AsRef<str>` impl, truncating it if
  /// necessary to fit within the maximum inline length.
  #[inline(always)]
  pub fn force_inline<'i, T: 'i + AsRef<str>>(s: T) -> CowStr<'i> {
    let src = s.as_ref().as_bytes();
    let mut len = src.len();
    if len > MAX_INLINE_STR_LEN {
      len = MAX_INLINE_STR_LEN;
    }
    let mut buf = [0u8; MAX_INLINE_STR_LEN];
    buf[..len].copy_from_slice(&src[..len]);
    let len = len as u8;
    CowStr::Inlined(InlineStr { buf, len })
  }

  /// Creates an inline `CowStr` from a single character.
  #[inline(always)]
  pub fn from_char(c: char) -> CowStr<'static> {
    CowStr::Inlined(c.into())
  }
}

#[cfg(feature = "serde")]
mod serde_impl {
  use core::fmt;

  use serde::Deserialize;
  use serde::Deserializer;
  use serde::Serialize;
  use serde::Serializer;
  use serde::de;

  use super::*;

  impl<'i> Serialize for CowStr<'i> {
    #[inline(always)]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
      S: Serializer,
    {
      serializer.serialize_str(self.as_ref())
    }
  }

  struct CowStrVisitor;

  impl<'de> de::Visitor<'de> for CowStrVisitor {
    type Value = CowStr<'de>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
      formatter.write_str("a string")
    }

    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
    where
      E: de::Error,
    {
      Ok(CowStr::Borrowed(v))
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
      E: de::Error,
    {
      match v.try_into() {
        Ok(it) => Ok(CowStr::Inlined(it)),
        Err(_) => Ok(CowStr::Owned(String::from(v).into_boxed_str())),
      }
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
      E: de::Error,
    {
      Ok(CowStr::Owned(v.into_boxed_str()))
    }
  }

  impl<'i, 'de: 'i> Deserialize<'de> for CowStr<'i> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
      D: Deserializer<'de>,
    {
      deserializer.deserialize_str(CowStrVisitor)
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn cowstr_size() {
    let size = std::mem::size_of::<CowStr>();
    let word_size = std::mem::size_of::<isize>();
    assert_eq!(3 * word_size, size);
  }

  #[test]
  fn cowstr_char_to_string() {
    let c = '';
    let smort: CowStr = c.into();
    let owned: String = smort.to_string();
    let expected = "".to_owned();
    assert_eq!(expected, owned);
  }

  #[test]
  #[cfg(target_pointer_width = "64")]
  fn small_boxed_str_clones_to_stack() {
    let s = "0123456789abcde".to_owned();
    let smort: CowStr = s.into();
    let smort_clone = smort.clone();

    if let CowStr::Inlined(..) = smort_clone {
    } else {
      panic!("Expected a Inlined variant!");
    }
  }

  #[test]
  fn cow_to_cow_str() {
    let s = "some text";
    let cow = Cow::Borrowed(s);
    let actual = CowStr::from(cow);
    let expected = CowStr::Borrowed(s);
    assert_eq!(actual, expected);
    assert!(variant_eq(&actual, &expected));

    let s = "some text".to_string();
    let cow: Cow<str> = Cow::Owned(s.clone());
    let actual = CowStr::from(cow);
    let expected = CowStr::Owned(s.into_boxed_str());
    assert_eq!(actual, expected);
    assert!(variant_eq(&actual, &expected));
  }

  #[test]
  fn cow_str_to_cow() {
    let s = "some text";
    let cow_str = CowStr::Borrowed(s);
    let actual = Cow::from(cow_str);
    let expected = Cow::Borrowed(s);
    assert_eq!(actual, expected);
    assert!(variant_eq(&actual, &expected));

    let s = "s";
    let inline_str: InlineStr = InlineStr::try_from(s).unwrap();
    let cow_str = CowStr::Inlined(inline_str);
    let actual = Cow::from(cow_str);
    let expected: Cow<str> = Cow::Owned(s.to_string());
    assert_eq!(actual, expected);
    assert!(variant_eq(&actual, &expected));

    let s = "s";
    let cow_str = CowStr::Owned(s.to_string().into_boxed_str());
    let actual = Cow::from(cow_str);
    let expected: Cow<str> = Cow::Owned(s.to_string());
    assert_eq!(actual, expected);
    assert!(variant_eq(&actual, &expected));
  }

  #[test]
  fn cow_str_to_string() {
    let s = "some text";
    let cow_str = CowStr::Borrowed(s);
    let actual = String::from(cow_str);
    let expected = String::from("some text");
    assert_eq!(actual, expected);

    let s = "s";
    let inline_str: InlineStr = InlineStr::try_from(s).unwrap();
    let cow_str = CowStr::Inlined(inline_str);
    let actual = String::from(cow_str);
    let expected = String::from("s");
    assert_eq!(actual, expected);

    let s = "s";
    let cow_str = CowStr::Owned(s.to_string().into_boxed_str());
    let actual = String::from(cow_str);
    let expected = String::from("s");
    assert_eq!(actual, expected);
  }

  #[test]
  fn cow_char_to_cow_str() {
    let c = 'c';
    let cow: Cow<char> = Cow::Owned(c);
    let actual = CowStr::from(cow);
    let expected = CowStr::Inlined(InlineStr::from(c));
    assert_eq!(actual, expected);
    assert!(variant_eq(&actual, &expected));

    let c = 'c';
    let cow: Cow<char> = Cow::Borrowed(&c);
    let actual = CowStr::from(cow);
    let expected = CowStr::Inlined(InlineStr::from(c));
    assert_eq!(actual, expected);
    assert!(variant_eq(&actual, &expected));
  }

  fn variant_eq<T>(a: &T, b: &T) -> bool {
    std::mem::discriminant(a) == std::mem::discriminant(b)
  }
}