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
use std::cell::RefCell;

/**
A structure containing a single value that can be moved out imutably.
This can be used if you want a structure to be able to own something that will eventaly be moved, but you want your structure to keep existing.
*/
pub struct Movable<T>(RefCell<Vec<T>>);

impl<T> Movable<T>
{
    /// Creates a new Movable, initialized with the given value.
    pub fn new(content: T) -> Self
    {
	Self(RefCell::new(vec![content]))
    }
    /**
    Moves the internal value, emptying the Movable
    Panics if the Movable has been moved.
     */
    pub fn consume(&self) -> T
    {
	if self.has_moved()
	{
	    panic!("Movable already consumed!")
	}
	else
	{
	    self.0.borrow_mut().pop().unwrap()
	}
    }

    /**
    Returns true if the Movable's internal value has been moved out.
     */
    pub fn has_moved(&self) -> bool
    {
	self.0.borrow().len() == 0	
    }

    /**
    Applies the given closure to the internal content of the Movable.
    Panics if the Movable has been moved.
    The type U shouldn't contain any reference to the internal value unless you know what you do.
     */
    pub fn use_to<U, F>(&self, f: F) -> U
    where
	F: Fn(&T) -> U
    {
	if self.has_moved()
	{
	    panic!("Movable already consumed!")
	}
	else
	{
	    f(self.0.borrow()
	      .get(0).unwrap())
	}
    }

    /**
    Replaces the contained value by a new one.
    If the previous value has been moved out, the movable now contain a new value.
     */
    pub fn insert(&self, new: T)
    {
	if self.has_moved()
	{
	    self.0.borrow_mut().push(new);
	}
	else
	{
	    self.0.borrow_mut()[0] = new;
	}
    }

    /**
    Replaces the internal value by the result of the given closure.
    The internal value is being moved by doing so.
     */
    pub fn update_move<F>(&self, f: F)
    where
	F: Fn(T) -> T
    {
	if self.has_moved()
	{
	    panic!("Movable already consumed!")
	}
	else
	{
	    let v = self.consume();
	    self.insert(f(v));
	}
    }

    
}



use std::fmt::{Error, Formatter, Debug};
impl<T: Debug> Debug for Movable<T>
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
    {
        if self.has_moved()
        {
            write!(f, "Movable(#MOVED#)")
        }
        else
        {
            write!(f, "Movable({:?})",
                   self.0.borrow().get(0).unwrap())
        }
    }
}