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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::SharedAddressRange;
use crate::SharedBox;
use crate::SharedMemRef;
use crate::Volatile;
use log::debug;
use shared_memory::SharedMemCast;
use std::convert::From;
use std::convert::TryFrom;
use std::mem;
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

/// An reference counted pointer into shared memory.
pub struct SharedRc<T: SharedMemCast>(ManuallyDrop<SharedBox<SharedRcContents<T>>>);

// This is repr(C) to ensure that the data is placed at the beginning
#[repr(C)]
pub(crate) struct SharedRcContents<T: SharedMemCast> {
    data: Volatile<T>,
    ref_count: AtomicUsize,
}

impl<T: SharedMemCast> SharedRc<T> {
    pub fn try_new(data: T) -> Option<SharedRc<T>> {
        let ref_count = AtomicUsize::new(1);
        let data = Volatile::new(data);
        let contents = SharedRcContents { ref_count, data };
        let boxed = SharedBox::try_new(contents)?;
        debug!("Using box as Rc");
        Some(SharedRc(ManuallyDrop::new(boxed)))
    }

    pub fn new(data: T) -> SharedRc<T> {
        SharedRc::try_new(data).expect("Failed to allocate shared Rc")
    }

    pub fn address(this: &Self) -> SharedAddressRange {
        this.0.address()
    }

    pub fn count(this: &Self) -> usize {
        this.0.ref_count.load(Ordering::SeqCst)
    }
}

impl<T: SharedMemCast> TryFrom<SharedAddressRange> for SharedRc<T> {
    type Error = ();
    fn try_from(address: SharedAddressRange) -> Result<SharedRc<T>, ()> {
        Ok(SharedRc(ManuallyDrop::new(SharedBox::try_from(address)?)))
    }
}

impl<T: SharedMemCast> From<SharedRc<T>> for SharedAddressRange {
    fn from(rc: SharedRc<T>) -> SharedAddressRange {
        let address = rc.0.address();
        mem::forget(rc);
        address
    }
}

impl<T: SharedMemCast + SharedMemRef> Deref for SharedRc<T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.0.data.deref()
    }
}

impl<T: SharedMemCast> Clone for SharedRc<T> {
    fn clone(&self) -> Self {
        self.0.ref_count.fetch_add(1, Ordering::SeqCst);
        SharedRc(ManuallyDrop::new(SharedBox::unchecked_from_address(
            self.0.address(),
        )))
    }
}

impl<T: SharedMemCast> Drop for SharedRc<T> {
    fn drop(&mut self) {
        let ref_count = match self.0.try_get() {
            Some(contents) => contents.ref_count.fetch_sub(1, Ordering::SeqCst),
            None => return,
        };
        if ref_count <= 1 {
            debug!("Dropping rc");
            mem::replace(
                &mut self.0,
                ManuallyDrop::new(SharedBox::unchecked_from_address(SharedAddressRange::null())),
            );
        } else {
            debug!("Not dropping rc (refcount is now {})", ref_count - 1);
        }
    }
}

#[test]
fn test_rc() {
    let rc: SharedRc<AtomicUsize> = SharedRc::new(AtomicUsize::new(37));
    let val = rc.load(Ordering::SeqCst);
    assert_eq!(val, 37);
}