shared-data 0.0.2

A library for data structures living in shared memory.
/* 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);
}