| 
 | 1 | +// Copyright 2013 The Rust Project Developers. See the COPYRIGHT  | 
 | 2 | +// file at the top-level directory of this distribution and at  | 
 | 3 | +// http://rust-lang.org/COPYRIGHT.  | 
 | 4 | +//  | 
 | 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or  | 
 | 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license  | 
 | 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your  | 
 | 8 | +// option. This file may not be copied, modified, or distributed  | 
 | 9 | +// except according to those terms.  | 
 | 10 | + | 
 | 11 | +//! A mutable memory location with dynamically checked borrow rules  | 
 | 12 | +
  | 
 | 13 | +use prelude::*;  | 
 | 14 | + | 
 | 15 | +use cast;  | 
 | 16 | +use util::NonCopyable;  | 
 | 17 | + | 
 | 18 | +/// A mutable memory location with dynamically checked borrow rules  | 
 | 19 | +#[no_freeze]  | 
 | 20 | +pub struct Mut<T> {  | 
 | 21 | +    priv value: T,  | 
 | 22 | +    priv borrow: BorrowFlag,  | 
 | 23 | +    priv nc: NonCopyable  | 
 | 24 | +}  | 
 | 25 | + | 
 | 26 | +// Values [1, MAX-1] represent the number of `Ref` active  | 
 | 27 | +// (will not outgrow its range since `uint` is the size of the address space)  | 
 | 28 | +type BorrowFlag = uint;  | 
 | 29 | +static UNUSED: BorrowFlag = 0;  | 
 | 30 | +static WRITING: BorrowFlag = -1;  | 
 | 31 | + | 
 | 32 | +impl<T> Mut<T> {  | 
 | 33 | +    /// Create a new `Mut` containing `value`  | 
 | 34 | +    pub fn new(value: T) -> Mut<T> {  | 
 | 35 | +        Mut {  | 
 | 36 | +            value: value,  | 
 | 37 | +            borrow: UNUSED,  | 
 | 38 | +            nc: NonCopyable  | 
 | 39 | +        }  | 
 | 40 | +    }  | 
 | 41 | + | 
 | 42 | +    /// Consumes the `Mut`, returning the wrapped value.  | 
 | 43 | +    pub fn unwrap(self) -> T {  | 
 | 44 | +        assert!(self.borrow == UNUSED);  | 
 | 45 | +        self.value  | 
 | 46 | +    }  | 
 | 47 | + | 
 | 48 | +    unsafe fn as_mut<'a>(&'a self) -> &'a mut Mut<T> {  | 
 | 49 | +        cast::transmute_mut(self)  | 
 | 50 | +    }  | 
 | 51 | + | 
 | 52 | +    /// Attempts to immutably borrow the wrapped value.  | 
 | 53 | +    ///  | 
 | 54 | +    /// The borrow lasts until the returned `Ref` exits scope. Multiple  | 
 | 55 | +    /// immutable borrows can be taken out at the same time.  | 
 | 56 | +    ///  | 
 | 57 | +    /// Returns `None` if the value is currently mutably borrowed.  | 
 | 58 | +    pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> {  | 
 | 59 | +        match self.borrow {  | 
 | 60 | +            WRITING => None,  | 
 | 61 | +            _ => {  | 
 | 62 | +                unsafe { self.as_mut().borrow += 1; }  | 
 | 63 | +                Some(Ref { parent: self })  | 
 | 64 | +            }  | 
 | 65 | +        }  | 
 | 66 | +    }  | 
 | 67 | + | 
 | 68 | +    /// Immutably borrows the wrapped value.  | 
 | 69 | +    ///  | 
 | 70 | +    /// The borrow lasts until the returned `Ref` exits scope. Multiple  | 
 | 71 | +    /// immutable borrows can be taken out at the same time.  | 
 | 72 | +    ///  | 
 | 73 | +    /// # Failure  | 
 | 74 | +    ///  | 
 | 75 | +    /// Fails if the value is currently mutably borrowed.  | 
 | 76 | +    pub fn borrow<'a>(&'a self) -> Ref<'a, T> {  | 
 | 77 | +        match self.try_borrow() {  | 
 | 78 | +            Some(ptr) => ptr,  | 
 | 79 | +            None => fail!("Mut<T> already mutably borrowed")  | 
 | 80 | +        }  | 
 | 81 | +    }  | 
 | 82 | + | 
 | 83 | +    /// Mutably borrows the wrapped value.  | 
 | 84 | +    ///  | 
 | 85 | +    /// The borrow lasts untile the returned `MutRef` exits scope. The value  | 
 | 86 | +    /// cannot be borrowed while this borrow is active.  | 
 | 87 | +    ///  | 
 | 88 | +    /// Returns `None` if the value is currently borrowed.  | 
 | 89 | +    pub fn try_borrow_mut<'a>(&'a self) -> Option<MutRef<'a, T>> {  | 
 | 90 | +        match self.borrow {  | 
 | 91 | +            UNUSED => unsafe {  | 
 | 92 | +                let mut_self = self.as_mut();  | 
 | 93 | +                mut_self.borrow = WRITING;  | 
 | 94 | +                Some(MutRef { parent: mut_self })  | 
 | 95 | +            },  | 
 | 96 | +            _ => None  | 
 | 97 | +        }  | 
 | 98 | +    }  | 
 | 99 | + | 
 | 100 | +    /// Mutably borrows the wrapped value.  | 
 | 101 | +    ///  | 
 | 102 | +    /// The borrow lasts untile the returned `MutRef` exits scope. The value  | 
 | 103 | +    /// cannot be borrowed while this borrow is active.  | 
 | 104 | +    ///  | 
 | 105 | +    /// # Failure  | 
 | 106 | +    ///  | 
 | 107 | +    /// Fails if the value is currently borrowed.  | 
 | 108 | +    pub fn borrow_mut<'a>(&'a self) -> MutRef<'a, T> {  | 
 | 109 | +        match self.try_borrow_mut() {  | 
 | 110 | +            Some(ptr) => ptr,  | 
 | 111 | +            None => fail!("Mut<T> already borrowed")  | 
 | 112 | +        }  | 
 | 113 | +    }  | 
 | 114 | + | 
 | 115 | +    /// Immutably borrows the wrapped value and applies `blk` to it.  | 
 | 116 | +    ///  | 
 | 117 | +    /// # Failure  | 
 | 118 | +    ///  | 
 | 119 | +    /// Fails if the value is currently mutably borrowed.  | 
 | 120 | +    #[inline]  | 
 | 121 | +    pub fn map<U>(&self, blk: |&T| -> U) -> U {  | 
 | 122 | +        let ptr = self.borrow();  | 
 | 123 | +        blk(ptr.get())  | 
 | 124 | +    }  | 
 | 125 | + | 
 | 126 | +    /// Mutably borrows the wrapped value and applies `blk` to it.  | 
 | 127 | +    ///  | 
 | 128 | +    /// # Failure  | 
 | 129 | +    ///  | 
 | 130 | +    /// Fails if the value is currently borrowed.  | 
 | 131 | +    #[inline]  | 
 | 132 | +    pub fn map_mut<U>(&self, blk: |&mut T| -> U) -> U {  | 
 | 133 | +        let mut ptr = self.borrow_mut();  | 
 | 134 | +        blk(ptr.get())  | 
 | 135 | +    }  | 
 | 136 | +}  | 
 | 137 | + | 
 | 138 | +impl<T: Clone> Clone for Mut<T> {  | 
 | 139 | +    fn clone(&self) -> Mut<T> {  | 
 | 140 | +        let x = self.borrow();  | 
 | 141 | +        Mut::new(x.get().clone())  | 
 | 142 | +    }  | 
 | 143 | +}  | 
 | 144 | + | 
 | 145 | +impl<T: DeepClone> DeepClone for Mut<T> {  | 
 | 146 | +    fn deep_clone(&self) -> Mut<T> {  | 
 | 147 | +        let x = self.borrow();  | 
 | 148 | +        Mut::new(x.get().deep_clone())  | 
 | 149 | +    }  | 
 | 150 | +}  | 
 | 151 | + | 
 | 152 | +impl<T: Eq> Eq for Mut<T> {  | 
 | 153 | +    fn eq(&self, other: &Mut<T>) -> bool {  | 
 | 154 | +        let a = self.borrow();  | 
 | 155 | +        let b = other.borrow();  | 
 | 156 | +        a.get() == b.get()  | 
 | 157 | +    }  | 
 | 158 | +}  | 
 | 159 | + | 
 | 160 | +/// Wraps a borrowed reference to a value in a `Mut` box.  | 
 | 161 | +pub struct Ref<'box, T> {  | 
 | 162 | +    priv parent: &'box Mut<T>  | 
 | 163 | +}  | 
 | 164 | + | 
 | 165 | +#[unsafe_destructor]  | 
 | 166 | +impl<'box, T> Drop for Ref<'box, T> {  | 
 | 167 | +    fn drop(&mut self) {  | 
 | 168 | +        assert!(self.parent.borrow != WRITING && self.parent.borrow != UNUSED);  | 
 | 169 | +        unsafe { self.parent.as_mut().borrow -= 1; }  | 
 | 170 | +    }  | 
 | 171 | +}  | 
 | 172 | + | 
 | 173 | +impl<'box, T> Ref<'box, T> {  | 
 | 174 | +    /// Retrieve an immutable reference to the stored value.  | 
 | 175 | +    #[inline]  | 
 | 176 | +    pub fn get<'a>(&'a self) -> &'a T {  | 
 | 177 | +        &self.parent.value  | 
 | 178 | +    }  | 
 | 179 | +}  | 
 | 180 | + | 
 | 181 | +/// Wraps a mutable borrowed reference to a value in a `Mut` box.  | 
 | 182 | +pub struct MutRef<'box, T> {  | 
 | 183 | +    priv parent: &'box mut Mut<T>  | 
 | 184 | +}  | 
 | 185 | + | 
 | 186 | +#[unsafe_destructor]  | 
 | 187 | +impl<'box, T> Drop for MutRef<'box, T> {  | 
 | 188 | +    fn drop(&mut self) {  | 
 | 189 | +        assert!(self.parent.borrow == WRITING);  | 
 | 190 | +        unsafe { self.parent.as_mut().borrow = UNUSED; }  | 
 | 191 | +    }  | 
 | 192 | +}  | 
 | 193 | + | 
 | 194 | +impl<'box, T> MutRef<'box, T> {  | 
 | 195 | +    /// Retrieve a mutable reference to the stored value.  | 
 | 196 | +    #[inline]  | 
 | 197 | +    pub fn get<'a>(&'a mut self) -> &'a mut T {  | 
 | 198 | +        &mut self.parent.value  | 
 | 199 | +    }  | 
 | 200 | +}  | 
 | 201 | + | 
 | 202 | +#[cfg(test)]  | 
 | 203 | +mod test {  | 
 | 204 | +    use super::*;  | 
 | 205 | + | 
 | 206 | +    #[test]  | 
 | 207 | +    fn double_imm_borrow() {  | 
 | 208 | +        let x = Mut::new(0);  | 
 | 209 | +        let _b1 = x.borrow();  | 
 | 210 | +        x.borrow();  | 
 | 211 | +    }  | 
 | 212 | + | 
 | 213 | +    #[test]  | 
 | 214 | +    fn no_mut_then_imm_borrow() {  | 
 | 215 | +        let x = Mut::new(0);  | 
 | 216 | +        let _b1 = x.borrow_mut();  | 
 | 217 | +        assert!(x.try_borrow().is_none());  | 
 | 218 | +    }  | 
 | 219 | + | 
 | 220 | +    #[test]  | 
 | 221 | +    fn no_imm_then_borrow_mut() {  | 
 | 222 | +        let x = Mut::new(0);  | 
 | 223 | +        let _b1 = x.borrow();  | 
 | 224 | +        assert!(x.try_borrow_mut().is_none());  | 
 | 225 | +    }  | 
 | 226 | + | 
 | 227 | +    #[test]  | 
 | 228 | +    fn no_double_borrow_mut() {  | 
 | 229 | +        let x = Mut::new(0);  | 
 | 230 | +        let _b1 = x.borrow_mut();  | 
 | 231 | +        assert!(x.try_borrow_mut().is_none());  | 
 | 232 | +    }  | 
 | 233 | + | 
 | 234 | +    #[test]  | 
 | 235 | +    fn imm_release_borrow_mut() {  | 
 | 236 | +        let x = Mut::new(0);  | 
 | 237 | +        {  | 
 | 238 | +            let _b1 = x.borrow();  | 
 | 239 | +        }  | 
 | 240 | +        x.borrow_mut();  | 
 | 241 | +    }  | 
 | 242 | + | 
 | 243 | +    #[test]  | 
 | 244 | +    fn mut_release_borrow_mut() {  | 
 | 245 | +        let x = Mut::new(0);  | 
 | 246 | +        {  | 
 | 247 | +            let _b1 = x.borrow_mut();  | 
 | 248 | +        }  | 
 | 249 | +        x.borrow();  | 
 | 250 | +    }  | 
 | 251 | + | 
 | 252 | +    #[test]  | 
 | 253 | +    fn double_borrow_single_release_no_borrow_mut() {  | 
 | 254 | +        let x = Mut::new(0);  | 
 | 255 | +        let _b1 = x.borrow();  | 
 | 256 | +        {  | 
 | 257 | +            let _b2 = x.borrow();  | 
 | 258 | +        }  | 
 | 259 | +        assert!(x.try_borrow_mut().is_none());  | 
 | 260 | +    }  | 
 | 261 | + | 
 | 262 | +    #[test]  | 
 | 263 | +    fn map_ok() {  | 
 | 264 | +        let x = Mut::new(0);  | 
 | 265 | +        assert_eq!(1, x.map(|x| *x+1));  | 
 | 266 | +    }  | 
 | 267 | + | 
 | 268 | +    #[test]  | 
 | 269 | +    #[should_fail]  | 
 | 270 | +    fn mut_borrow_map() {  | 
 | 271 | +        let x = Mut::new(0);  | 
 | 272 | +        let _b1 = x.borrow_mut();  | 
 | 273 | +        x.map(|x| *x+1);  | 
 | 274 | +    }  | 
 | 275 | + | 
 | 276 | +    #[test]  | 
 | 277 | +    fn borrow_map() {  | 
 | 278 | +        let x = Mut::new(0);  | 
 | 279 | +        let _b1 = x.borrow();  | 
 | 280 | +        assert_eq!(1, x.map(|x| *x+1));  | 
 | 281 | +    }  | 
 | 282 | + | 
 | 283 | +    #[test]  | 
 | 284 | +    fn map_mut_ok() {  | 
 | 285 | +        let x = Mut::new(0);  | 
 | 286 | +        x.map_mut(|x| *x += 1);  | 
 | 287 | +        let b = x.borrow();  | 
 | 288 | +        assert_eq!(1, *b.get());  | 
 | 289 | +    }  | 
 | 290 | + | 
 | 291 | +    #[test]  | 
 | 292 | +    #[should_fail]  | 
 | 293 | +    fn borrow_map_mut() {  | 
 | 294 | +        let x = Mut::new(0);  | 
 | 295 | +        let _b = x.borrow();  | 
 | 296 | +        x.map_mut(|x| *x += 1);  | 
 | 297 | +    }  | 
 | 298 | +}  | 
0 commit comments