mstr 0.1.5

MStr is a 2-word, immutable Cow<str>
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
#![doc = include_str!("../README.md")]
#![no_std]
#![deny(unsafe_op_in_unsafe_fn)]
#![deny(elided_lifetimes_in_paths)]

extern crate alloc;

use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::String;
use core::borrow::Borrow;
use core::cmp::Ordering;
use core::fmt::{Debug, Display, Formatter, Pointer};
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::ops::Deref;
use core::ptr::NonNull;
use core::{fmt, mem, ptr, str};

// the high bit of usize
// if set (1), MStr is owned
// if not (0), MStr is borrowed
const TAG: usize = 1 << (usize::BITS - 1);
// every bit except the tag bit
const MASK: usize = !TAG;

/// `MStr` is a 2-word, immutable version of `Cow<str>`.
///
/// See the [crate docs](crate) for more info.
pub struct MStr<'a> {
    ptr: NonNull<u8>,

    // if high bit (TAG) is set, we are owned
    // rust requires all allocations to be less than isize::MAX bytes,
    // so the top bit is never used and thus available for tagging
    len: usize,

    // use the lifetime (also makes it covariant)
    _marker: PhantomData<&'a str>,
}

unsafe impl Send for MStr<'_> {}
unsafe impl Sync for MStr<'_> {}

impl<'a> MStr<'a> {
    // -- Constructors --

    /// Creates a new `MStr<'a>` from an `&'a str`.
    ///
    /// The returned `MStr` is borrowed for the same lifetime as the input data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// # use std::borrow::Cow;
    /// let s = String::from("foo");
    /// let mstr = MStr::new_borrowed(&s);
    ///
    /// assert!(mstr.is_borrowed());
    /// assert_eq!(mstr, s);
    /// assert_eq!(mstr.as_str(), "foo");
    /// assert_eq!(mstr.as_ptr(), s.as_ptr());
    /// assert!(matches!(mstr.into_cow(), Cow::Borrowed(_)));
    /// ```
    #[inline]
    #[must_use]
    pub const fn new_borrowed(s: &'a str) -> MStr<'a> {
        MStr::_new(s.as_ptr(), s.len(), false)
    }

    /// Creates a new `MStr` from owned data.
    /// The input type is anything that can be converted into a `Box<str>` (String, &str, etc).
    ///
    /// The returned `MStr` is owned.
    /// The lifetime can be chosen to be anything, including `'static`.
    ///
    /// If `s` is `Box<str>`, it will not reallocate.  
    /// If `s` is `String`, it [may reallocate](String::into_boxed_str) if there is excess capacity.  
    /// If `s` is `&str`, it will be copied to a new heap allocation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// # use std::borrow::Cow;
    /// let s = Box::<str>::from("foo");
    /// let ptr = s.as_ptr();
    /// let mstr = MStr::new_owned(s);
    ///
    /// assert!(mstr.is_owned());
    /// assert_eq!(mstr, "foo");
    /// assert_eq!(mstr.as_ptr(), ptr); // the allocation is reused
    /// assert!(matches!(mstr.into_cow(), Cow::Owned(_)));
    /// ```
    ///
    /// Passing a string slice makes an owned copy:
    /// ```rust
    /// # use mstr::MStr;
    /// let s = "bar";
    /// let ptr = s.as_ptr();
    /// let mstr = MStr::new_owned(s);
    ///
    /// assert!(mstr.is_owned());
    /// assert_eq!(mstr, s);
    /// assert_eq!(mstr, "bar");
    ///
    /// // a new allocation was created, and so the pointer are different
    /// assert_ne!(mstr.as_ptr(), s.as_ptr());
    /// ```
    #[must_use]
    pub fn new_owned(s: impl Into<Box<str>>) -> MStr<'a> {
        let s = s.into();

        let len = s.len();
        let ptr = Box::into_raw(s).cast::<u8>();

        MStr::_new(ptr, len, true)
    }

    /// Creates a new `MStr<'a>` from a `Cow<'a, str>`.
    ///
    /// The returned `MStr` will be borrowed if the cow is borrowed,
    /// and owned if the cow is owned.  
    /// If the cow is owned, and has excess capacity, it [may reallocate](String::into_boxed_str).
    ///
    /// # Examples
    ///
    /// Owned:
    /// ```rust
    /// # use mstr::MStr;
    /// # use std::borrow::Cow;
    /// let cow = Cow::Owned(String::from("foo"));
    /// let mstr = MStr::new_cow(cow);
    ///
    /// assert!(mstr.is_owned());
    /// assert_eq!(mstr, "foo");
    /// assert!(matches!(mstr.into_cow(), Cow::Owned(_)));
    /// ```
    ///
    /// Borrowed:
    /// ```rust
    /// # use mstr::MStr;
    /// # type Cow<'a> = std::borrow::Cow<'a, str>; // fix inference
    /// let s = String::from("bar");
    /// let cow = Cow::Borrowed(&s);
    /// let mstr = MStr::new_cow(cow);
    ///
    /// assert!(mstr.is_borrowed());
    /// assert_eq!(mstr, s);
    /// assert_eq!(mstr.as_ptr(), s.as_ptr());
    /// assert!(matches!(mstr.into_cow(), Cow::Borrowed(_)));
    /// ```
    ///
    /// Borrowed (static):
    /// ```rust
    /// # use mstr::MStr;
    /// # use std::borrow::Cow;
    /// let cow = Cow::Borrowed("qux");
    /// let mstr = MStr::new_cow(cow);
    ///
    /// assert!(mstr.is_borrowed());
    /// assert_eq!(mstr, "qux");
    /// assert!(matches!(mstr.into_cow(), Cow::Borrowed("qux")));
    /// ```
    #[inline]
    #[must_use]
    pub fn new_cow(s: Cow<'a, str>) -> MStr<'a> {
        match s {
            Cow::Borrowed(s) => MStr::new_borrowed(s),
            Cow::Owned(s) => MStr::new_owned(s),
        }
    }

    #[inline]
    #[must_use]
    const fn _new(ptr: *const u8, len: usize, tag: bool) -> MStr<'a> {
        MStr {
            // SAFETY: always comes from a valid string
            ptr: unsafe { NonNull::new_unchecked(ptr.cast_mut()) },
            len: if tag { len | TAG } else { len },
            _marker: PhantomData,
        }
    }

    // -- Accessors --

    /// Converts this `MStr` to a string slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let mstr = MStr::new_borrowed("foo");
    ///
    /// assert_eq!(mstr.as_str(), "foo");
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_str(&self) -> &str {
        unsafe { &*self.as_str_ptr() }
    }

    /// Converts this `MStr` to a UTF-8 byte slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let mstr = MStr::new_borrowed("foo");
    ///
    /// assert_eq!(mstr.as_bytes(), b"foo");
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8] {
        self.as_str().as_bytes()
    }

    /// Converts this `MStr` into an owned `String`.
    /// This will consume `self`.
    ///
    /// If `self` is owned, the allocation will be reused.  
    /// If `self` is borrowed, it will be copied to the heap.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let mstr = MStr::new_borrowed("foo");
    /// let s: String = mstr.into_string();
    ///
    /// assert_eq!(s, "foo");
    /// ```
    ///
    /// Reuses owned allocation:
    /// ```rust
    /// # use mstr::MStr;
    /// let owned = Box::<str>::from("bar");
    /// let ptr = owned.as_ptr();
    /// let mstr = MStr::new_owned(owned);
    /// let s = mstr.into_string();
    ///
    /// assert_eq!(s, "bar");
    /// assert_eq!(s.as_ptr(), ptr);
    /// ```
    #[inline]
    #[must_use]
    pub fn into_string(self) -> String {
        self.into_cow().into_owned()
    }

    /// Converts this `MStr` into an owned `Box<str>`.
    /// This will consume `self`.
    ///
    /// If `self` is owned, the allocation will be reused.  
    /// If `self` is borrowed, it will be copied to the heap.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let mstr = MStr::new_borrowed("foo");
    /// let s: Box<str> = mstr.into_boxed();
    ///
    /// assert_eq!(&*s, "foo");
    /// ```
    ///
    /// Reuses owned allocation:
    /// ```rust
    /// # use mstr::MStr;
    /// let owned = Box::<str>::from("bar");
    /// let ptr = owned.as_ptr();
    /// let mstr = MStr::new_owned(owned);
    /// let s = mstr.into_boxed();
    ///
    /// assert_eq!(&*s, "bar");
    /// assert_eq!(s.as_ptr(), ptr);
    /// ```
    #[inline]
    #[must_use]
    pub fn into_boxed(self) -> Box<str> {
        self.into_string().into_boxed_str()
    }

    /// Converts this `MStr<'a>` into a `Cow<'a, str>`.
    /// This will consume `self`.
    ///
    /// The returned cow will be owned if `self` is owned, and borrowed if `self` is borrowed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// # use std::borrow::Cow;
    /// let borrowed = MStr::new_borrowed("foo");
    /// let owned = MStr::new_owned("bar");
    ///
    /// assert!(matches!(borrowed.into_cow(), Cow::Borrowed("foo")));
    /// assert!(matches!(owned.into_cow(), Cow::Owned(_)));
    /// ```
    #[must_use]
    pub fn into_cow(self) -> Cow<'a, str> {
        let ptr = self.as_str_ptr();
        let is_owned = self.is_owned();
        mem::forget(self);

        if is_owned {
            let b = unsafe { Box::from_raw(ptr.cast_mut()) };
            Cow::Owned(b.into_string())
        } else {
            Cow::Borrowed(unsafe { &*ptr })
        }
    }

    /// Checks if this `MStr` is owned.
    ///
    /// The result of this function is mutually exclusive with [`is_borrowed`](MStr::is_borrowed).
    /// Exactly one of `is_borrowed` and `is_owned` will be true for every `MStr`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let mstr = MStr::new_owned("bar");
    ///
    /// assert!(mstr.is_owned());
    /// assert!(!mstr.is_borrowed());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_owned(&self) -> bool {
        self.len & TAG == TAG
    }

    /// Checks if this `MStr` is borrowed.
    ///
    /// The result of this function is mutually exclusive with [`is_owned`](MStr::is_owned).
    /// Exactly one of `is_borrowed` and `is_owned` will be true for every `MStr`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let mstr = MStr::new_borrowed("bar");
    ///
    /// assert!(mstr.is_borrowed());
    /// assert!(!mstr.is_owned());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_borrowed(&self) -> bool {
        self.len & TAG == 0
    }

    /// If this `MStr<'a>` is borrowed, get the underlying `&'a str`.
    /// Useful if you want access to the borrowed data for longer than the borrow of `&self`.
    ///
    /// This will return `Some` if `self` is borrowed, and `None` if `self` is owned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let mstr: MStr<'static> = MStr::new_borrowed("abc");
    /// let s: Option<&'static str> = mstr.as_borrowed();
    ///
    /// assert_eq!(s, Some("abc"));
    /// ```
    ///
    /// If `self` is owned:
    /// ```
    /// # use mstr::MStr;
    /// assert_eq!(MStr::new_owned("abc").as_borrowed(), None);
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_borrowed(&self) -> Option<&'a str> {
        if self.is_borrowed() {
            // SAFETY: self is borrowed which means it is an &'a str
            Some(unsafe { &*self.as_str_ptr() })
        } else {
            None
        }
    }

    /// Gets the length of the underlying string slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let mstr = MStr::new_borrowed("12345");
    ///
    /// assert_eq!(mstr.len(), 5);
    /// ```
    #[inline]
    #[must_use]
    pub const fn len(&self) -> usize {
        self.len & MASK
    }

    /// Checks if the underlying string slice is empty (length of 0)
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let empty = MStr::new_borrowed("");
    /// let mstr = MStr::new_borrowed("foo");
    ///
    /// assert!(empty.is_empty());
    /// assert!(!mstr.is_empty());
    /// ```
    #[inline]
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Gets a pointer (`*const u8`) to the underlying slice's buffer.
    ///
    /// Do **NOT** use the returned pointer mutably, as `self` may be borrowed.
    ///
    /// Use [`as_str_ptr`](MStr::as_str_ptr) if you want a `*const str` instead.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let s = "foo";
    /// let mstr = MStr::new_borrowed(s);
    ///
    /// assert_eq!(mstr.as_ptr(), s.as_ptr());
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_ptr(&self) -> *const u8 {
        self.ptr.as_ptr()
    }

    /// Gets a pointer (`*const str`) to the underlying slice's buffer.
    ///
    /// Do **NOT** use the returned pointer mutably, as `self` may be borrowed.
    ///
    /// Use [`as_ptr`](MStr::as_ptr) if you want a `*const u8` instead.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let s = "foo";
    /// let mstr = MStr::new_borrowed(s);
    ///
    /// assert_eq!(mstr.as_str_ptr(), s as *const str);
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_str_ptr(&self) -> *const str {
        ptr::slice_from_raw_parts::<u8>(self.as_ptr(), self.len()) as *const str
    }
}

// ===== Trait Impls =====

impl Clone for MStr<'_> {
    /// Clones this `MStr`.
    ///
    /// The returned `MStr` will be owned if `self` is owned, and borrowed if `self` is borrowed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let mstr = MStr::new_owned("foo");
    /// let mstr2 = mstr.clone();
    ///
    /// assert_eq!(mstr, mstr2);
    /// ```
    ///
    /// Borrowed/Owned is preserved:
    /// ```rust
    /// # use mstr::MStr;
    /// let borrowed = MStr::new_borrowed("bar");
    /// let owned = MStr::new_owned("qux");
    ///
    /// assert!(borrowed.clone().is_borrowed());
    /// assert!(owned.clone().is_owned());
    /// ```
    fn clone(&self) -> Self {
        if self.is_borrowed() {
            MStr::_new(self.as_ptr(), self.len(), false)
        } else {
            MStr::new_owned(self.as_str())
        }
    }
}

impl Drop for MStr<'_> {
    fn drop(&mut self) {
        if self.is_owned() {
            let b = unsafe { Box::from_raw(self.as_str_ptr().cast_mut()) };
            drop(b);
        }
    }
}

// -- Default --

impl Default for MStr<'_> {
    /// Creates a new, empty, borrowed `MStr`.
    ///
    /// The returned `MStr` can have any lifetime.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use mstr::MStr;
    /// let default = MStr::default();
    ///
    /// assert_eq!(default, "");
    /// assert!(default.is_empty());
    /// assert!(default.is_borrowed());
    /// ```
    fn default() -> Self {
        // a dangling (suitably aligned) slice of length 0 is always valid
        MStr::_new(NonNull::<u8>::dangling().as_ptr(), 0, false)
    }
}

// -- Format --

impl Debug for MStr<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(self.as_str(), f)
    }
}

impl Display for MStr<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(self.as_str(), f)
    }
}

impl Pointer for MStr<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Pointer::fmt(&self.as_str_ptr(), f)
    }
}

// -- Convert From --

impl<'a> From<&'a str> for MStr<'a> {
    fn from(value: &'a str) -> Self {
        MStr::new_borrowed(value)
    }
}

impl<'a> From<&'a mut str> for MStr<'a> {
    fn from(value: &'a mut str) -> Self {
        MStr::new_borrowed(value)
    }
}

impl<'a> From<Cow<'a, str>> for MStr<'a> {
    fn from(value: Cow<'a, str>) -> Self {
        MStr::new_cow(value)
    }
}

impl From<String> for MStr<'_> {
    fn from(value: String) -> Self {
        MStr::new_owned(value)
    }
}

impl From<Box<str>> for MStr<'_> {
    fn from(value: Box<str>) -> Self {
        MStr::new_owned(value)
    }
}

// -- Convert To --

impl<'a> From<MStr<'a>> for Cow<'a, str> {
    fn from(value: MStr<'a>) -> Self {
        value.into_cow()
    }
}

impl From<MStr<'_>> for String {
    fn from(value: MStr<'_>) -> Self {
        value.into_string()
    }
}

impl From<MStr<'_>> for Box<str> {
    fn from(value: MStr<'_>) -> Self {
        value.into_boxed()
    }
}

// -- Convert Ref --

impl Deref for MStr<'_> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl AsRef<str> for MStr<'_> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl AsRef<[u8]> for MStr<'_> {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl Borrow<str> for MStr<'_> {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

// no Borrow<[u8]> because str/String don't implement it
// (because the Hash impls are different)

// -- Hash --

impl Hash for MStr<'_> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        Hash::hash(self.as_str(), state)
    }
}

// -- [Partial]Eq --

impl Eq for MStr<'_> {}

impl PartialEq for MStr<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.as_str() == other.as_str()
    }
}

// str

impl PartialEq<str> for MStr<'_> {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<MStr<'_>> for str {
    fn eq(&self, other: &MStr<'_>) -> bool {
        self == other.as_str()
    }
}

// &str

impl PartialEq<&str> for MStr<'_> {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl PartialEq<MStr<'_>> for &str {
    fn eq(&self, other: &MStr<'_>) -> bool {
        *self == other.as_str()
    }
}

// String

impl PartialEq<String> for MStr<'_> {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<MStr<'_>> for String {
    fn eq(&self, other: &MStr<'_>) -> bool {
        self == other.as_str()
    }
}

// Box<str>

impl PartialEq<Box<str>> for MStr<'_> {
    fn eq(&self, other: &Box<str>) -> bool {
        self.as_str() == &**other
    }
}

impl PartialEq<MStr<'_>> for Box<str> {
    fn eq(&self, other: &MStr<'_>) -> bool {
        &**self == other.as_str()
    }
}

// -- [Partial]Ord --

impl Ord for MStr<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_str().cmp(other.as_str())
    }
}

impl PartialOrd for MStr<'_> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialOrd<str> for MStr<'_> {
    fn partial_cmp(&self, other: &str) -> Option<Ordering> {
        self.as_str().partial_cmp(other)
    }
}

impl PartialOrd<MStr<'_>> for str {
    fn partial_cmp(&self, other: &MStr<'_>) -> Option<Ordering> {
        self.partial_cmp(other.as_str())
    }
}

// ===== serde =====

#[cfg(feature = "serde")]
mod serde_impls {
    use super::*;
    use serde::de::{Deserialize, Deserializer, Error, Visitor};
    use serde::ser::{Serialize, Serializer};

    // -- Serialize --

    impl Serialize for MStr<'_> {
        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
            s.serialize_str(self.as_str())
        }
    }

    // -- Deserialize --

    struct MStrVisitor;

    impl Visitor<'_> for MStrVisitor {
        type Value = MStr<'static>;

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

        fn visit_str<E: Error>(self, s: &str) -> Result<Self::Value, E> {
            Ok(MStr::new_owned(s))
        }

        fn visit_string<E: Error>(self, s: String) -> Result<Self::Value, E> {
            Ok(MStr::new_owned(s))
        }
    }

    impl<'de> Deserialize<'de> for MStr<'_> {
        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
            d.deserialize_string(MStrVisitor)
        }
    }

    // -- Unit Tests --

    #[cfg(test)]
    mod tests {
        use super::*;
        use serde::de::DeserializeOwned;
        use serde_json::json;
        use serde_test::{assert_tokens, Token};

        #[test]
        fn basic() {
            assert_tokens(&MStr::from("roar"), &[Token::BorrowedStr("roar")]);
            assert_tokens(&MStr::from("honk"), &[Token::Str("honk")]);
            assert_tokens(&MStr::from("quack"), &[Token::String("quack")]);
        }

        #[test]
        fn always_de_owned() {
            let not_static = String::from("\"frogs <3\"");

            let s: MStr<'static> = serde_json::from_str(&not_static).unwrap();

            assert_eq!(s, "frogs <3");
            assert!(s.is_owned());
        }

        #[test]
        fn de_value() {
            let s: MStr<'static> =
                serde_json::from_value(json!("i like frogs can you tell")).unwrap();

            assert_eq!(s, "i like frogs can you tell");
            assert!(s.is_owned());
        }

        #[test]
        fn assert_deserialize_owned() {
            fn assert_deserialize_owned<T: DeserializeOwned>() {}

            assert_deserialize_owned::<MStr<'_>>();
            assert_deserialize_owned::<MStr<'static>>();
        }
    }
}

// ===== Unit Tests =====

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

    // fix inference
    type Cow<'a> = alloc::borrow::Cow<'a, str>;

    #[test]
    fn correct_repr() {
        assert!(MStr::new_borrowed("abc").is_borrowed());
        assert!(!MStr::new_borrowed("abc").is_owned());

        assert!(MStr::new_owned("123").is_owned());
        assert!(!MStr::new_owned("123").is_borrowed());
    }

    #[test]
    fn empty() {
        assert!(MStr::new_borrowed("").is_empty());
        assert!(MStr::new_owned("").is_empty());
        assert!(MStr::default().is_empty());

        assert_eq!(MStr::new_borrowed("").len(), 0);
        assert_eq!(MStr::new_owned("").len(), 0);
        assert_eq!(MStr::default().len(), 0);
    }

    #[test]
    fn owned_empty() {
        // even though its dangling it should still be marked as owned
        // behaviour has to be consistent
        assert!(MStr::new_owned("").is_owned());
        assert!(MStr::new_owned(Box::<str>::default()).is_owned());
    }

    #[test]
    fn len() {
        assert_eq!(MStr::new_borrowed("12345").len(), 5);
        assert_eq!(MStr::new_owned("12345").len(), 5);
    }

    #[test]
    fn borrowed_stays_borrowed() {
        let s = "1234";
        let mstr = MStr::new_borrowed(s);

        assert_eq!(mstr, s);
        assert_eq!(mstr.as_str(), s);

        assert_eq!(mstr.as_ptr(), s.as_ptr());
        assert_eq!(mstr.as_str().as_ptr(), s.as_ptr());
        assert_eq!(mstr.as_str_ptr(), s as *const str);

        let clone = mstr.clone();

        assert!(clone.is_borrowed());
        assert!(!clone.is_owned());

        assert_eq!(mstr, clone);
        assert_eq!(mstr.as_ptr(), clone.as_ptr());
        assert_eq!(mstr.as_str_ptr(), clone.as_str_ptr());
    }

    #[test]
    fn into_cow() {
        assert!(matches!(
            MStr::new_borrowed("meow").into_cow(),
            Cow::Borrowed("meow")
        ));
        assert!(matches!(
            MStr::new_cow(Cow::Borrowed("purr")).into_cow(),
            Cow::Borrowed("purr")
        ));

        assert!(matches!(MStr::new_owned("woof").into_cow(), Cow::Owned(_)));
        assert!(matches!(
            MStr::new_cow(Cow::Owned("bark".into())).into_cow(),
            Cow::Owned(_)
        ));

        assert_eq!(MStr::new_owned("woof").into_cow(), "woof");
        assert_eq!(MStr::new_cow(Cow::Owned("bark".into())).into_cow(), "bark");
    }

    #[test]
    fn roundtrip() {
        assert_eq!(MStr::new_borrowed("foo").into_string(), String::from("foo"));
        assert_eq!(MStr::new_owned("bar").into_string(), String::from("bar"));
    }

    #[test]
    fn roundtrip_string_ptr() {
        let s = String::from("quack");
        let ptr = s.as_ptr();
        let mstr = MStr::new_owned(s);

        assert_eq!(mstr, "quack");
        assert_eq!(mstr.as_ptr(), ptr);

        let s2 = mstr.into_string();
        assert_eq!(s2.as_ptr(), ptr);
    }

    #[test]
    fn owned_clone() {
        let mstr = MStr::new_owned("quack");
        let mstr2 = mstr.clone();

        assert!(mstr.is_owned());
        assert!(mstr2.is_owned());
        assert!(!mstr2.is_borrowed());

        assert_eq!(mstr, mstr2);
        assert_ne!(mstr.as_ptr(), mstr2.as_ptr());
        assert_ne!(mstr.as_str_ptr(), mstr2.as_str_ptr());
    }

    #[test]
    fn as_borrowed() {
        let s = String::from("meow");
        let mstr = MStr::new_borrowed(&s);
        let s2 = mstr.as_borrowed();
        drop(mstr);
        assert_eq!(s2, Some("meow"));
        assert_eq!(s2.unwrap(), s);
    }

    #[test]
    fn static_lt() {
        let owned: MStr<'static> = MStr::new_owned("abc");
        let borrowed: MStr<'static> = MStr::new_borrowed("abc");

        assert_eq!(owned, borrowed);
    }

    #[test]
    fn covariant_lt() {
        fn same_lt<'a>(a: &MStr<'a>, b: &MStr<'a>, s: &'a str) {
            assert_eq!(a, b);
            assert_eq!(a, s);
            assert_eq!(b, s);
        }

        let st1: MStr<'static> = MStr::new_borrowed("oink");
        let st2: MStr<'static> = MStr::new_owned("oink");

        same_lt(&st1, &st2, "oink");

        let s = String::from("oink");
        let ms = MStr::new_borrowed(&s);

        same_lt(&st1, &ms, &s);

        // --

        fn coerce_any_lt_owned<'a>() -> MStr<'a> {
            MStr::new_owned("abc")
        }
        assert_eq!(coerce_any_lt_owned(), "abc");

        fn coerce_any_lt_borrowed<'a>() -> MStr<'a> {
            MStr::new_borrowed("123")
        }
        assert_eq!(coerce_any_lt_borrowed(), "123");
    }

    #[test]
    fn assert_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}

        assert_send_sync::<MStr<'_>>();
        assert_send_sync::<MStr<'static>>();
    }
}