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
#![warn(missing_docs)]

//! This crate provides the `ProcessOwned` type, a value
//! that shares its lifetime with the process *unless* it
//! can be optimally freed earlier than that.
//! 
//! Internally, `ProcessOwned` uses the `Rc` type to
//! ensure that the value is only dropped when the last
//! owner is dropped. The specific implementation is
//! subject to change for performance reasons.

use std::{
    rc::Rc,
    ops::{Deref, DerefMut}
};

/// A value that is owned by the process itself.
/// 
/// The lifetime of a value is tied to its owner. When the
/// owner is dropped, the value is dropped as well. This
/// object uses the `Rc` type internally to ensure that
/// the value is only dropped when the last owner is dropped.
/// The specific implementation is subject to change for
/// performance reasons.
/// 
/// When a `ProcessOwned` is initialized as a global static
/// variable with the `lazy_static` crate, it will never be
/// dropped. This allows values to easily and clearly share
/// the scope of the entire process.
#[derive(Clone, Debug)]
pub struct ProcessOwned<T> {
    value: Rc<T>
}

impl<T> ProcessOwned<T> {
    /// Create a new `ProcessOwned` value.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use process_owned::ProcessOwned;
    /// 
    /// let value = ProcessOwned::new(5);
    /// assert_eq!(*value, 5);
    /// ```
    pub fn new(value: T) -> Self {
        ProcessOwned {
            value: Rc::new(value)
        }
    }
}

impl<T> Deref for ProcessOwned<T> {
    type Target = T;

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

impl<T: Clone> DerefMut for ProcessOwned<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        Rc::make_mut(&mut self.value)
    }
}