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
//! Miscelaneous utility functions

use std_::mem::{self,ManuallyDrop};

/// Allows transmuting between types of different sizes.
///
/// # Safety
///
/// This function has the same safety concerns as [::std::mem::transmute_copy].
#[inline(always)]
pub unsafe fn transmute_ignore_size<T, U>(v: T) -> U {
    let v=ManuallyDrop::new(v);
    mem::transmute_copy::<T, U>(&v)
}

#[inline(always)]
/// Converts a reference to T to a slice of 1 T.
pub fn as_slice<T>(v: &T) -> &[T] {
    unsafe { ::std_::slice::from_raw_parts(v, 1) }
}

#[inline(always)]
/// Converts a mutable reference to T to a mutable slice of 1 T.
pub fn as_slice_mut<T>(v: &mut T) -> &mut [T] {
    unsafe { ::std_::slice::from_raw_parts_mut(v, 1) }
}

/// Use this function to mark to the compiler that this branch is impossible.
///
/// This function panics when debug assertions are enabled,
/// if debug assertions are disabled then reaching this is undefined behaviour.
///
/// For a version which doesn't panic in debug builds but instead always causes
/// undefined behaviour when reached use
/// [unreachable_unchecked](::std::hint::unreachable_unchecked)
/// which was stabilized in Rust 1.27.
///
/// # Safety
///
/// It is undefined behaviour for this function to be reached at runtime at all.
///
/// The compiler is free to delete any code that reaches and depends on this function
/// on the assumption that this branch can't be reached.
///
/// # Example
/// ```
/// use core_extensions::BoolExt;
/// use core_extensions::utils::impossible;
///
/// mod only_even{
///     use super::*;
///     #[derive(Debug,Copy,Clone)]
///     pub struct NonZero(usize);
///
///     impl NonZero{
///         pub fn new(value:usize)->Option<NonZero> {
///             (value!=0).if_true(|| NonZero( value ) )
///         }
///         pub fn value(&self)->usize{
///             self.0
///         }
///     }
/// }
/// use self::only_even::NonZero;
///
/// # fn main(){
///
/// fn div(numerator:usize,denom:Option<NonZero>)->usize{
///     let denom=match denom {
///         Some(v)if v.value()==0 => unsafe{
///             // unreachable: NonZero::value() can never be 0,
///             impossible()
///         },
///         Some(v)=>v.value(),
///         None=>1,
///     };
///     numerator / denom
/// }
///
/// assert_eq!(div(60,NonZero::new(0)) , 60);
/// assert_eq!(div(60,NonZero::new(1)) , 60);
/// assert_eq!(div(60,NonZero::new(2)) , 30);
/// assert_eq!(div(60,NonZero::new(3)) , 20);
/// assert_eq!(div(60,NonZero::new(4)) , 15);
/// assert_eq!(div(60,NonZero::new(5)) , 12);
/// assert_eq!(div(60,NonZero::new(6)) , 10);
///
///
/// # }
///
///
///
/// ```
///
///
#[inline(always)]
pub unsafe fn impossible() -> ! {
    #[cfg(debug_assertions)]
    {
        panic!("reached core_extensions::impossible() ")
    }
    #[cfg(not(debug_assertions))]
    {
        use void::Void;
        match *(1 as *const Void) {}
    }
}


/////////////////////////////////////////////////////////


/// A wrapper type to run a closure at the end of the scope.
///
/// This allows construction with an explicitly captured value,
/// so that it can be used before the end of the scope.
///
/// ```rust
/// use core_extensions::utils::RunOnDrop;
///
/// fn main() { 
///     let mut guard = RunOnDrop::new("Hello".to_string(), |string|{
///         assert_eq!(string, "Hello, world!");
///     });
///
///     assert_eq!(guard.get(), "Hello");
///     
///     guard.get_mut().push_str(", world!");
/// }   
///
/// ```
pub struct RunOnDrop<T, F>
where
    F: FnOnce(T),
{
    value: ManuallyDrop<T>,
    function: ManuallyDrop<F>,
}

impl<T, F> RunOnDrop<T, F>
where
    F: FnOnce(T),
{
    /// Constructs this RunOnDrop.
    #[inline(always)]
    pub fn new(value: T, function: F) -> Self {
        Self {
            value: ManuallyDrop::new(value),
            function: ManuallyDrop::new(function),
        }
    }
}

impl<T, F> RunOnDrop<T, F>
where
    F: FnOnce(T),
{
    /// Reborrows the wrapped value.
    #[inline(always)]
    pub fn get(&self) -> &T {
        &*self.value
    }

    /// Reborrows the wrapped value mutably.
    #[inline(always)]
    pub fn get_mut(&mut self) -> &mut T {
        &mut *self.value
    }

    /// Extracts the wrapped value, preventing the closure from running at the end of the scope.
    pub fn into_inner(self) -> T {
        let mut this = ManuallyDrop::new(self);
        unsafe{
            let ret = take_manuallydrop(&mut this.value);
            ManuallyDrop::drop(&mut this.function);
            ret
        }
    }

}

impl<'a, T, F> Drop for RunOnDrop<T, F>
where
    F: FnOnce(T),
{
    #[inline(always)]
    fn drop(&mut self) {
        unsafe {
            let value = take_manuallydrop(&mut self.value);
            let function = take_manuallydrop(&mut self.function);
            function(value);
        }
    }
}


////////////////////////////////////////////////////////////////////////////////


/// Takes the contents out of a `ManuallyDrop<T>`.
///
/// # Safety
///
/// After this function is called `slot` becomes uninitialized and
/// must not be used again.
unsafe fn take_manuallydrop<T>(slot: &mut ManuallyDrop<T>) -> T {
    #[cfg(feature = "rust_1_42")]
    {
        ManuallyDrop::take(slot)
    }
    #[cfg(not(feature = "rust_1_42"))]
    {
        ::std_::ptr::read(slot as *mut ManuallyDrop<T> as *mut T)
    }
}


////////////////////////////////////////////////////////////////////////////////


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

    use std_::cell::Cell;  
    use test_utils::DecOnDrop;  

    
    #[test]
    fn drop_guard() {
        let count = Cell::new(0);
        
        {
            let guard = RunOnDrop::new(DecOnDrop::new(&count), |rod|{
                assert_eq!(count.get(), 15);
                drop(rod);
                assert_eq!(count.get(), 14);
            });

            assert_eq!(count.get(), 0);
            count.set(16);

            let clone = guard.get().clone();
            assert_eq!(count.get(), 16);
            drop(clone);
            assert_eq!(count.get(), 15);

        }

        assert_eq!(count.get(), 14);
    }

    #[test]
    fn unwrap_run_on_drop() {
        let count = Cell::new(0);
        
        {
            let guard = RunOnDrop::new(DecOnDrop::new(&count), |rod|{
                assert_eq!(count.get(), 15);
                drop(rod);
                assert_eq!(count.get(), 14);
            });

            assert_eq!(count.get(), 0);
            count.set(16);

            let clone = guard.get().clone();
            assert_eq!(count.get(), 16);
            drop(clone);
            assert_eq!(count.get(), 15);

            let rod = guard.into_inner();
            assert_eq!(count.get(), 15);
            drop(rod);
            assert_eq!(count.get(), 14);
        }

        assert_eq!(count.get(), 14);
    }


    #[test]
    fn take_manuallydrop_test(){
        let count = Cell::new(10);
        let mut md = ManuallyDrop::new(DecOnDrop::new(&count));

        assert_eq!(count.get(), 10);

        let dod = unsafe{ take_manuallydrop(&mut md) };
        assert_eq!(count.get(), 10);

        drop(dod);
        assert_eq!(count.get(), 9);
    }

}