high_mem_utils 0.2.7

This crate provides a bunch of mem safe abstractions,some involving transmute.
Documentation
#![doc(html_root_url = "https://docs.rs/high_mem_utils/0.2.7/")]
#![feature(vec_leak, untagged_unions, const_fn, const_fn_union)]
#![allow(unused_unsafe, clippy::wrong_self_convention, clippy::map_entry)]

/*!
This crate provides high-level memory abstractions used for ensure memory and exception safety in some
patterns.

High-level signifies that it only brings safe abstractions for some cases of transmute and others unsafe
functions in the mem or ptr module,does not provide a custom allocator or garbage collector neither depends
on the [core::alloc] unstable lib.

At the moment this crate is nightly only,this will change if the features [`vec_leak`], [`const_fn`],
[`untagged_unions`] and [`const_fn_union`] get stabilished.

# Examples

```
use high_mem_utils::{Catch, DontDropOpt, DropBy};

let mut string = String::from("Hello world!");
let catch = Catch::new_str(string.clone());

assert_eq!(catch.leaked().to_string(), string); // leaked returns &&mut str,not use to_string
                                                // it's a bit difficult cast rigth now

assert_eq!(catch.seal(), string); // catch consumed
let mut a = [1, 2, 3];

{
    let elem = DropBy::new([2, 3, 4], |e: [u32; 3]| { a = e.clone(); });

    assert_eq!(*elem, Some([2, 3, 4]));
}

assert_eq!(a, [2, 3, 4]);

unsafe {
    let b = DontDropOpt::new([1, 2, 3]); // we're not dropping here because we will have two variables
                                 // pointing to the same memory and "b" lives for shorter
    a = [0; 3];
    b.as_ref().unwrap().as_ptr().copy_to(a.as_mut_ptr(), 3);
}

assert_eq!(a, [1, 2, 3]);
```

[`vec_leak`]: https://github.com/rust-lang/rust/issues/62195
[`untagged_unions`]: https://github.com/rust-lang/rust/issues/32836
[`const_fn_union`]: https://github.com/rust-lang/rust/issues/51909
[`const_fn`]: https://github.com/rust-lang/rust/issues/57563
[core::alloc]: https://doc.rust-lang.org/core/alloc/index.html
*/

use core::mem::{take, ManuallyDrop, MaybeUninit, forget, align_of};
use core::ops::{Deref, DerefMut};
use core::fmt::{Debug, Pointer};
use core::hash::Hash;
use core::ptr::NonNull;
use std::collections::BTreeMap;
use fast_new_type::new_type;

/// A trait that represents a [`raw pointer`] or [`NonNull<T>`],useful for functions that creates them.
/// 
/// This trait is unsafe because the [`dangling`] safe function requires the implementors to have less
/// or equal size and equal alignment of an [`usize`],otherwise it will be UB.
/// 
/// [`NonNull<T>`]: https://doc.rust-lang.org/core/ptr/struct.NonNull.html
/// [`raw pointer`]: https://doc.rust-lang.org/std/primitive.pointer.html
/// [`dangling`]: ../dangling.fn.html
pub unsafe trait RawPointer<T: ?Sized>: Copy + Clone + Pointer + Debug + PartialEq + Eq + Hash + PartialOrd + Ord + Unpin {}

unsafe impl<T: ?Sized> RawPointer<T> for *const T {}
unsafe impl<T: ?Sized> RawPointer<T> for *mut T {}
unsafe impl<T: ?Sized> RawPointer<T> for NonNull<T> {} 

#[repr(packed)]
union Ptr<T, U: RawPointer<T>> {
    address: usize,
    ptr: U,
    p: core::marker::PhantomData<T>
}

/// Creates a dangling but well-aligned raw pointer.
/// 
/// # Examples
/// 
/// ```
/// use high_mem_utils::dangling;
/// use core::slice::{from_raw_parts, from_raw_parts_mut};
/// 
/// assert_eq!(unsafe { from_raw_parts::<i32>(dangling(), 0) }, &[]);
/// assert_eq!(unsafe { from_raw_parts_mut::<i32>(dangling(), 0) }, &[]);
/// ```
#[inline]
pub const fn dangling<T, U: RawPointer<T>>() -> U {
    unsafe { Ptr { address: align_of::<T>() }.ptr }
} 

#[cfg(feature = "serde_support")]
use serde::{Serialize, Deserialize};

/// This macro panics with the given message with debug_assertions on and call
/// [unreachable_unchecked](https://doc.rust-lang.org/std/hint/fn.unreachable_unchecked.html) when off.
/// 
/// # Safety
/// 
/// You should use this macro for code that must not reach.But all the cases where can are not handled and
/// will be handled on release or otherwise the responsability of do it passed to another caller,via unsafe
/// interfaces. 
#[macro_export]
macro_rules! unreachable_debug {
    () => { unreachable!("entered unreachable code") };
    ($e:expr) => {
        if cfg!(not(debug_assertions)) {
            unsafe { std::hint::unreachable_unchecked() };
        } else {
            panic!($e);
        }
    }
}

/// An union type that can be leaked or sealed(owned),useful when you want to give temporal global access to a particular value.
pub union Catch<'a, T: ?Sized> {
    leaked: &'a mut T,
    sealed: ManuallyDrop<Box<T>>,
}

impl<'a, U> Catch<'a, [U]> {
    /// Creates a new Catch with a leak, you can lately get the underlying sequence and consume the Catch
    /// with the [`seal`](#method.seal) method.
    pub fn new_seq(a: Vec<U>) -> Self {
        Catch {
            leaked: Vec::leak(a),
        }
    }

    /// Returns a a reference to the leaked field,as the only safe ways for construct this union returns a leaked
    /// one,for warranty never transmute stack to heap data,this method does not transmute implicitly.
    pub fn leaked(&self) -> &&'a mut [U] {
        unsafe { &self.leaked }
    }

    /// Consumes the Catch and gets the inner Vec<T>, preventing the memory leak.
    ///
    /// This does a call to transmute but,as the only safe ways for construct this union returns a leaked
    /// one,this never trigger undefined behavior by itself.
    pub fn seal(self) -> Vec<U> {
        unsafe { ManuallyDrop::into_inner(self.sealed).into_vec() }
    }
    /// Consumes the Catch and returns a mutable reference pointing to leaked data.
    pub fn leak(self) -> &'a mut [U] {
        unsafe { self.leaked }
    }

    /// Creates a new Catch from a `&mut [U]`,without checking if the referent is in the heap.
    ///
    /// # Safety
    ///
    /// This function should only be used with data returned by the [`leak`](#method.leak) method from a safely constructed
    /// Catch or with data returned by `Vec::leak` otherwise this will trigger undefined behavior
    /// if the [`seal`](#method.seal) method is called.
    pub unsafe fn from_leaked(leaked: &'a mut [U]) -> Self {
        Catch { leaked }
    }
}


impl<'a> Catch<'a, str> {
    /// Creates a new Catch with a leak, you can lately get the underlying string and consume the Catch
    /// with the [`seal`](#method.seal) method.
    pub fn new_str(a: String) -> Self {
        Catch {
            leaked: Box::leak(a.into_boxed_str()),
        }
    }

    /// Returns a a reference to the leaked field,as the only safe ways for construct this union returns a leaked
    /// one,for warranty never transmute stack to heap data,this method does not use transmute implicitly.
    pub fn leaked(&self) -> &&'a mut str {
        unsafe { &self.leaked }
    }

    /// Consumes the Catch and gets the inner String,preventing the memory leak.
    ///
    /// This does a call to transmute but,as the only safe ways for construct this union return a leaked
    /// one,this never trigger undefined behavior by itself.
    pub fn seal(self) -> String {
        unsafe { ManuallyDrop::into_inner(self.sealed).into_string() }
    }

    /// Consumes the Catch and returns a mutable reference pointing to leaked data.
    pub fn leak(self) -> &'a mut str {
        unsafe { self.leaked }
    }

    /// Creates a new CatchStr from a `&mut str`,without checking if the referent is in the heap.
    ///
    /// # Safety
    ///
    /// This function should only be used with data returned by the [`leak`](#method.leak) method from a safely constructed
    /// Catch or with data returned by `Box::leak(string.into_boxed_str())` otherwise this will trigger undefined behavior
    /// if the [`seal`](#method.seal) method is called.
    pub unsafe fn from_leaked(leaked: &'a mut str) -> Self {
        Catch { leaked }
    }
}

impl<'a, T> Catch<'a, T> {
    /// Creates a new Catch with a leak, you can lately get the underlying value and consume the Catch
    /// with the [`seal`](#method.seal) method.
    pub fn new(a: Box<T>) -> Self {
        Catch {
            leaked: Box::leak(a),
        }
    }

    /// Returns a reference to the leaked field,'cause the only ways for construct this union returns
    /// a leaked one,for warranty never transmute stack to heap data,this method does not use transmute
    /// implicitly.
    pub fn leaked(&self) -> &&'a mut T {
        unsafe { &self.leaked }
    }
    
    /// Returns a mutable reference to the sealed field.
    pub fn sealed(&mut self) -> &mut ManuallyDrop<Box<T>> {
        unsafe { &mut self.sealed }
    }

    /// Consumes the Catch and gets the inner Box\<T\>,preventing the memory leak.
    ///
    /// This does a call to transmute but,as the only ways to construct this union gives you a leaked one
    /// this never trigger undefined behavior by itself.
    pub fn seal(self) -> Box<T> {
        unsafe { ManuallyDrop::into_inner(self.sealed) }
    }

    /// Consumes the Catch and returns a mutable reference pointing to leaked data.
    pub fn leak(self) -> &'a mut T {
        unsafe { self.leaked }
    }

    /// Creates a new Catch from a mutable reference to T,without checking if T is in the heap.
    ///
    /// # Safety
    ///
    /// This function should only be used with data returned by the [`leak`](#method.leak) method from a safely constructed
    /// Catch or with data returned by `Box::leak(t)` otherwise this will trigger undefined behavior if the [`seal`](#method.seal)
    /// method is called.
    pub unsafe fn from_leaked(leaked: &'a mut T) -> Self {
        Catch { leaked }
    }
}

impl<'a, T: Default> Catch<'a, T> {
    /// Takes the sealed data and leaves T::default in their place,useful when you want to use the sealed
    /// value but you don't have ownership of the Catch.
    pub fn take(&mut self) -> Box<T> {
        let tmp = unsafe { ManuallyDrop::take(&mut self.sealed) };
        let ptr = self as *mut Self;
        unsafe { ptr.write( Self::new(Box::new(T::default())) ); }
        tmp
    }
}

// /// I have my doubts if implement this `Drop` which drop the sealed data but,as temporal global access does not mean neccesarily a
// /// memory leak and,many of the methods that this type implement returns or consumes the `Catch`.If you do know that your catch may
// /// be dropped,use the (leak)[#method.leak] or (seal)[#method.seal] method,depending at the need of static or owned access.
// impl<'a, T> Drop for Catch<'a, T> {
//    fn drop(&mut self) {
//        unsafe { ManuallyDrop::drop(&mut self.sealed) };
//    }
// }

/// An union slice that can be leaked or sealed(owned),useful when you want to give temporal global access
/// to a particular sequence.
#[deprecated(since = "0.2.5", note = "Catch has implementations for serve the same functionality")]
pub union CatchSeq<'a, T> {
    leaked: &'a mut [T],
    sealed: ManuallyDrop<Box<[T]>>,
}

#[allow(deprecated)]
impl<'a, T> CatchSeq<'a, T> {
    /// Creates a new CatchSeq with a leak, you can lately get the underlying sequence and consume the CatchSeq
    /// with the [`seal`](#method.seal) method.
    pub fn new(a: Vec<T>) -> Self {
        CatchSeq {
            leaked: Vec::leak(a),
        }
    }

    /// Returns a a reference to the leaked field,as the only safe ways for construct this union returns a leaked
    /// one,for warranty never transmute stack to heap data,this method does not use transmute implicitly.
    pub fn leaked(&self) -> &&'a mut [T] {
        unsafe { &self.leaked }
    }

    /// Consumes the Catch and gets the inner Vec<T>, preventing the memory leak.
    ///
    /// This does a call to transmute but,as the only safe ways for construct this union returns a leaked
    /// one,this never trigger undefined behavior by itself.
    pub fn seal(self) -> Vec<T> {
        unsafe { ManuallyDrop::into_inner(self.sealed).into_vec() }
    }
    /// Consumes the CatchSeq and returns a mutable reference pointing to leaked data.
    pub fn leak(self) -> &'a mut [T] {
        unsafe { self.leaked }
    }

    /// Creates a new CatchSeq from a `&mut [T]`,without checking if the referent is in the heap.
    ///
    /// # Safety
    ///
    /// This function should only be used with data returned by the [`leak`](#method.leak) method from a safely constructed
    /// CatchSeq or with data returned by `Vec::leak` otherwise this will trigger undefined behavior
    /// if the [`seal`](#method.seal) method is called.
    pub unsafe fn from_leaked(leaked: &'a mut [T]) -> Self {
        CatchSeq { leaked }
    }
}

/// An union string that can be leaked or sealed(owned),useful when you want to give temporal global access
/// to a particular string.
#[deprecated(since = "0.2.5", note = "Catch has implementations for serve the same functionality")]
pub union CatchStr<'a> {
    leaked: &'a mut str,
    sealed: ManuallyDrop<Box<str>>,
}

#[allow(deprecated)]
impl<'a> CatchStr<'a> {
    /// Creates a new CatchStr with a leak, you can lately get the underlying string and consume the CatchStr
    /// with the [`seal`](#method.seal) method.
    pub fn new(a: String) -> Self {
        CatchStr {
            leaked: Box::leak(a.into_boxed_str()),
        }
    }

    /// Returns a a reference to the leaked field,as the only safe ways for construct this union returns a leaked
    /// one,for warranty never transmute stack to heap data,this method does not use transmute implicitly.
    pub fn leaked(&self) -> &&'a mut str {
        unsafe { &self.leaked }
    }

    /// Consumes the Catch and gets the inner String, preventing the memory leak.
    ///
    /// This does a call to transmute but,as the only safe ways for construct this union return a leaked
    /// one,this never trigger undefined behavior by itself.
    pub fn seal(self) -> String {
        unsafe { ManuallyDrop::into_inner(self.sealed).into_string() }
    }

    /// Consumes the CatchStr and returns a mutable reference pointing to leaked data.
    pub fn leak(self) -> &'a mut str {
        unsafe { self.leaked }
    }

    /// Creates a new CatchStr from a `&mut str`,without checking if the referent is in the heap.
    ///
    /// # Safety
    ///
    /// This function should only be used with data returned by the [`leak`](#method.leak) method from a safely constructed
    /// CatchStr or with data returned by `Box::leak(string.into_boxed_str())` otherwise this will trigger undefined behavior
    /// if the [`seal`](#method.seal) method is called.
    pub unsafe fn from_leaked(leaked: &'a mut str) -> Self {
        CatchStr { leaked }
    }
}

/// A wrapper for an implementation of drop that [`mem::take`] the value and [`mem::forget`]s it.
///
/// This might be useful if you want assuring that a particular destructor not run if it can lead to
/// a double-free or another memory issue.
///
/// This type is particularly not recomended for reference types because as such they can never be null
/// and the value is still dropped. Neither on types with a costly initialization because it replaces the
/// forgotten value with the `Default` one,these values should not implement it anyways.
///
/// This type has the same implications that forget except for the fact that this ensures that the value
/// is never dropped even on panic,unless you abort.In general [`DontDropOpt`](./struct.DontDropOpt.html) is preferred.
///
/// It derefs to T.
///
/// [`mem::take`]: https://doc.rust-lang.org/core/mem/fn.take.html
/// [`mem::forget`]: https://doc.rust-lang.org/core/mem/fn.forget.html
#[deprecated(since = "0.2.4", note = "Use ManuallyDrop or DontDropOpt if you want to take the value and reuse the container,instead.")]
#[repr(transparent)]
pub struct DontDrop<T: Default>(pub T);

#[allow(deprecated)]
impl<T: Default> DontDrop<T> {
    /// Returns the field,allowing it to be dropped again.
    pub fn into_inner(&mut self) -> T {
        take(&mut self.0)
    }
}

#[allow(deprecated)]
impl<T: Default> Deref for DontDrop<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[allow(deprecated)]
impl<T: Default> DerefMut for DontDrop<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[allow(deprecated)]
impl<T: Default> Drop for DontDrop<T> {
    fn drop(&mut self) {
        forget(take(&mut self.0));
    }
}

/// A wrapper for an implementation of drop that [`mem::forget`] the previous value and replace it with None.
///
/// This might be useful if you want assuring that a particular destructor not run if it can lead to
/// a double-free or another memory issue.
///
/// This type is particularly not recomended for reference types because as such they can never be null
/// and the value is still dropped.
///
/// This type has the same implications that [`mem::forget`] except for the fact that this ensures that the
/// value is never dropped even on panic,unless you abort.
///
/// It derefs to Option<T>.
/// 
/// [`mem::forget`]: https://doc.rust-lang.org/core/mem/fn.forget.html
#[repr(transparent)]
#[new_type]
pub struct DontDropOpt<T>(Option<T>);

impl<T> DontDropOpt<T> {
    /// Construct a new `DontDropOpt` from a value,this has no effect if the value is a reference.
    pub fn new(a: T) -> Self {
        DontDropOpt(Some(a))
    }

    /// Returns the value,allowing it to be dropped again.
    pub fn into_inner(&mut self) -> Option<T> {
        self.0.take()
    }

    /// Takes the value away from the Option\<T\> and forgets it,preventing further access and allowing
    /// the container to be re-used.
    pub fn forget(&mut self) {
        forget((&mut self.0).take())
    }

    /// Convenience function for `self.0 = Some(**value**)`.
    pub fn set(&mut self, value: T) {
        self.0 = Some(value)
    }

    /// Unwraps the Option<T>,allowing it to be dropped again.
    /// 
    /// # Safety
    /// 
    /// This will panic if the type contained is None with debug_assertions enabled,otherwise triggers UB.
    pub unsafe fn into_inner_unchecked(&mut self) -> T {
        self.0.take().unwrap_or_else(|| unreachable_debug!("Called into_inner_unchecked with None value on DontDropOpt in debug."))
    } 
}

impl<T> Drop for DontDropOpt<T> {
    fn drop(&mut self) {
        self.forget()
    }
}

/// A wrapper that calls the given closure at Drop. Useful when you have a conditional assign of one
/// that,once assigned,you want to warranty a call to it with the given T,and then drop it.
/// 
/// Currently this type has a value field of an `Option<T>`,because the closure needs to take ownership
/// doing use of the [take](https://doc.rust-lang.org/std/option/enum.Option.html#method.take) method on
/// `Option`.In case of `None` because there's no meaningful value for the closure,drop returns at that point.
///
/// It derefs to Option<T>.
#[new_type]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct DropBy<T, F: FnMut(T)> {
    pub value: Option<T>,
    pub clos: F
}

impl<T, F: FnMut(T)> DropBy<T, F> {
    /// Creates a new `DropBy` with the value and the closure that takes the value at their `Drop` impl.
    pub const fn new(value: T, clos: F) -> Self {
        let value = Some(value);
        DropBy { value, clos }
    }

    /// Takes the value,disabling any code in the closure.
    pub fn into_inner(&mut self) -> Option<T> {
        self.value.take()
    }

    /// This function takes the value and calls the closure with it,allowing re-use the container.
    /// 
    /// This struct implements [`Drop`] so the name can conflict with they method,other way will be called
    /// "drop".
    /// 
    /// [`Drop`]: #impl-Drop
    pub fn drop_by(&mut self) {
        let value = match self.value.take() {
            Some(a) => a,
            None => return,
        };

        (self.clos)(value)
    }

    /// Convenience function for `self.value = Some(some_value)`.
    pub fn set(&mut self, value: T) {
        self.value = Some(value)
    }

    /// Takes and unwraps the value,disabling any code in the closure.
    /// 
    /// # Safety
    /// 
    /// This will panic if the type contained is `None` with debug_assertions enabled,otherwise triggers UB.
    pub unsafe fn into_inner_unchecked(&mut self) -> T {
        self.value.take().unwrap_or_else(|| unreachable_debug!("Called into_inner_unchecked with None value on DropBy in debug."))
    } 
}

impl<T, F: FnMut(T)> Drop for DropBy<T, F> {
    fn drop(&mut self) {
        self.drop_by()
    }
}

/// An enum that can be all sorts of Catch's over T,useful when you do not known if you gonna have a Box,Vec or String and you want to
/// grant static temporal access to any of them safely.
#[deprecated(since = "0.2.5", note = "Catch has implementations for serve the same functionality of the other variants")]
pub enum CatchT<'a, T> {
    Catch(Catch<'a, T>),
    #[allow(deprecated)]
    CatchSeq(CatchSeq<'a, T>),
    #[allow(deprecated)]
    CatchStr(CatchStr<'a>),
}

/// A lazy-iniatialiazed cache for a Fn closure with a constant constructor.
pub struct LazyCache<P: Ord, V: Clone, C: Fn(P) -> V> {
    cache: MaybeUninit<BTreeMap<P, V>>,
    pub closure: C,
    init: bool
}

impl<P: Ord + Clone, V: Clone, C: Fn(P) -> V> LazyCache<P, V, C> {
    /// Construct a cache for a closure that is initialized in the first call to [call_cache](#method.call_cache).
    /// 
    /// This is particularly useful for fn pointers of recurrently used functions because it can be used
    /// on statics,althought you need make them mutable for actually call [call_cache](#method.call_cache).
    pub const fn new(closure: C) -> Self {
        Self {cache: MaybeUninit::uninit(), closure, init: false}
    }

    /// Construct a cache for a closure providing an iniatialized cache.
    pub const fn with_cache(cache: BTreeMap<P, V>, closure: C) -> Self {
        Self {cache: MaybeUninit::new(cache), closure, init: true }
    }

    /// Cosntruct a cache for a closure providing a maybe unininitialized one along with the init state.
    /// 
    /// If you do know that `init` is true the [`with_cache`](#method.with_cache) is preferred.
    ///  
    /// # Safety
    /// 
    /// This function is unsafe due to being unable to prove that the init value is correct and `true`
    /// only for initialiazed caches. 
    /// 
    /// Considering that a bad use can lead to try to read or destruct uninitializated memory the
    /// use of this function is discouraged and it only exist to give flexibility while maintaining the
    /// fields private.
    pub const unsafe fn with_cache_unchecked(cache: MaybeUninit<BTreeMap<P, V>>, closure: C, init: bool) -> Self {
        Self {cache, closure, init}
    }
    
    fn init(&mut self) {
        unsafe {
            self.cache.as_mut_ptr().write(BTreeMap::new());
            self.init = true;
        }
    }

    /// Calls the inner closure with the given arg,after initializing the cache if it did not before.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use high_mem_utils::LazyCache;
    /// 
    /// fn foo(num: u32) -> u32 {
    ///     num
    /// }
    /// 
    /// let mut cache = LazyCache::new(foo);
    /// 
    /// assert_eq!(cache.call_cache(2), 2);
    /// assert_eq!(cache.call_cache(2), 2);
    /// assert_eq!(cache.call_cache(4), 4);
    /// ```
    pub fn call_cache(&mut self, arg: P) -> V {
    
        if !self.init {
            self.init();
        }

        let mut_ref = unsafe { &mut *self.cache.as_mut_ptr() };
    
        if mut_ref.contains_key(&arg) {
            (mut_ref.get(&arg).unwrap()).clone()
        } else {
            let temp = (self.closure)(arg.clone());
            mut_ref.insert(arg, temp.clone());
            temp
        }
    }

    /// This method removes an argument from the cache and returns the value or None if there's no one
    /// or the cache is uninitialized.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use high_mem_utils::LazyCache;
    /// 
    /// fn foo(num: u32) -> u32 {
    ///     num
    /// }
    /// 
    /// let mut cache = LazyCache::new(foo);
    /// 
    /// assert_eq!(cache.call_cache(2), 2);
    /// assert_eq!(cache.pop(&2), Some(2));
    /// assert_eq!(cache.pop(&2), None);
    /// ```
    pub fn pop(&mut self, arg: &P) -> Option<V> {
        if !self.init { 
            return None;
        }

        (unsafe { &mut *self.cache.as_mut_ptr() }).remove(arg)
    }

    /// Clears the cache,removing all their values.This is no-op if the cache is not initialized.
    pub fn clear(&mut self) {
        if !self.init {
            return;
        }

        (unsafe { &mut *self.cache.as_mut_ptr() }).clear();
    }

    /// Returns true if the cache is initialized,not neccesarily filled with an argument. Use \![is_empty](#method.is_empty)
    /// for that purpose.
    pub fn is_init(&self) -> bool {
        self.init
    }

    /// Returns true if the cache has no arguments or if it's not initialized.
    pub fn is_empty(&self) -> bool {
        if self.init {
            (unsafe { &*self.cache.as_ptr() }).is_empty()
        } else {
            true
        }
    }

    /// This method calls a closure that receives a mutable reference to the cache,allowing using methods provided by `BTreeMap`.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use high_mem_utils::LazyCache;
    /// 
    /// let mut cache = LazyCache::new(|x| x);
    /// 
    /// cache.cache(|c| {c.insert(2, 2);});
    /// assert_eq!(cache.pop(&2), Some(2));
    /// assert_eq!(cache.call_cache(2), 2);
    /// assert_eq!(cache.pop(&2), Some(2));
    /// assert_eq!(cache.pop(&2), None);
    /// ```
    pub fn cache<F: Fn(&mut BTreeMap<P, V>)>(&mut self, f: F) {
        if !self.init {
            self.init();
        }

        unsafe {
            f(&mut *self.cache.as_mut_ptr());
        }
    }
}

/// This impl drops the cache only if it's initialiazed.
impl<P: Ord, V: Clone, C: Fn(P) -> V> Drop for LazyCache<P, V, C> {
    fn drop(&mut self) {
        if self.init { 
            unsafe { self.cache.as_mut_ptr().drop_in_place() }
        }
    }   
}