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
//! This crate provides a [`Clone`] trait that can be used in trait objects, and
//! a [`clone_box`] function that can clone any sized or dynamically sized
//! implementation of `Clone`. Types that implement the standard library's
//! [`std::clone::Clone`] trait are automatically usable this way.
//! 
//! [`Clone`]: trait.Clone.html
//! [`clone_box`]: fn.clone_box.html
//! [`std::clone::Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html
//! 
//! # Example
//! 
//! ```edition2018
//! trait MyTrait: objekt::Clone {
//!     fn recite(&self);
//! }
//! 
//! impl MyTrait for String {
//!     fn recite(&self) {
//!         println!("{} ♫", self);
//!     }
//! }
//! 
//! fn main() {
//!     let line = "The slithy structs did gyre and gimble the namespace";
//! 
//!     // Build a trait object holding a String.
//!     // This requires String to implement MyTrait and std::clone::Clone.
//!     let x: Box<MyTrait> = Box::new(String::from(line));
//! 
//!     x.recite();
//! 
//!     // The type of x2 is a Box<MyTrait> cloned from x.
//!     let x2 = objekt::clone_box(&*x);
//! 
//!     x2.recite();
//! }
//! ```
//!
//! This crate includes a macro for concisely implementing `impl
//! std::clone::Clone for Box<MyTrait>` in terms of `objekt::clone_box`.
//!
//! ```edition2018
//! // As before.
//! trait MyTrait: objekt::Clone {
//!     /* ... */
//! }
//!
//! objekt::clone_trait_object!(MyTrait);
//!
//! // Now data structures containing Box<MyTrait> can derive Clone:
//! #[derive(Clone)]
//! struct Container {
//!     trait_object: Box<MyTrait>,
//! }
//! ```

#![doc(html_root_url = "https://docs.rs/objekt/0.1.2")]

#[macro_use]
mod macros;

#[doc(hidden)]
pub extern crate std as private;

/// This trait is implemented by any type that implements [`std::clone::Clone`].
///
/// [`std::clone::Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html
pub trait Clone {
    // Not public API
    #[doc(hidden)]
    unsafe fn clone_box(&self) -> *mut ();
}

pub fn clone<T>(t: &T) -> T
where
    T: Clone,
{
    unsafe {
        *Box::from_raw(<T as Clone>::clone_box(t) as *mut T)
    }
}

pub fn clone_box<T>(t: &T) -> Box<T>
where
    T: ?Sized + Clone,
{
    let mut fat_ptr = t as *const T;
    unsafe {
        let data_ptr = &mut fat_ptr as *mut *const T as *mut *mut ();
        assert_eq!(*data_ptr as *const (), t as *const T as *const ());
        *data_ptr = <T as Clone>::clone_box(t);
    }
    unsafe {
        Box::from_raw(fat_ptr as *mut T)
    }
}

impl<T> Clone for T
where
    T: std::clone::Clone,
{
    unsafe fn clone_box(&self) -> *mut () {
        Box::into_raw(Box::new(self.clone())) as *mut ()
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::{self, Display};
    use std::sync::{Arc, Mutex};

    struct Log {
        id: u64,
        events: Arc<Mutex<Vec<String>>>,
    }

    impl Clone for Log {
        fn clone(&self) -> Self {
            Log {
                id: self.id + 1,
                events: self.events.clone(),
            }
        }
    }

    impl Display for Log {
        fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            write!(formatter, "id={}", self.id)
        }
    }

    impl Drop for Log {
        fn drop(&mut self) {
            self.events.lock().unwrap().push(format!("dropping {}", self))
        }
    }

    #[test]
    fn clone_sized() {
        let arc = Arc::new(0);
        assert_eq!(Arc::strong_count(&arc), 1);

        let c = ::clone(&arc);
        assert_eq!(Arc::strong_count(&arc), 2);
        drop(c);
        assert_eq!(Arc::strong_count(&arc), 1);
    }

    #[test]
    fn clone_trait_object() {
        trait MyTrait: Display + Sync + super::Clone {}

        impl MyTrait for Log {}

        let events = Arc::new(Mutex::new(Vec::new()));
        let mut expected = Vec::new();
        {
            let b11: Box<MyTrait> = Box::new(Log {
                id: 11,
                events: events.clone(),
            });
            let b12 = ::clone_box(&*b11);
            assert_eq!(b11.to_string(), "id=11");
            assert_eq!(b12.to_string(), "id=12");
            expected.push("dropping id=12".to_owned());
            expected.push("dropping id=11".to_owned());
        }
        assert_eq!(*events.lock().unwrap(), expected);
    }
}