(index<- ) ./librustuv/rc.rs
git branch: * master 5200215 auto merge of #14035 : alexcrichton/rust/experimental, r=huonw
modified: Wed Apr 9 17:27:02 2014
1 // Copyright 2014 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 /// Simple refcount structure for cloning handles
12 ///
13 /// This is meant to be an unintrusive solution to cloning handles in rustuv.
14 /// The handles themselves shouldn't be sharing memory because there are bits of
15 /// state in the rust objects which shouldn't be shared across multiple users of
16 /// the same underlying uv object, hence Rc is not used and this simple counter
17 /// should suffice.
18
19 use std::sync::arc::UnsafeArc;
20
21 pub struct Refcount {
22 rc: UnsafeArc<uint>,
23 }
24
25 impl Refcount {
26 /// Creates a new refcount of 1
27 pub fn new() -> Refcount {
28 Refcount { rc: UnsafeArc::new(1) }
29 }
30
31 fn increment(&self) {
32 unsafe { *self.rc.get() += 1; }
33 }
34
35 /// Returns whether the refcount just hit 0 or not
36 pub fn decrement(&self) -> bool {
37 unsafe {
38 *self.rc.get() -= 1;
39 *self.rc.get() == 0
40 }
41 }
42 }
43
44 impl Clone for Refcount {
45 fn clone(&self) -> Refcount {
46 self.increment();
47 Refcount { rc: self.rc.clone() }
48 }
49 }