speedy_refs 0.2.7

A collection of simple and fast and useful smart pointers.
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
/// A `HeapCell` is Heap allocated type pointer.
/// Functions like `NonNull` + `UnsafeCell`
///
/// ## Note
/// - It moves the data onto the heap and stores a pointer to it.
/// - It never drops or deallocates the data it wraps until `drop()` and `dealloc()` methods are explicitly called or `drop_n_dealloc()` is called.
///
/// ## Uses
/// `HeapCell` can be accessed mutably through the `as_mut` method and immutably through the
/// `as_ref` method without requiring the container to be mutable.
///
/// ## Examples
///
/// ```
/// use speedy_refs::HeapCell;
///
/// let cell = HeapCell::new(42);
/// assert_eq!(unsafe { *cell.as_ref() }, 42);
///
/// unsafe {
///     *cell.as_mut() = 7;
///     assert_eq!(*cell.as_ref(), 7);
///
///     let val = cell.take();
///     assert_eq!(val, 7);
///
///     cell.replace(42);
///     assert_eq!(*cell.as_ref(), 42);
///
///     cell.drop_n_dealloc();
/// }
/// ```

pub struct HeapCell<T> {
    inner: *mut T,
}

impl<T> Clone for HeapCell<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T> HeapCell<T> {
    /// Creates a new `HeapCell` containing the given value.
    ///
    /// # Safety
    ///
    /// This function takes ownership of the given value and stores it behind a
    /// raw pointer. It is the responsibility of the caller to ensure that the
    /// value passed in is valid and the HeapCell is not used after the value has been
    /// dropped or moved.
    ///
    /// # Panics
    ///
    /// This function will panic if memory allocation fails.
    pub fn new(val: T) -> Self {
        Self {
            inner: Box::leak(Box::new(val)) as *mut T,
        }
    }

    /// Creates a mutable reference to T from an immutable reference to self.
    ///
    /// # Returns
    /// * **&mut T** - A mutable reference to the `self.inner` value
    ///
    /// # Safety
    /// This function returns a mutable reference to T by dereferencing a raw pointer.
    /// It is the responsibility of the caller to
    /// ensure that this method is not invoked while there is an outstanding
    /// **mutable** or **immutable** reference this same T, as that would lead to data races.
    ///
    pub unsafe fn as_mut(&self) -> &mut T {
        &mut *self.inner
    }

    /// Creates an immutable reference to self from an immutable reference to self.
    ///
    /// # Returns
    /// * &T - An immutable reference to T, the `self.inner` value
    ///
    /// # Safety
    /// This function returns an immutable reference to T by dereferencing a raw pointer.
    /// It is the responsibility of the caller to
    /// ensure that this method is not invoked while there is an outstanding
    /// **mutable** reference this same T, as that would lead to data races.
    pub unsafe fn as_ref(&self) -> &T {
        &*self.inner
    }

    /// Takes ownership of the value stored in the `HeapCell`.
    ///
    /// # Safety
    ///
    /// This function is marked as unsafe because it assumes ownership of the value
    /// behind the raw pointer held by the `HeapCell`. The caller must ensure that it is
    /// safe to take ownership of the value.
    ///
    /// # Returns
    ///
    /// This function returns the owned value of type `T` that was stored in the `HeapCell`.
    ///
    /// # Note
    ///
    /// The caller must ensure that the `HeapCell` is not used after calling `take`,
    /// as the `HeapCell` will be left in an invalid state.
    ///
    pub unsafe fn take(&self) -> T {
        // It is safe to call `from_raw` here, as the `self.inner` was originally created
        // using `Box::into_raw`.
        std::ptr::read(self.inner)
    }

    /// Drops the content and deallocates its memory.
    ///
    /// This function first calls drop on T and then deallocates the memory associated with it
    ///
    /// # Safety
    ///
    /// The caller must ensure that the `HeapCell` is not used after calling `deallocate` as
    /// `self.inner` will then point to an invalid memory.
    pub unsafe fn drop_n_dealloc(&self) {
        let ptr = self.inner;
        std::ptr::drop_in_place(ptr);
        std::alloc::dealloc(ptr as *mut u8, std::alloc::Layout::new::<T>());
    }
    /// Creates a new cell wrapping a clone of the inner value.
    ///
    /// # Returns
    /// The new cloned value
    pub fn clone_inner(&self) -> HeapCell<T>
    where
        T: Clone,
    {
        let clone = unsafe { self.inner.as_ref().unwrap() }.clone();
        HeapCell::new(clone)
    }

    /// Replaces the wraped value with `val` and returns the original one
    ///
    /// # Safety
    /// It is up to the caller to make sure that this method is not called while T is borrowed
    pub unsafe fn replace(&self, mut val: T) -> T {
        std::mem::swap(unsafe { self.as_mut() }, &mut val);
        val
    }

    // Calls drop on T, if it implements Drop
    #[inline]
    pub unsafe fn drop(&self) {
        std::ptr::drop_in_place(self.inner);
    }

    // Deallocates the momory associated with T
    #[inline]
    pub unsafe fn dealloc(&self) {
        std::alloc::dealloc(self.inner as *mut u8, std::alloc::Layout::new::<T>());
    }
}

/// # BorrowFlag
/// For `immutably` and `safely` tracking the reads and writes to an owned value.
///
/// Rust rules allow a number of reads or a single write at a time.
///
/// # Fields
/// * `inner: std::cell::UnsafeCell<isize>`
///
/// # Note
/// BorrowFlag is meant to be added as a field in your struct for added borrow checker functionalities since it
/// doesn't store the actual value described
///
#[repr(transparent)]
pub struct BorrowFlag {
    inner: std::cell::UnsafeCell<isize>,
}

impl BorrowFlag {
    /// Initiallizes a new BorrowFlag with 0 current reads and no current writer
    pub fn new() -> Self {
        Self {
            inner: std::cell::UnsafeCell::new(0),
        }
    }

    /// Checks if the described value can be borrowed immutably
    ///
    /// # Note
    /// The value can only be borrowed immutably if there is currently no mutable references to it
    ///
    /// # Returns
    /// * `true` - If immutable borrow is possible
    /// * `false` - If immutable borrow is impossible
    pub fn can_borrow(&self) -> bool {
        unsafe { *self.inner.get() >= 0 }
    }

    /// Checks if the described value can be borrowed mutably
    ///
    /// # Note
    /// The value can only be borrowed mutably if there is currently no mutable or immutable references to it.
    ///
    /// # Returns
    /// * `true` - If mutable borrow is possible
    /// * `false` - If mutable borrow is impossible
    pub fn can_borrow_mut(&self) -> bool {
        unsafe { *self.inner.get() == 0 }
    }

    /// Checks if the described value can be taken ownership of
    ///
    /// # Note
    /// The value can only be owned if there is currently no mutable or immutable references to it.
    ///
    /// # Returns
    /// * `true` - If taking ownership is possible
    /// * `false` - If taking ownership is impossible

    pub fn can_own(&self) -> bool {
        self.can_borrow_mut()
    }
    /// Marks a the start of a new read by increasing the count of the internal `readers`
    ///
    pub fn borrow(&self) {
        unsafe { std::ptr::write(self.inner.get(), *self.inner.get() + 1) }
    }
    /// Marks the end of an ongoing read by decrementing the count of the internal `readers`
    ///
    ///
    pub fn drop_borrow(&self) {
        unsafe { std::ptr::write(self.inner.get(), *self.inner.get() - 1) }
    }

    /// Marks the start of a write by setting the internal `write` field to true
    ///
    pub fn borrow_mut(&self) {
        unsafe { std::ptr::write(self.inner.get(), -1) }
    }
    /// Marks the end of a write session by setting the internal `write` field to false
    ///
    pub fn drop_borrow_mut(&self) {
        unsafe { std::ptr::write(self.inner.get(), 0) }
    }
}

/// An immutable borrow of RefCell
pub struct Ref<'a, T> {
    val: &'a mut Inner<T>,
}

/// Dropping a Ref object
impl<'a, T> Drop for Ref<'a, T> {
    #[inline]
    fn drop(&mut self) {
        self.val.flag -= 1;
    }
}

impl<'a, T> std::ops::Deref for Ref<'a, T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.val.val
    }
}

impl<'a, T> AsRef<T> for Ref<'a, T> {
    fn as_ref(&self) -> &T {
        std::ops::Deref::deref(self)
    }
}

pub struct RefMut<'a, T> {
    val: &'a mut Inner<T>,
}

impl<'a, T> RefMut<'a, T> {
    pub fn replace(&mut self, val: T) -> T {
        std::mem::replace(&mut self.val.val, val)
    }
}

impl<'a, T> std::ops::Deref for RefMut<'a, T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.val.val
    }
}

impl<'a, T> AsRef<T> for RefMut<'a, T> {
    fn as_ref(&self) -> &T {
        std::ops::Deref::deref(self)
    }
}

impl<'a, T> std::ops::DerefMut for RefMut<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.val.val
    }
}

impl<'a, T> AsMut<T> for RefMut<'a, T> {
    fn as_mut(&mut self) -> &mut T {
        std::ops::DerefMut::deref_mut(self)
    }
}

impl<'a, T> Drop for RefMut<'a, T> {
    #[inline]
    fn drop(&mut self) {
        self.val.flag = 0;
    }
}

/// # RefCell
/// A RefCell is a mutable memory location with dynamically checked borrow rules.
///
///
/// # vs std::cell::RefCell
/// //TODO
///
/// The `RefCell` stores a value of type `T`, and allows mutable access through the `borrow_mut` method,
/// which returns a `RefMut<T>` type. Immutable access is granted through the `borrow` method, which
/// returns a `Ref<T>` type.
///
/// # Panics
/// If any of the borrow rules are violated at runtime
///
/// # Others
/// The `take` method can be used to extract the value from the RefCell and invalidate the borrow flag.
///
/// The `Clone` trait is implemented for `RefCell<T>` only if `T` also implements `Clone`.
///
/// # Examples
///
/// ```
/// use speedy_refs::RefCell;
/// let x = RefCell::new(42);
/// // borrowing immutably
/// let y = x.borrow();
/// assert_eq!(*y, 42);
/// // attempting to borrow mutably while already borrowed immutably
/// // will panic at runtime ///
/// // let z = x.borrow_mut();
/// // uncomment to see the panic ///
///
/// // borrowing mutably
/// std::mem::drop(y);
/// let mut z = x.borrow_mut();
/// *z += 1;
/// assert_eq!(*z, 43);
/// // attempting to borrow immutably while already borrowed mutably will panic at runtime
/// /// // let y = x.borrow();
/// // uncomment to see the panic
///
/// // extracting the value from the RefCell
/// std::mem::drop(z);
/// let val = x.take();
/// assert_eq!(val, 43);
/// ```

pub struct RefCell<T> {
    inner: std::cell::UnsafeCell<Inner<T>>,
}

impl<T> RefCell<T> {
    /// Creates a new `RefCell` containing the given value.
    ///
    /// # Examples
    ///
    /// ```
    /// use speedy_refs::RefCell;
    ///
    /// let cell = RefCell::new(42);
    /// ```
    pub fn new(val: T) -> Self {
        Self {
            inner: std::cell::UnsafeCell::new(Inner::new(val)),
        }
    }

    /// Borrows the value immutably. Panics if the value is currently borrowed mutably.
    ///
    /// # Examples
    ///
    /// ```
    /// use speedy_refs::RefCell;
    ///
    /// let cell = RefCell::new(42);
    ///
    /// let reference = cell.borrow();
    ///
    /// assert_eq!(*reference, 42);
    /// ```
    pub fn borrow<'a>(&'a self) -> Ref<'a, T> {
        self.try_borrow()
            .expect("T cannot be borrowed immutably while T is borrowed mutably")
    }

    /// Tries to borrow the value immutably. Returns `None` if the value is currently borrowed mutably.
    ///
    /// # Examples
    ///
    /// ```
    /// use speedy_refs::RefCell;
    ///
    /// let cell = RefCell::new(42);
    ///
    /// let reference1 = cell.try_borrow().unwrap();
    /// assert_eq!(*reference1, 42);
    ///
    /// let reference2 = cell.try_borrow();
    /// assert!(reference2.is_none());
    /// ```
    pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> {
        unsafe {
            if (*self.inner.get()).flag == 0 {
                (&mut *self.inner.get()).flag += 1;
                Some(Ref {
                    val: &mut *self.inner.get(),
                })
            } else {
                None
            }
        }
    }

    /// Borrows the value mutably. Panics if the value is currently borrowed (either mutably or immutably).
    ///
    /// # Examples
    ///
    /// ```
    /// use speedy_refs::RefCell;
    ///
    /// let cell = RefCell::new(42);
    ///
    /// *cell.borrow_mut() = 13;
    ///
    /// let reference = cell.borrow();
    ///
    /// assert_eq!(*reference, 13);
    /// ```
    pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> {
        self.try_borrow_mut()
            .expect("T cannot be borrowed mutably while T is borrowed mutably or immutably")
    }

    /// Tries to borrow the value mutably. Returns `None` if the value is currently borrowed (either mutably or immutably).
    ///
    /// # Examples
    ///
    /// ```
    /// use speedy_refs::RefCell;
    ///
    /// let cell = RefCell::new(42);
    ///
    /// let mut mut_reference1 = cell.try_borrow_mut().unwrap();
    /// *mut_reference1 = 13;
    ///
    /// let mut_reference2 = cell.try_borrow_mut();
    /// assert!(mut_reference2.is_none());
    /// ```
    pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> {
        unsafe {
            if (*self.inner.get()).flag == 0 {
                (&mut *self.inner.get()).flag = -1;
                Some(RefMut {
                    val: &mut *self.inner.get(),
                })
            } else {
                None
            }
        }
    }

    pub fn take(mut self) -> T {
        if self.inner.get_mut().flag == 0 {
            let Inner { val, flag: _ } = self.inner.into_inner();
            val
        } else {
            panic!("T cannot be moved while T is borrowed mutably or immutably")
        }
    }
    /// Replaces the wrapped value with a new one computed from f, returning the old value, without deinitializing either one.
    ///
    /// # Panics
    ///Panics if the value is currently borrowed.
    pub fn replace(&self, val: T) -> T {
        self.borrow_mut().replace(val)
    }
}

impl<T: Clone> Clone for RefCell<T> {
    fn clone(&self) -> Self {
        unsafe { RefCell::new((*self.inner.get()).val.clone()) }
    }
}

struct Inner<T> {
    val: T,
    flag: isize,
}

impl<T> Inner<T> {
    fn new(val: T) -> Self {
        Self { val, flag: 0 }
    }
}

unsafe impl<T: Send> Send for RefCell<T> {}

/// # speedy_refs::RcCell
/// A reference-counted cell that allows for interior mutability.
///
/// This struct is essentially a zero-cost abstraction over using `std::rc::Rc<std::cell::RefCell<T>>`,
/// allowing for easier and more concise code. Multiple `RcCell` instances can share ownership of the
/// same value, and the value can be mutated even when there are shared references to it.
///
/// # Example
/// ```
/// use speedy_refs::RcCell;
/// let rc_cell = RcCell::new(42);
/// let shared_rc_cell = rc_cell.clone();
/// // Get a shared reference to the value inside the RcCell.
///
/// // Update the value inside the RcCell.
/// *rc_cell.borrow_mut() += 1;
///
/// let shared_ref = shared_rc_cell.borrow();
///
/// // The shared reference reflects the updated value.
/// assert_eq!(*shared_ref, 43);
/// ```

pub struct RcCell<T> {
    inner: std::rc::Rc<std::cell::RefCell<T>>,
}

impl<T> RcCell<T> {
    /// Creates a new `RcCell<T>` instance containing the provided value.
    pub fn new(value: T) -> RcCell<T> {
        Self {
            inner: std::rc::Rc::new(std::cell::RefCell::new(value)),
        }
    }
}

impl<T> Clone for RcCell<T> {
    /// Clones the `RcCell<T>` instance, creating a new instance that shares ownership of the same value.
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T> std::ops::Deref for RcCell<T> {
    type Target = std::cell::RefCell<T>;
    /// Dereferences the `RcCell<T>` instance to the underlying `RefCell<T>`.
    fn deref(&self) -> &Self::Target {
        std::ops::Deref::deref(&self.inner)
    }
}

/// Freely share multiple mutable references within a single thread.
///
///
/// A smart pointer that provides shared ownership of its contained value `T` in a single-threaded environment.
///
/// This struct uses an `UnsafeCell` internally to allow for interior mutability, which means that the value can be mutated
/// even if there are multiple references to it. However, it is not safe for concurrent access from multiple threads.
///
/// # Examples
/// ```
/// use speedy_refs::SharedCell;
/// // Create a new SharedCell with the initial value 42.
/// let cell = SharedCell::new(42);
/// // Get a shared reference to the contained value.
/// let value_ref = unsafe { cell.get_ref() };
/// assert_eq!(*value_ref, 42);
/// // Get a mutable reference to the contained value.
/// let value_mut_ref = unsafe { cell.get_mut() };
/// *value_mut_ref = 10;
/// assert_eq!(*value_ref, 10);
/// ```
pub struct SharedCell<T> {
    value: std::cell::UnsafeCell<T>,
}

impl<T> SharedCell<T> {
    /// Creates a new `SharedCell` instance with the specified initial value.
    pub fn new(value: T) -> SharedCell<T> {
        Self {
            value: std::cell::UnsafeCell::new(value),
        }
    }

    /// Returns a mutable reference to the contained value.
    ///
    /// This method uses the `UnsafeCell` internally to allow for mutable access without violating Rust's borrowing rules.
    /// However, it is marked as unsafe because it allows for multiple mutable references to the same value, which can lead
    /// to data races if not used correctly.
    ///  
    /// # Examples
    /// ```
    /// use speedy_refs::SharedCell;
    /// #[derive(Default)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let person = SharedCell::new(Person::default());
    ///
    /// unsafe {
    ///     person.get_mut().name = String::from("Dennis");
    ///     person.get_mut().age = 56;
    /// }
    /// assert_eq!(unsafe { person.get_ref().age }, 56);
    /// assert_eq!(unsafe { &person.get_ref().name }, &String::from("Dennis"));
    ///
    /// ```
    pub unsafe fn get_mut(&self) -> &mut T {
        &mut *self.value.get()
    }

    /// Returns a shared reference to the contained value.
    ///
    /// This method uses the `UnsafeCell` internally to allow for shared access without violating Rust's borrowing rules.
    /// However, it is marked as unsafe for the same reason as `get_mut`.
    ///
    /// # Examples
    /// ```
    /// use speedy_refs::SharedCell;
    /// #[derive(Default)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let person = SharedCell::new(Person::default());
    /// assert_eq!(unsafe { person.get_ref().age }, u32::default());
    /// assert_eq!(unsafe { &person.get_ref().name }, &String::default());
    ///
    /// ```
    #[inline(always)]
    pub unsafe fn get_ref(&self) -> &T {
        &*self.value.get()
    }
}

// We mark `SharedCell` as not `Sync` because it is not safe for concurrent access from multiple threads.
impl<T> !Sync for SharedCell<T> {}

// We mark `SharedCell` as `Send` if the contained type `T` is also `Send`.
unsafe impl<T: Send> Send for SharedCell<T> {}

#[cfg(test)]
mod tests {
    use serde::{Deserialize, Serialize};

    use crate::Borrow;

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    struct Data {
        item: String,
        value: f64,
    }

    impl Data {
        fn new(item: &str, value: f64) -> Data {
            Data {
                item: item.to_string(),
                value,
            }
        }
    }

    #[test]
    fn test_1() {
        let value = Data::new("Rust Weeklies", 98.1);
        let data = Borrow::new(value);
        println!("Old value: {:?}", data);
        let val = serde_json::to_string(&data).unwrap();
        println!("Serialized string = {}", val);
        let obj = serde_json::from_str::<Borrow<Data>>(&val).unwrap();

        println!("New value: {:?}", obj);
        assert_eq!(data, obj)
        // chatgpt says you can use {1,3,4}.min() in rust :)
    }

    #[test]
    fn test_2() {
        let vec = Borrow::new(vec![1, 2, 3]);

        let clone = vec.clone();

        // The clone also provides shared ownership and interior mutability of the same value.
        let mut shared_ref_1 = vec.clone();
        let mut shared_ref_2 = clone.clone();

        // Both shared references can be used to access the interior value.
        assert_eq!(*shared_ref_1, vec![1, 2, 3]);
        assert_eq!(*shared_ref_2, vec![1, 2, 3]);

        // The interior value can be mutated through either shared reference.
        shared_ref_1.push(4);
        assert_eq!(*shared_ref_2, vec![1, 2, 3, 4]);
        shared_ref_2.push(5);
        assert_eq!(*shared_ref_1, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_3() {
        #[derive(Debug, PartialEq, Eq)]
        struct Data(String, usize, bool, Vec<Self>);
        // Create a new variable
        let data = Data(String::from("Hello, World"), 100, false, vec![]);
        // Create a Borrow (a reference) with the variable
        let mut data_ref = Borrow::new(data);
        // Create another reference to the same variable
        let mut clone = Borrow::clone(&data_ref);
        // Use the Borrow seemlessly
        data_ref.0.push('!');
        clone.1 += 55;
        data_ref.2 = true;
        clone.3.push(Data("".into(), 0, false, Vec::new()));

        // Debug for JavaCell is same as that for Data
        println!("{:?}", clone);
        // Output
        //Data("Hello, World!", 155, true, [Data("", 0, false, [])])
        println!("{:?}", data_ref);
        // Output
        //Data("Hello, World!", 155, true, [Data("", 0, false, [])])

        assert_eq!(
            *data_ref,
            Data(
                String::from("Hello, World!"),
                155,
                true,
                vec![Data("".into(), 0, false, vec![])]
            )
        );
        assert_eq!(
            *clone,
            Data(
                String::from("Hello, World!"),
                155,
                true,
                vec![Data("".into(), 0, false, vec![])]
            )
        );
        // Borrow implements AsRef and Deref of T
        do_something(&data_ref);

        fn do_something(_data: &Data) {
            // do something
        }
    }
}