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
//! This module contains the `Oco` (Owned Clones Once) smart pointer,
//! which is used to store immutable references to values.
//! This is useful for storing, for example, strings.

use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::{
    borrow::{Borrow, Cow},
    ffi::{CStr, OsStr},
    fmt,
    hash::Hash,
    ops::{Add, Deref},
    path::Path,
    sync::Arc,
};

/// "Owned Clones Once" - a smart pointer that can be either a reference,
/// an owned value, or a reference counted pointer. This is useful for
/// storing immutable values, such as strings, in a way that is cheap to
/// clone and pass around.
///
/// The `Clone` implementation is amortized `O(1)`. Cloning the [`Oco::Borrowed`]
/// variant simply copies the references (`O(1)`). Cloning the [`Oco::Counted`]
/// variant increments a reference count (`O(1)`). Cloning the [`Oco::Owned`]
/// variant upgrades it to [`Oco::Counted`], which requires an `O(n)` clone of the
/// data, but all subsequent clones will be `O(1)`.
pub enum Oco<'a, T: ?Sized + ToOwned + 'a> {
    /// A static reference to a value.
    Borrowed(&'a T),
    /// A reference counted pointer to a value.
    Counted(Arc<T>),
    /// An owned value.
    Owned(<T as ToOwned>::Owned),
}

impl<'a, T: ?Sized + ToOwned> Oco<'a, T> {
    /// Converts the value into an owned value.
    pub fn into_owned(self) -> <T as ToOwned>::Owned {
        match self {
            Oco::Borrowed(v) => v.to_owned(),
            Oco::Counted(v) => v.as_ref().to_owned(),
            Oco::Owned(v) => v,
        }
    }

    /// Checks if the value is [`Oco::Borrowed`].
    /// # Examples
    /// ```
    /// # use std::sync::Arc;
    /// # use oco_ref::Oco;
    /// assert!(Oco::<str>::Borrowed("Hello").is_borrowed());
    /// assert!(!Oco::<str>::Counted(Arc::from("Hello")).is_borrowed());
    /// assert!(!Oco::<str>::Owned("Hello".to_string()).is_borrowed());
    /// ```
    pub const fn is_borrowed(&self) -> bool {
        matches!(self, Oco::Borrowed(_))
    }

    /// Checks if the value is [`Oco::Counted`].
    /// # Examples
    /// ```
    /// # use std::sync::Arc;
    /// # use oco_ref::Oco;
    /// assert!(Oco::<str>::Counted(Arc::from("Hello")).is_counted());
    /// assert!(!Oco::<str>::Borrowed("Hello").is_counted());
    /// assert!(!Oco::<str>::Owned("Hello".to_string()).is_counted());
    /// ```
    pub const fn is_counted(&self) -> bool {
        matches!(self, Oco::Counted(_))
    }

    /// Checks if the value is [`Oco::Owned`].
    /// # Examples
    /// ```
    /// # use std::sync::Arc;
    /// # use oco_ref::Oco;
    /// assert!(Oco::<str>::Owned("Hello".to_string()).is_owned());
    /// assert!(!Oco::<str>::Borrowed("Hello").is_owned());
    /// assert!(!Oco::<str>::Counted(Arc::from("Hello")).is_owned());
    /// ```
    pub const fn is_owned(&self) -> bool {
        matches!(self, Oco::Owned(_))
    }
}

impl<T: ?Sized + ToOwned> Deref for Oco<'_, T> {
    type Target = T;

    fn deref(&self) -> &T {
        match self {
            Oco::Borrowed(v) => v,
            Oco::Owned(v) => v.borrow(),
            Oco::Counted(v) => v,
        }
    }
}

impl<T: ?Sized + ToOwned> Borrow<T> for Oco<'_, T> {
    #[inline(always)]
    fn borrow(&self) -> &T {
        self.deref()
    }
}

impl<T: ?Sized + ToOwned> AsRef<T> for Oco<'_, T> {
    #[inline(always)]
    fn as_ref(&self) -> &T {
        self.deref()
    }
}

impl AsRef<Path> for Oco<'_, str> {
    #[inline(always)]
    fn as_ref(&self) -> &Path {
        self.as_str().as_ref()
    }
}

impl AsRef<Path> for Oco<'_, OsStr> {
    #[inline(always)]
    fn as_ref(&self) -> &Path {
        self.as_os_str().as_ref()
    }
}

// --------------------------------------
// pub fn as_{slice}(&self) -> &{slice}
// --------------------------------------

impl Oco<'_, str> {
    /// Returns a `&str` slice of this [`Oco`].
    /// # Examples
    /// ```
    /// # use oco_ref::Oco;
    /// let oco = Oco::<str>::Borrowed("Hello");
    /// let s: &str = oco.as_str();
    /// assert_eq!(s, "Hello");
    /// ```
    #[inline(always)]
    pub fn as_str(&self) -> &str {
        self
    }
}

impl Oco<'_, CStr> {
    /// Returns a `&CStr` slice of this [`Oco`].
    /// # Examples
    /// ```
    /// # use oco_ref::Oco;
    /// use std::ffi::CStr;
    ///
    /// let oco =
    ///     Oco::<CStr>::Borrowed(CStr::from_bytes_with_nul(b"Hello\0").unwrap());
    /// let s: &CStr = oco.as_c_str();
    /// assert_eq!(s, CStr::from_bytes_with_nul(b"Hello\0").unwrap());
    /// ```
    #[inline(always)]
    pub fn as_c_str(&self) -> &CStr {
        self
    }
}

impl Oco<'_, OsStr> {
    /// Returns a `&OsStr` slice of this [`Oco`].
    /// # Examples
    /// ```
    /// # use oco_ref::Oco;
    /// use std::ffi::OsStr;
    ///
    /// let oco = Oco::<OsStr>::Borrowed(OsStr::new("Hello"));
    /// let s: &OsStr = oco.as_os_str();
    /// assert_eq!(s, OsStr::new("Hello"));
    /// ```
    #[inline(always)]
    pub fn as_os_str(&self) -> &OsStr {
        self
    }
}

impl Oco<'_, Path> {
    /// Returns a `&Path` slice of this [`Oco`].
    /// # Examples
    /// ```
    /// # use oco_ref::Oco;
    /// use std::path::Path;
    ///
    /// let oco = Oco::<Path>::Borrowed(Path::new("Hello"));
    /// let s: &Path = oco.as_path();
    /// assert_eq!(s, Path::new("Hello"));
    /// ```
    #[inline(always)]
    pub fn as_path(&self) -> &Path {
        self
    }
}

impl<T> Oco<'_, [T]>
where
    [T]: ToOwned,
{
    /// Returns a `&[T]` slice of this [`Oco`].
    /// # Examples
    /// ```
    /// # use oco_ref::Oco;
    /// let oco = Oco::<[u8]>::Borrowed(b"Hello");
    /// let s: &[u8] = oco.as_slice();
    /// assert_eq!(s, b"Hello");
    /// ```
    #[inline(always)]
    pub fn as_slice(&self) -> &[T] {
        self
    }
}

impl<'a, T> Clone for Oco<'a, T>
where
    T: ?Sized + ToOwned + 'a,
    for<'b> Arc<T>: From<&'b T>,
{
    /// Returns a new [`Oco`] with the same value as this one.
    /// If the value is [`Oco::Owned`], this will convert it into
    /// [`Oco::Counted`], so that the next clone will be O(1).
    /// # Examples
    /// [`String`] :
    /// ```
    /// # use oco_ref::Oco;
    /// let oco = Oco::<str>::Owned("Hello".to_string());
    /// let oco2 = oco.clone();
    /// assert_eq!(oco, oco2);
    /// assert!(oco2.is_counted());
    /// ```
    /// [`Vec`] :
    /// ```
    /// # use oco_ref::Oco;
    /// let oco = Oco::<[u8]>::Owned(b"Hello".to_vec());
    /// let oco2 = oco.clone();
    /// assert_eq!(oco, oco2);
    /// assert!(oco2.is_counted());
    /// ```
    fn clone(&self) -> Self {
        match self {
            Self::Borrowed(v) => Self::Borrowed(v),
            Self::Counted(v) => Self::Counted(Arc::clone(v)),
            Self::Owned(v) => Self::Counted(Arc::from(v.borrow())),
        }
    }
}

impl<'a, T> Oco<'a, T>
where
    T: ?Sized + ToOwned + 'a,
    for<'b> Arc<T>: From<&'b T>,
{
    /// Clones the value with inplace conversion into [`Oco::Counted`] if it
    /// was previously [`Oco::Owned`].
    /// # Examples
    /// ```
    /// # use oco_ref::Oco;
    /// let mut oco1 = Oco::<str>::Owned("Hello".to_string());
    /// let oco2 = oco1.clone_inplace();
    /// assert_eq!(oco1, oco2);
    /// assert!(oco1.is_counted());
    /// assert!(oco2.is_counted());
    /// ```
    pub fn clone_inplace(&mut self) -> Self {
        match &*self {
            Self::Borrowed(v) => Self::Borrowed(v),
            Self::Counted(v) => Self::Counted(Arc::clone(v)),
            Self::Owned(v) => {
                let rc = Arc::from(v.borrow());
                *self = Self::Counted(rc.clone());
                Self::Counted(rc)
            }
        }
    }

    /// Converts the value into its cheaply-clonable form in place.
    /// In other words, if it is currently [`Oco::Owned`], converts into [`Oco::Counted`]
    /// in an `O(n)` operation, so that all future clones are `O(1)`.
    ///
    /// # Examples
    /// ```
    /// # use oco_ref::Oco;
    /// let mut oco = Oco::<str>::Owned("Hello".to_string());
    /// oco.upgrade_inplace();
    /// assert!(oco.is_counted());
    /// ```
    pub fn upgrade_inplace(&mut self) {
        if let Self::Owned(v) = &*self {
            let rc = Arc::from(v.borrow());
            *self = Self::Counted(rc);
        }
    }
}

impl<T: ?Sized> Default for Oco<'_, T>
where
    T: ToOwned,
    T::Owned: Default,
{
    fn default() -> Self {
        Oco::Owned(T::Owned::default())
    }
}

impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<Oco<'b, B>> for Oco<'a, A>
where
    A: PartialEq<B>,
    A: ToOwned,
    B: ToOwned,
{
    fn eq(&self, other: &Oco<'b, B>) -> bool {
        **self == **other
    }
}

impl<T: ?Sized + ToOwned + Eq> Eq for Oco<'_, T> {}

impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<Oco<'b, B>> for Oco<'a, A>
where
    A: PartialOrd<B>,
    A: ToOwned,
    B: ToOwned,
{
    fn partial_cmp(&self, other: &Oco<'b, B>) -> Option<std::cmp::Ordering> {
        (**self).partial_cmp(&**other)
    }
}

impl<T: ?Sized + Ord> Ord for Oco<'_, T>
where
    T: ToOwned,
{
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        (**self).cmp(&**other)
    }
}

impl<T: ?Sized + Hash> Hash for Oco<'_, T>
where
    T: ToOwned,
{
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        (**self).hash(state)
    }
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for Oco<'_, T>
where
    T: ToOwned,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl<T: ?Sized + fmt::Display> fmt::Display for Oco<'_, T>
where
    T: ToOwned,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl<'a, T: ?Sized> From<&'a T> for Oco<'a, T>
where
    T: ToOwned,
{
    fn from(v: &'a T) -> Self {
        Oco::Borrowed(v)
    }
}

impl<'a, T: ?Sized> From<Cow<'a, T>> for Oco<'a, T>
where
    T: ToOwned,
{
    fn from(v: Cow<'a, T>) -> Self {
        match v {
            Cow::Borrowed(v) => Oco::Borrowed(v),
            Cow::Owned(v) => Oco::Owned(v),
        }
    }
}

impl<'a, T: ?Sized> From<Oco<'a, T>> for Cow<'a, T>
where
    T: ToOwned,
{
    fn from(value: Oco<'a, T>) -> Self {
        match value {
            Oco::Borrowed(v) => Cow::Borrowed(v),
            Oco::Owned(v) => Cow::Owned(v),
            Oco::Counted(v) => Cow::Owned(v.as_ref().to_owned()),
        }
    }
}

impl<T: ?Sized> From<Arc<T>> for Oco<'_, T>
where
    T: ToOwned,
{
    fn from(v: Arc<T>) -> Self {
        Oco::Counted(v)
    }
}

impl<T: ?Sized> From<Box<T>> for Oco<'_, T>
where
    T: ToOwned,
{
    fn from(v: Box<T>) -> Self {
        Oco::Counted(v.into())
    }
}

impl From<String> for Oco<'_, str> {
    fn from(v: String) -> Self {
        Oco::Owned(v)
    }
}

impl From<Oco<'_, str>> for String {
    fn from(v: Oco<'_, str>) -> Self {
        match v {
            Oco::Borrowed(v) => v.to_owned(),
            Oco::Counted(v) => v.as_ref().to_owned(),
            Oco::Owned(v) => v,
        }
    }
}

impl<T> From<Vec<T>> for Oco<'_, [T]>
where
    [T]: ToOwned<Owned = Vec<T>>,
{
    fn from(v: Vec<T>) -> Self {
        Oco::Owned(v)
    }
}

impl<'a, T, const N: usize> From<&'a [T; N]> for Oco<'a, [T]>
where
    [T]: ToOwned,
{
    fn from(v: &'a [T; N]) -> Self {
        Oco::Borrowed(v)
    }
}

impl<'a> From<Oco<'a, str>> for Oco<'a, [u8]> {
    fn from(v: Oco<'a, str>) -> Self {
        match v {
            Oco::Borrowed(v) => Oco::Borrowed(v.as_bytes()),
            Oco::Owned(v) => Oco::Owned(v.into_bytes()),
            Oco::Counted(v) => Oco::Counted(v.into()),
        }
    }
}

/// Error returned from `Oco::try_from` for unsuccessful
/// conversion from `Oco<'_, [u8]>` to `Oco<'_, str>`.
#[derive(Debug, Clone, thiserror::Error)]
#[error("invalid utf-8 sequence: {_0}")]
pub enum FromUtf8Error {
    /// Error for conversion of [`Oco::Borrowed`] and [`Oco::Counted`] variants
    /// (`&[u8]` to `&str`).
    #[error("{_0}")]
    StrFromBytes(
        #[source]
        #[from]
        std::str::Utf8Error,
    ),
    /// Error for conversion of [`Oco::Owned`] variant (`Vec<u8>` to `String`).
    #[error("{_0}")]
    StringFromBytes(
        #[source]
        #[from]
        std::string::FromUtf8Error,
    ),
}

macro_rules! impl_slice_eq {
    ([$($g:tt)*] $((where $($w:tt)+))?, $lhs:ty, $rhs: ty) => {
        impl<$($g)*> PartialEq<$rhs> for $lhs
        $(where
            $($w)*)?
        {
            #[inline]
            fn eq(&self, other: &$rhs) -> bool {
                PartialEq::eq(&self[..], &other[..])
            }
        }

        impl<$($g)*> PartialEq<$lhs> for $rhs
        $(where
            $($w)*)?
        {
            #[inline]
            fn eq(&self, other: &$lhs) -> bool {
                PartialEq::eq(&self[..], &other[..])
            }
        }
    };
}

impl_slice_eq!([], Oco<'_, str>, str);
impl_slice_eq!(['a, 'b], Oco<'a, str>, &'b str);
impl_slice_eq!([], Oco<'_, str>, String);
impl_slice_eq!(['a, 'b], Oco<'a, str>, Cow<'b, str>);

impl_slice_eq!([T: PartialEq] (where [T]: ToOwned), Oco<'_, [T]>, [T]);
impl_slice_eq!(['a, 'b, T: PartialEq] (where [T]: ToOwned), Oco<'a, [T]>, &'b [T]);
impl_slice_eq!([T: PartialEq] (where [T]: ToOwned), Oco<'_, [T]>, Vec<T>);
impl_slice_eq!(['a, 'b, T: PartialEq] (where [T]: ToOwned), Oco<'a, [T]>, Cow<'b, [T]>);

impl<'a, 'b> Add<&'b str> for Oco<'a, str> {
    type Output = Oco<'static, str>;

    fn add(self, rhs: &'b str) -> Self::Output {
        Oco::Owned(String::from(self) + rhs)
    }
}

impl<'a, 'b> Add<Cow<'b, str>> for Oco<'a, str> {
    type Output = Oco<'static, str>;

    fn add(self, rhs: Cow<'b, str>) -> Self::Output {
        Oco::Owned(String::from(self) + rhs.as_ref())
    }
}

impl<'a, 'b> Add<Oco<'b, str>> for Oco<'a, str> {
    type Output = Oco<'static, str>;

    fn add(self, rhs: Oco<'b, str>) -> Self::Output {
        Oco::Owned(String::from(self) + rhs.as_ref())
    }
}

impl<'a> FromIterator<Oco<'a, str>> for String {
    fn from_iter<T: IntoIterator<Item = Oco<'a, str>>>(iter: T) -> Self {
        iter.into_iter().fold(String::new(), |mut acc, item| {
            acc.push_str(item.as_ref());
            acc
        })
    }
}

impl<'a, T> Deserialize<'a> for Oco<'static, T>
where
    T: ?Sized + ToOwned + 'a,
    T::Owned: DeserializeOwned,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'a>,
    {
        <T::Owned>::deserialize(deserializer).map(Oco::Owned)
    }
}

impl<'a, T> Serialize for Oco<'a, T>
where
    T: ?Sized + ToOwned + 'a,
    for<'b> &'b T: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.as_ref().serialize(serializer)
    }
}

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

    #[test]
    fn debug_fmt_should_display_quotes_for_strings() {
        let s: Oco<str> = Oco::Borrowed("hello");
        assert_eq!(format!("{:?}", s), "\"hello\"");
        let s: Oco<str> = Oco::Counted(Arc::from("hello"));
        assert_eq!(format!("{:?}", s), "\"hello\"");
    }

    #[test]
    fn partial_eq_should_compare_str_to_str() {
        let s: Oco<str> = Oco::Borrowed("hello");
        assert_eq!(s, "hello");
        assert_eq!("hello", s);
        assert_eq!(s, String::from("hello"));
        assert_eq!(String::from("hello"), s);
        assert_eq!(s, Cow::from("hello"));
        assert_eq!(Cow::from("hello"), s);
    }

    #[test]
    fn partial_eq_should_compare_slice_to_slice() {
        let s: Oco<[i32]> = Oco::Borrowed([1, 2, 3].as_slice());
        assert_eq!(s, [1, 2, 3].as_slice());
        assert_eq!([1, 2, 3].as_slice(), s);
        assert_eq!(s, vec![1, 2, 3]);
        assert_eq!(vec![1, 2, 3], s);
        assert_eq!(s, Cow::<'_, [i32]>::Borrowed(&[1, 2, 3]));
        assert_eq!(Cow::<'_, [i32]>::Borrowed(&[1, 2, 3]), s);
    }

    #[test]
    fn add_should_concatenate_strings() {
        let s: Oco<str> = Oco::Borrowed("hello");
        assert_eq!(s.clone() + " world", "hello world");
        assert_eq!(s.clone() + Cow::from(" world"), "hello world");
        assert_eq!(s + Oco::from(" world"), "hello world");
    }

    #[test]
    fn as_str_should_return_a_str() {
        let s: Oco<str> = Oco::Borrowed("hello");
        assert_eq!(s.as_str(), "hello");
        let s: Oco<str> = Oco::Counted(Arc::from("hello"));
        assert_eq!(s.as_str(), "hello");
    }

    #[test]
    fn as_slice_should_return_a_slice() {
        let s: Oco<[i32]> = Oco::Borrowed([1, 2, 3].as_slice());
        assert_eq!(s.as_slice(), [1, 2, 3].as_slice());
        let s: Oco<[i32]> = Oco::Counted(Arc::from([1, 2, 3]));
        assert_eq!(s.as_slice(), [1, 2, 3].as_slice());
    }

    #[test]
    fn default_for_str_should_return_an_empty_string() {
        let s: Oco<str> = Default::default();
        assert!(s.is_empty());
    }

    #[test]
    fn default_for_slice_should_return_an_empty_slice() {
        let s: Oco<[i32]> = Default::default();
        assert!(s.is_empty());
    }

    #[test]
    fn default_for_any_option_should_return_none() {
        let s: Oco<Option<i32>> = Default::default();
        assert!(s.is_none());
    }

    #[test]
    fn cloned_owned_string_should_make_counted_str() {
        let s: Oco<str> = Oco::Owned(String::from("hello"));
        assert!(s.clone().is_counted());
    }

    #[test]
    fn cloned_borrowed_str_should_make_borrowed_str() {
        let s: Oco<str> = Oco::Borrowed("hello");
        assert!(s.clone().is_borrowed());
    }

    #[test]
    fn cloned_counted_str_should_make_counted_str() {
        let s: Oco<str> = Oco::Counted(Arc::from("hello"));
        assert!(s.clone().is_counted());
    }

    #[test]
    fn cloned_inplace_owned_string_should_make_counted_str_and_become_counted()
    {
        let mut s: Oco<str> = Oco::Owned(String::from("hello"));
        assert!(s.clone_inplace().is_counted());
        assert!(s.is_counted());
    }

    #[test]
    fn cloned_inplace_borrowed_str_should_make_borrowed_str_and_remain_borrowed(
    ) {
        let mut s: Oco<str> = Oco::Borrowed("hello");
        assert!(s.clone_inplace().is_borrowed());
        assert!(s.is_borrowed());
    }

    #[test]
    fn cloned_inplace_counted_str_should_make_counted_str_and_remain_counted() {
        let mut s: Oco<str> = Oco::Counted(Arc::from("hello"));
        assert!(s.clone_inplace().is_counted());
        assert!(s.is_counted());
    }

    #[test]
    fn serialization_works() {
        let s = serde_json::to_string(&Oco::Borrowed("foo"))
            .expect("should serialize string");
        assert_eq!(s, "\"foo\"");
    }

    #[test]
    fn deserialization_works() {
        let s: Oco<str> = serde_json::from_str("\"bar\"")
            .expect("should deserialize from string");
        assert_eq!(s, Oco::from(String::from("bar")));
    }
}