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
use std::borrow::{Borrow, BorrowMut};
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;

use clear::Clear;

/// Zeroizes a storage location when dropped.
///
/// This struct contains a reference to a memory location, either as a
/// mutable borrow (`&mut T`), or as a owned container (`Box<T>` or
/// similar). When this struct is dropped, the referenced location is
/// overwritten with its `Default` value.
///
/// # Example
///
/// ```
/// # use clear_on_drop::ClearOnDrop;
/// #[derive(Default)]
/// struct MyData {
///     value: u32,
/// }
///
/// let mut place = MyData { value: 0 };
/// {
///     let mut key = ClearOnDrop::new(&mut place);
///     key.value = 0x01234567;
///     // ...
/// }   // key is dropped here
/// assert_eq!(place.value, 0);
/// ```
pub struct ClearOnDrop<P>
    where P: DerefMut,
          P::Target: Clear
{
    _place: P,
}

impl<P> ClearOnDrop<P>
    where P: DerefMut,
          P::Target: Clear
{
    /// Creates a new `ClearOnDrop` which clears `place` on drop.
    ///
    /// The `place` parameter can be a `&mut T`, a `Box<T>`, or other
    /// containers which behave like `Box<T>`.
    #[inline]
    pub fn new(place: P) -> Self {
        ClearOnDrop { _place: place }
    }

    /// Consumes the `ClearOnDrop`, returning the `place` without clearing.
    ///
    /// Note: this is an associated function, which means that you have
    /// to call it as `ClearOnDrop::into_uncleared_place(c)` instead of
    /// `c.into_uncleared_place()`. This is so that there is no conflict
    /// with a method on the inner type.
    #[inline]
    pub fn into_uncleared_place(c: Self) -> P {
        unsafe {
            let place = ptr::read(&c._place);
            mem::forget(c);
            place
        }
    }

    /// Consumes the `ClearOnDrop`, returning the `place` after clearing.
    ///
    /// Note: this is an associated function, which means that you have
    /// to call it as `ClearOnDrop::into_place(c)` instead of
    /// `c.into_place()`. This is so that there is no conflict with a
    /// method on the inner type.
    #[inline]
    pub fn into_place(mut c: Self) -> P {
        c.clear();
        Self::into_uncleared_place(c)
    }
}

impl<P> Clone for ClearOnDrop<P>
    where P: DerefMut + Clone,
          P::Target: Clear
{
    #[inline]
    fn clone(&self) -> Self {
        ClearOnDrop { _place: Clone::clone(&self._place) }
    }

    #[inline]
    fn clone_from(&mut self, source: &Self) {
        self.clear();
        Clone::clone_from(&mut self._place, &source._place)
    }
}

impl<P> fmt::Debug for ClearOnDrop<P>
    where P: DerefMut + fmt::Debug,
          P::Target: Clear
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self._place, f)
    }
}

impl<P> Deref for ClearOnDrop<P>
    where P: DerefMut,
          P::Target: Clear
{
    type Target = P::Target;

    #[inline]
    fn deref(&self) -> &Self::Target {
        Deref::deref(&self._place)
    }
}

impl<P> DerefMut for ClearOnDrop<P>
    where P: DerefMut,
          P::Target: Clear
{
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        DerefMut::deref_mut(&mut self._place)
    }
}

impl<P> Drop for ClearOnDrop<P>
    where P: DerefMut,
          P::Target: Clear
{
    #[inline]
    fn drop(&mut self) {
        self.clear();
    }
}

// std::convert traits

impl<P, T: ?Sized> AsRef<T> for ClearOnDrop<P>
    where P: DerefMut + AsRef<T>,
          P::Target: Clear
{
    #[inline]
    fn as_ref(&self) -> &T {
        AsRef::as_ref(&self._place)
    }
}

impl<P, T: ?Sized> AsMut<T> for ClearOnDrop<P>
    where P: DerefMut + AsMut<T>,
          P::Target: Clear
{
    #[inline]
    fn as_mut(&mut self) -> &mut T {
        AsMut::as_mut(&mut self._place)
    }
}

// std::borrow traits

// The `T: Clear` bound avoids a conflict with the blanket impls
// `impl<T> Borrow<T> for T` and `impl<T> BorrowMut<T> for T`, since
// `ClearOnDrop<_>` is not `Clear`.

impl<P, T: ?Sized> Borrow<T> for ClearOnDrop<P>
    where P: DerefMut + Borrow<T>,
          P::Target: Clear,
          T: Clear
{
    #[inline]
    fn borrow(&self) -> &T {
        Borrow::borrow(&self._place)
    }
}

impl<P, T: ?Sized> BorrowMut<T> for ClearOnDrop<P>
    where P: DerefMut + BorrowMut<T>,
          P::Target: Clear,
          T: Clear
{
    #[inline]
    fn borrow_mut(&mut self) -> &mut T {
        BorrowMut::borrow_mut(&mut self._place)
    }
}

// std::hash traits

impl<P> Hash for ClearOnDrop<P>
    where P: DerefMut + Hash,
          P::Target: Clear
{
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        Hash::hash(&self._place, state)
    }
}

// std::cmp traits

impl<P, Q> PartialEq<ClearOnDrop<Q>> for ClearOnDrop<P>
    where P: DerefMut + PartialEq<Q>,
          P::Target: Clear,
          Q: DerefMut,
          Q::Target: Clear
{
    #[inline]
    fn eq(&self, other: &ClearOnDrop<Q>) -> bool {
        PartialEq::eq(&self._place, &other._place)
    }

    #[inline]
    fn ne(&self, other: &ClearOnDrop<Q>) -> bool {
        PartialEq::ne(&self._place, &other._place)
    }
}

impl<P> Eq for ClearOnDrop<P>
    where P: DerefMut + Eq,
          P::Target: Clear
{
}

impl<P, Q> PartialOrd<ClearOnDrop<Q>> for ClearOnDrop<P>
    where P: DerefMut + PartialOrd<Q>,
          P::Target: Clear,
          Q: DerefMut,
          Q::Target: Clear
{
    #[inline]
    fn partial_cmp(&self, other: &ClearOnDrop<Q>) -> Option<Ordering> {
        PartialOrd::partial_cmp(&self._place, &other._place)
    }

    #[inline]
    fn lt(&self, other: &ClearOnDrop<Q>) -> bool {
        PartialOrd::lt(&self._place, &other._place)
    }

    #[inline]
    fn le(&self, other: &ClearOnDrop<Q>) -> bool {
        PartialOrd::le(&self._place, &other._place)
    }

    #[inline]
    fn gt(&self, other: &ClearOnDrop<Q>) -> bool {
        PartialOrd::gt(&self._place, &other._place)
    }

    #[inline]
    fn ge(&self, other: &ClearOnDrop<Q>) -> bool {
        PartialOrd::ge(&self._place, &other._place)
    }
}

impl<P> Ord for ClearOnDrop<P>
    where P: DerefMut + Ord,
          P::Target: Clear
{
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        Ord::cmp(&self._place, &other._place)
    }
}

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

    #[derive(Debug, Default)]
    struct Place {
        data: [u32; 4],
    }

    const DATA: [u32; 4] = [0x01234567, 0x89abcdef, 0xfedcba98, 0x76543210];

    #[test]
    fn on_stack() {
        let mut place: Place = Default::default();
        {
            let mut clear = ClearOnDrop::new(&mut place);
            clear.data = DATA;
            assert_eq!(clear.data, DATA);
        }
        assert_eq!(place.data, [0; 4]);
    }

    #[test]
    fn on_box() {
        let place: Box<Place> = Box::new(Default::default());
        let mut clear = ClearOnDrop::new(place);
        clear.data = DATA;
        assert_eq!(clear.data, DATA);
    }

    #[test]
    fn into_box() {
        let place: Box<Place> = Box::new(Default::default());
        let mut clear = ClearOnDrop::new(place);
        clear.data = DATA;
        assert_eq!(clear.data, DATA);

        let place = ClearOnDrop::into_place(clear);
        assert_eq!(place.data, [0; 4]);
    }

    #[test]
    fn into_uncleared_box() {
        let place: Box<Place> = Box::new(Default::default());
        let mut clear = ClearOnDrop::new(place);
        clear.data = DATA;
        assert_eq!(clear.data, DATA);

        let place = ClearOnDrop::into_uncleared_place(clear);
        assert_eq!(place.data, DATA);
    }

    #[test]
    fn on_slice() {
        let mut place: [u32; 4] = Default::default();
        {
            let mut clear = ClearOnDrop::new(&mut place[..]);
            clear.copy_from_slice(&DATA);
            assert_eq!(&clear[..], DATA);
        }
        assert_eq!(place, [0; 4]);
    }

    #[test]
    fn on_boxed_slice() {
        let place: Box<[u32]> = vec![0; 4].into_boxed_slice();
        let mut clear = ClearOnDrop::new(place);
        clear.copy_from_slice(&DATA);
        assert_eq!(&clear[..], DATA);
    }
}