anycow 0.1.0

A supercharged container for read-heavy, occasionally-updated data structures with multiple storage strategies
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
//! # AnyCow - A Supercharged Container for Read-Heavy, Update-Light Data
//!
//! `AnyCow` is a versatile, high-performance container that extends the concept of `Cow`
//! (Clone-on-Write) with multiple storage strategies optimized for different use cases.
//! It's perfect for scenarios where you need to read values frequently but update them
//! only occasionally.
//!
//! ## Features
//!
//! - **Multiple Storage Strategies**: Choose the right storage for your use case
//! - **Lock-Free Updates**: Atomic updates using `arc-swap` for the `Updatable` variant
//! - **Thread-Safe Options**: Share data safely across threads
//! - **Zero-Cost Abstractions**: Minimal overhead for common operations
//!
//! ## Storage Variants
//!
//! - [`AnyCow::Borrowed`] - Zero-cost references for temporary data
//! - [`AnyCow::Owned`] - Heap-allocated owned data via `Box<T>`
//! - [`AnyCow::Shared`] - `Arc<T>` for shared immutable data across threads
//! - [`AnyCow::Updatable`] - Lock-free atomic updates using `arc-swap`
//! - [`AnyCow::Lazy`] - Lazy initialization with atomic updates for static contexts
//!
//! ## Quick Example
//!
//! ```rust
//! use anycow::AnyCow;
//!
//! // Create from different sources
//! let borrowed = AnyCow::borrowed(&"hello");
//! let owned = AnyCow::owned(String::from("world"));
//! let updatable = AnyCow::updatable(vec![1, 2, 3]);
//! let lazy = AnyCow::lazy(|| vec![7, 8, 9]);
//!
//! // Read values efficiently
//! println!("{}", *borrowed.borrow()); // "hello"
//! println!("{}", *owned.borrow());    // "world"
//!
//! // Atomic updates (lock-free!)
//! updatable.try_replace(vec![4, 5, 6]).unwrap();
//! lazy.try_replace(vec![10, 11, 12]).unwrap();
//! ```

use arc_swap::{ArcSwap, Guard};
use std::ops::Deref;
use std::sync::{Arc, OnceLock};

/// A supercharged container that can hold data in multiple storage formats,
/// optimized for read-heavy, occasionally-updated scenarios.
///
/// `AnyCow` extends the concept of `Cow` (Clone-on-Write) by providing multiple
/// storage strategies, each optimized for different use cases:
///
/// - **Borrowed**: Zero-cost references to existing data
/// - **Owned**: Heap-allocated owned data via `Box<T>`
/// - **Shared**: Reference-counted sharing via `Arc<T>`
/// - **Updatable**: Atomic, lock-free updates via `arc-swap`
/// - **Lazy**: Lazy initialization with atomic updates for static contexts
///
/// # Examples
///
/// ```rust
/// use anycow::AnyCow;
/// use std::sync::Arc;
///
/// // Different ways to create AnyCow
/// let borrowed = AnyCow::borrowed(&"hello");
/// let owned = AnyCow::owned(String::from("world"));
/// let shared = AnyCow::shared(Arc::new(42));
/// let updatable = AnyCow::updatable(vec![1, 2, 3]);
/// let lazy = AnyCow::lazy(|| vec![4, 5, 6]);
///
/// // All variants can be read the same way
/// assert_eq!(*borrowed.borrow(), "hello");
/// assert_eq!(*owned.borrow(), "world");
/// assert_eq!(*shared.borrow(), 42);
/// assert_eq!(*updatable.borrow(), vec![1, 2, 3]);
/// assert_eq!(*lazy.borrow(), vec![4, 5, 6]);
/// ```
pub enum AnyCow<'a, T>
where
    T: 'a + ToOwned,
{
    /// A borrowed reference to the data with zero allocation cost.
    ///
    /// This variant is ideal for temporary references and hot code paths
    /// where you want to avoid any allocation overhead.
    Borrowed(&'a T),

    /// Heap-allocated owned data stored in a `Box<T>`.
    ///
    /// This variant gives you ownership of the data stored on the heap
    /// and allows for direct mutation via [`to_mut()`](AnyCow::to_mut).
    /// Useful for data that needs to be owned and potentially large.
    Owned(Box<T>),

    /// Reference-counted shared data via `Arc<T>`.
    ///
    /// Perfect for sharing immutable data across multiple threads
    /// or when you need multiple owners of the same data.
    Shared(Arc<T>),

    /// Atomically updatable data using lock-free operations.
    ///
    /// This variant uses `arc-swap` to provide lock-free, atomic updates
    /// while allowing multiple concurrent readers. Ideal for configuration
    /// data, caches, or any shared state that needs occasional updates.
    Updatable(ArcSwap<T>),

    /// Lazy initialization with atomic updates.
    ///
    /// This variant combines lazy initialization with atomic updates.
    /// The data is initialized on first access using the provided closure,
    /// and can then be atomically updated like the `Updatable` variant.
    /// Perfect for static contexts where you need lazy initialization
    /// with subsequent atomic updates.
    ///
    /// The initialization function is stored as a function pointer to
    /// ensure the variant can be used in const contexts and static variables.
    Lazy {
        /// The lazily-initialized atomic data
        data: OnceLock<ArcSwap<T>>,
        /// The initialization function, called only once on first access
        init: fn() -> T,
    },
}

impl<'a, T> AnyCow<'a, T>
where
    T: 'a + ToOwned<Owned = T>,
{
    /// Creates a new `AnyCow` with a borrowed reference to the data.
    ///
    /// This is the most efficient variant as it involves no allocation
    /// and provides zero-cost access to the underlying data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// let data = "hello world";
    /// let cow = AnyCow::borrowed(&data);
    /// assert!(cow.is_borrowed());
    /// ```
    pub const fn borrowed(value: &'a T) -> Self {
        AnyCow::Borrowed(value)
    }

    /// Creates a new `AnyCow` with owned data stored in a `Box<T>`.
    ///
    /// The data is moved into a heap-allocated box and can be mutated
    /// via [`to_mut()`](Self::to_mut).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// let cow = AnyCow::owned(String::from("hello"));
    /// assert!(cow.is_owned());
    /// ```
    pub fn owned(value: T) -> Self {
        AnyCow::Owned(Box::new(value))
    }

    /// Creates a new `AnyCow` with reference-counted shared data.
    ///
    /// Perfect for sharing immutable data across multiple threads
    /// or when you need multiple owners.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    /// use std::sync::Arc;
    ///
    /// let data = Arc::new(String::from("shared data"));
    /// let cow = AnyCow::shared(data);
    /// ```
    pub const fn shared(value: Arc<T>) -> Self {
        AnyCow::Shared(value)
    }

    /// Creates a new `AnyCow` with atomically updatable data.
    ///
    /// This variant uses `arc-swap` for lock-free, atomic updates
    /// while allowing concurrent reads. Perfect for configuration
    /// data, caches, or shared state with infrequent updates.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// let cow = AnyCow::updatable(vec![1, 2, 3]);
    ///
    /// // Read the current value
    /// assert_eq!(*cow.borrow(), vec![1, 2, 3]);
    ///
    /// // Atomically update the value
    /// cow.try_replace(vec![4, 5, 6]).unwrap();
    /// assert_eq!(*cow.borrow(), vec![4, 5, 6]);
    /// ```
    pub fn updatable(value: T) -> Self {
        AnyCow::Updatable(ArcSwap::from(Arc::new(value)))
    }

    /// Creates a new `AnyCow` with lazy initialization and atomic updates.
    ///
    /// This variant combines lazy initialization with atomic updates.
    /// The data is initialized on first access using the provided function,
    /// and can then be atomically updated like the `Updatable` variant.
    /// Perfect for static contexts where you need lazy initialization.
    ///
    /// The initialization function is stored as a function pointer to
    /// ensure the variant can be used in const contexts and static variables.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// // Can be used in const contexts and static variables
    /// static GLOBAL_CONFIG: AnyCow<Vec<i32>> = AnyCow::lazy(|| vec![1, 2, 3]);
    ///
    /// // First access initializes the data
    /// assert_eq!(*GLOBAL_CONFIG.borrow(), vec![1, 2, 3]);
    ///
    /// // Subsequent updates work atomically
    /// GLOBAL_CONFIG.try_replace(vec![4, 5, 6]).unwrap();
    /// assert_eq!(*GLOBAL_CONFIG.borrow(), vec![4, 5, 6]);
    /// ```
    pub const fn lazy(init: fn() -> T) -> Self {
        AnyCow::Lazy {
            data: OnceLock::new(),
            init,
        }
    }

    /// Returns `true` if this `AnyCow` contains a borrowed reference.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// let data = "hello";
    /// let cow = AnyCow::borrowed(&data);
    /// assert!(cow.is_borrowed());
    ///
    /// let cow = AnyCow::owned(String::from("hello"));
    /// assert!(!cow.is_borrowed());
    /// ```
    pub const fn is_borrowed(&self) -> bool {
        matches!(self, AnyCow::Borrowed(_))
    }

    /// Returns `true` if this `AnyCow` contains owned data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// let cow = AnyCow::owned(String::from("hello"));
    /// assert!(cow.is_owned());
    ///
    /// let data = "hello";
    /// let cow = AnyCow::borrowed(&data);
    /// assert!(!cow.is_owned());
    /// ```
    pub const fn is_owned(&self) -> bool {
        matches!(self, AnyCow::Owned(_))
    }

    /// Returns `true` if this `AnyCow` contains shared data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    /// use std::sync::Arc;
    ///
    /// let cow = AnyCow::shared(Arc::new(String::from("hello")));
    /// assert!(cow.is_shared());
    ///
    /// let cow = AnyCow::owned(String::from("hello"));
    /// assert!(!cow.is_shared());
    /// ```
    pub const fn is_shared(&self) -> bool {
        matches!(self, AnyCow::Shared(_))
    }

    /// Returns `true` if this `AnyCow` contains updatable data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// let cow = AnyCow::updatable(String::from("hello"));
    /// assert!(cow.is_updatable());
    ///
    /// let cow = AnyCow::owned(String::from("hello"));
    /// assert!(!cow.is_updatable());
    /// ```
    pub const fn is_updatable(&self) -> bool {
        matches!(self, AnyCow::Updatable(_))
    }

    /// Returns `true` if this `AnyCow` contains lazy data.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// let cow = AnyCow::lazy(|| String::from("hello"));
    /// assert!(cow.is_lazy());
    ///
    /// let cow = AnyCow::owned(String::from("hello"));
    /// assert!(!cow.is_lazy());
    /// ```
    pub const fn is_lazy(&self) -> bool {
        matches!(self, AnyCow::Lazy { .. })
    }

    /// Returns a mutable reference to the owned data.
    ///
    /// If the data is not already owned, this method will clone it
    /// (following Clone-on-Write semantics) and convert the container
    /// to the `Owned` variant.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// let hello = String::from("hello");
    /// let mut cow = AnyCow::borrowed(&hello);
    /// assert!(cow.is_borrowed());
    ///
    /// // This will clone the data and make it owned
    /// let mutable_ref = cow.to_mut();
    /// *mutable_ref = String::from("world");
    ///
    /// assert!(cow.is_owned());
    /// assert_eq!(*cow.borrow(), "world");
    /// ```
    pub fn to_mut(&mut self) -> &mut T {
        match self {
            AnyCow::Borrowed(value) => {
                *self = AnyCow::Owned(Box::new(value.to_owned()));
                match self {
                    AnyCow::Owned(value) => value,
                    _ => unreachable!(),
                }
            }
            AnyCow::Owned(value) => value,
            AnyCow::Shared(value) => {
                *self = AnyCow::Owned(Box::new(value.as_ref().to_owned()));
                match self {
                    AnyCow::Owned(value) => value,
                    _ => unreachable!(),
                }
            }
            AnyCow::Updatable(value) => {
                let owned = value.load().as_ref().to_owned();
                *self = AnyCow::Owned(Box::new(owned));
                match self {
                    AnyCow::Owned(value) => value,
                    _ => unreachable!(),
                }
            }
            AnyCow::Lazy { data, init } => {
                let arc_swap = data.get_or_init(|| ArcSwap::from(Arc::new(init())));
                let owned = arc_swap.load().as_ref().to_owned();
                *self = AnyCow::Owned(Box::new(owned));
                match self {
                    AnyCow::Owned(value) => value,
                    _ => unreachable!(),
                }
            }
        }
    }

    /// Converts this `AnyCow` into owned data.
    ///
    /// This method consumes the container and returns the owned data,
    /// cloning if necessary. For `Arc` data, it will try to unwrap
    /// the `Arc` if there's only one reference, otherwise it will clone.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    /// use std::sync::Arc;
    ///
    /// let hello = String::from("hello");
    /// let cow = AnyCow::borrowed(&hello);
    /// let owned: String = cow.into_owned();
    /// assert_eq!(owned, "hello");
    ///
    /// let cow = AnyCow::shared(Arc::new(42));
    /// let owned: i32 = cow.into_owned();
    /// assert_eq!(owned, 42);
    /// ```
    pub fn into_owned(self) -> T {
        match self {
            AnyCow::Borrowed(value) => value.to_owned(),
            AnyCow::Owned(value) => *value,
            AnyCow::Shared(value) => {
                Arc::try_unwrap(value).unwrap_or_else(|arc| arc.as_ref().to_owned())
            }
            AnyCow::Updatable(value) => value.load().as_ref().to_owned(),
            AnyCow::Lazy { data, init } => {
                let arc_swap = data.get_or_init(|| ArcSwap::from(Arc::new(init())));
                arc_swap.load().as_ref().to_owned()
            }
        }
    }

    /// Returns a reference to the contained data.
    ///
    /// This method provides unified access to the data regardless of
    /// the storage variant. For the `Updatable` variant, this returns
    /// a guard that ensures the data remains valid during access.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    /// use std::sync::Arc;
    ///
    /// let borrowed = AnyCow::borrowed(&"hello");
    /// let owned = AnyCow::owned(String::from("world"));
    /// let shared = AnyCow::shared(Arc::new(42));
    ///
    /// assert_eq!(*borrowed.borrow(), "hello");
    /// assert_eq!(*owned.borrow(), "world");
    /// assert_eq!(*shared.borrow(), 42);
    /// ```
    pub fn borrow(&self) -> AnyCowRef<T> {
        match self {
            AnyCow::Borrowed(value) => AnyCowRef::Direct(value),
            AnyCow::Owned(value) => AnyCowRef::Direct(&**value),
            AnyCow::Shared(value) => AnyCowRef::Direct(value),
            AnyCow::Updatable(value) => AnyCowRef::Guarded(value.load()),
            AnyCow::Lazy { data, init } => {
                let arc_swap = data.get_or_init(|| ArcSwap::from(Arc::new(init())));
                AnyCowRef::Guarded(arc_swap.load())
            }
        }
    }

    /// Attempts to atomically replace the value in an `Updatable` or `Lazy` variant.
    ///
    /// This method succeeds if the container is of the `Updatable` or `Lazy` variant.
    /// The replacement is atomic and lock-free, making it perfect for
    /// concurrent scenarios. For `Lazy` variants, this will initialize the
    /// data if it hasn't been accessed before.
    ///
    /// # Returns
    ///
    /// - `Ok(())` if the replacement was successful
    /// - `Err(AnyCowReplaceError)` if this container is not an `Updatable` or `Lazy` variant
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    ///
    /// let updatable = AnyCow::updatable(vec![1, 2, 3]);
    /// assert_eq!(*updatable.borrow(), vec![1, 2, 3]);
    ///
    /// // Atomic replacement
    /// assert!(updatable.try_replace(vec![4, 5, 6]).is_ok());
    /// assert_eq!(*updatable.borrow(), vec![4, 5, 6]);
    ///
    /// // Also works with lazy variants
    /// let lazy = AnyCow::lazy(|| vec![7, 8, 9]);
    /// assert!(lazy.try_replace(vec![10, 11, 12]).is_ok());
    /// assert_eq!(*lazy.borrow(), vec![10, 11, 12]);
    ///
    /// // This will fail for other variants
    /// let owned = AnyCow::owned(vec![1, 2, 3]);
    /// assert!(owned.try_replace(vec![4, 5, 6]).is_err());
    /// ```
    pub fn try_replace(&self, new_val: T) -> Result<(), AnyCowReplaceError> {
        match self {
            AnyCow::Updatable(a) => {
                a.store(Arc::new(new_val));
                Ok(())
            }
            AnyCow::Lazy { data, init } => {
                let arc_swap = data.get_or_init(|| ArcSwap::from(Arc::new(init())));
                arc_swap.store(Arc::new(new_val));
                Ok(())
            }
            _ => Err(AnyCowReplaceError),
        }
    }

    /// Converts this `AnyCow` to an `Arc<T>`.
    ///
    /// This method will clone the data if necessary to create an `Arc`.
    /// If the container already holds an `Arc` (in the `Shared` or `Updatable`
    /// variants), it may reuse the existing `Arc`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    /// use std::sync::Arc;
    ///
    /// let cow = AnyCow::owned(String::from("hello"));
    /// let arc: Arc<String> = cow.to_arc();
    /// assert_eq!(*arc, "hello");
    /// ```
    pub fn to_arc(&self) -> Arc<T> {
        match self {
            AnyCow::Borrowed(value) => Arc::new((*value).to_owned()),
            AnyCow::Owned(value) => Arc::new((**value).to_owned()),
            AnyCow::Shared(value) => value.clone(),
            AnyCow::Updatable(value) => value.load().to_owned(),
            AnyCow::Lazy { data, init } => {
                let arc_swap = data.get_or_init(|| ArcSwap::from(Arc::new(init())));
                arc_swap.load().to_owned()
            }
        }
    }

    /// Converts this `AnyCow` to a shared variant.
    ///
    /// Borrowed stays borrowed (no heap allocation).
    /// All other variants allocate or clone into an Arc<T>.
    /// Calling to_shared on a Lazy will force initialization.
    ///
    /// # Conversion behavior:
    /// - `Borrowed` → stays `Borrowed` (zero-cost)
    /// - `Owned` → converts to `Shared` with `Arc`
    /// - `Shared` → returns a clone (cheap `Arc` clone)
    /// - `Updatable` → converts to `Shared` with current value
    /// - `Lazy` → initializes if needed and converts to `Shared`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anycow::AnyCow;
    /// use std::sync::Arc;
    ///
    /// let data = "hello";
    /// let borrowed = AnyCow::borrowed(&data);
    /// let shared = borrowed.to_shared();
    /// assert!(shared.is_borrowed()); // Still borrowed!
    ///
    /// let owned = AnyCow::owned(String::from("world"));
    /// let shared = owned.to_shared();
    /// assert!(shared.is_shared()); // Now shared
    /// ```
    pub fn to_shared(&self) -> AnyCow<'a, T> {
        match self {
            AnyCow::Borrowed(value) => AnyCow::Borrowed(value),
            _ => AnyCow::Shared(self.to_arc()),
        }
    }
}

/// Automatic conversion from owned values.
///
/// This implementation allows any owned value to be automatically
/// converted into an `AnyCow::Owned` variant.
///
/// # Examples
///
/// ```rust
/// use anycow::AnyCow;
///
/// let cow: AnyCow<String> = String::from("hello").into();
/// assert!(cow.is_owned());
/// ```
impl<T> From<T> for AnyCow<'_, T>
where
    T: ToOwned,
{
    fn from(value: T) -> Self {
        AnyCow::Owned(Box::new(value))
    }
}

/// Automatic conversion from borrowed references.
///
/// This implementation allows borrowed references to be automatically
/// converted into an `AnyCow::Borrowed` variant.
///
/// # Examples
///
/// ```rust
/// use anycow::AnyCow;
///
/// let data = String::from("hello");
/// let cow: AnyCow<String> = (&data).into();
/// assert!(cow.is_borrowed());
/// ```
impl<'a, T> From<&'a T> for AnyCow<'a, T>
where
    T: 'a + ToOwned,
{
    fn from(value: &'a T) -> Self {
        AnyCow::Borrowed(value)
    }
}

/// Automatic conversion from `Arc<T>`.
///
/// This implementation allows `Arc<T>` values to be automatically
/// converted into an `AnyCow::Shared` variant.
///
/// # Examples
///
/// ```rust
/// use anycow::AnyCow;
/// use std::sync::Arc;
///
/// let arc = Arc::new(String::from("hello"));
/// let cow: AnyCow<String> = arc.into();
/// ```
impl<T> From<Arc<T>> for AnyCow<'_, T>
where
    T: ToOwned,
{
    fn from(value: Arc<T>) -> Self {
        AnyCow::Shared(value)
    }
}

/// A reference to data contained in an `AnyCow`.
///
/// This enum provides unified access to data regardless of how it's stored
/// in the `AnyCow`. The `Guarded` variant is used for the `Updatable` storage
/// to ensure the data remains valid during access through lock-free mechanisms.
///
/// # Examples
///
/// ```rust
/// use anycow::AnyCow;
///
/// let cow = AnyCow::owned(String::from("hello"));
/// let cow_ref = cow.borrow();
/// assert_eq!(&*cow_ref, "hello");
/// ```
pub enum AnyCowRef<'a, T>
where
    T: 'a + ToOwned,
{
    /// A direct reference to the data.
    ///
    /// Used for `Borrowed`, `Owned`, `Shared`, and `Boxed` variants
    /// where we can provide a direct reference to the data.
    Direct(&'a T),

    /// A guarded reference to atomically-managed data.
    ///
    /// Used for the `Updatable` variant to ensure the data remains
    /// valid during access through the `arc-swap` guard mechanism.
    Guarded(Guard<Arc<T>>),
}

/// Provides transparent access to the contained data.
///
/// This implementation allows `AnyCowRef` to be used transparently
/// as if it were a direct reference to the contained data.
impl<'a, T> Deref for AnyCowRef<'a, T>
where
    T: 'a + ToOwned,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match self {
            AnyCowRef::Direct(value) => value,
            AnyCowRef::Guarded(guard) => guard.as_ref(),
        }
    }
}

/// Cloning support for `AnyCow`.
///
/// Cloning behavior varies by variant:
/// - `Borrowed`: Copies the reference (cheap)
/// - `Owned`: Clones the owned data in the box
/// - `Shared`: Clones the `Arc` (cheap reference counting)
/// - `Updatable`: Creates a new `Updatable` with a snapshot of current data
/// - `Lazy`: Always initializes and creates an `Updatable` with the initialized data
///
/// Note: Cloning a `Lazy` variant will trigger initialization if it hasn't
/// happened yet, and the resulting clone will be an `Updatable` variant.
/// This ensures that cloned data is immediately ready for use.
impl<'a, T> Clone for AnyCow<'a, T>
where
    T: 'a + ToOwned<Owned = T> + Clone,
{
    fn clone(&self) -> Self {
        match self {
            AnyCow::Borrowed(value) => AnyCow::Borrowed(value),
            AnyCow::Owned(value) => AnyCow::Owned(Box::new((**value).clone())),
            AnyCow::Shared(value) => AnyCow::Shared(value.clone()),
            AnyCow::Updatable(value) => {
                // Create a new Updatable with a snapshot of the current data
                // This maintains updatable semantics for the clone
                AnyCow::Updatable(ArcSwap::from(value.load().clone()))
            }
            AnyCow::Lazy { data, init } => {
                // Always initialize the lazy data when cloning to ensure the clone
                // has access to the actual data. This changes the clone from Lazy
                // to Updatable, which is intentional - once we've decided to clone
                // the data, we want it to be readily available.
                let arc_swap = data.get_or_init(|| ArcSwap::from(Arc::new(init())));
                AnyCow::Updatable(ArcSwap::from(arc_swap.load().clone()))
            }
        }
    }
}

/// Debug formatting for `AnyCow`.
///
/// Shows both the variant type and the contained data for easy debugging.
impl<'a, T> std::fmt::Debug for AnyCow<'a, T>
where
    T: 'a + ToOwned<Owned = T> + std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AnyCow::Borrowed(value) => f.debug_tuple("Borrowed").field(value).finish(),
            AnyCow::Owned(value) => f.debug_tuple("Owned").field(&**value).finish(),
            AnyCow::Shared(value) => f.debug_tuple("Shared").field(value).finish(),
            AnyCow::Updatable(value) => f.debug_tuple("Updatable").field(&*value.load()).finish(),
            AnyCow::Lazy { data, .. } => {
                if let Some(arc_swap) = data.get() {
                    f.debug_tuple("Lazy").field(&*arc_swap.load()).finish()
                } else {
                    f.debug_tuple("Lazy").field(&"<uninitialized>").finish()
                }
            }
        }
    }
}

/// Equality comparison for `AnyCow`.
///
/// Compares the contained data regardless of storage variant.
/// Two `AnyCow` instances are equal if their contained data is equal.
impl<'a, T> PartialEq for AnyCow<'a, T>
where
    T: 'a + ToOwned<Owned = T> + PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.borrow().deref() == other.borrow().deref()
    }
}

/// Full equality for `AnyCow`.
impl<'a, T> Eq for AnyCow<'a, T> where T: 'a + ToOwned<Owned = T> + Eq {}

/// Hash implementation for `AnyCow`.
///
/// Hashes the contained data regardless of storage variant.
impl<'a, T> std::hash::Hash for AnyCow<'a, T>
where
    T: 'a + ToOwned<Owned = T> + std::hash::Hash,
{
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.borrow().deref().hash(state)
    }
}

/// Partial ordering for `AnyCow`.
///
/// Compares the contained data regardless of storage variant.
impl<'a, T> PartialOrd for AnyCow<'a, T>
where
    T: 'a + ToOwned<Owned = T> + PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.borrow().deref().partial_cmp(other.borrow().deref())
    }
}

/// Total ordering for `AnyCow`.
///
/// Orders based on the contained data regardless of storage variant.
impl<'a, T> Ord for AnyCow<'a, T>
where
    T: 'a + ToOwned<Owned = T> + Ord,
{
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.borrow().deref().cmp(other.borrow().deref())
    }
}

/// Display formatting for `AnyCow`.
///
/// Displays the contained data regardless of storage variant.
impl<'a, T> std::fmt::Display for AnyCow<'a, T>
where
    T: 'a + ToOwned<Owned = T> + std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.borrow().deref().fmt(f)
    }
}

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub struct AnyCowReplaceError;