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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/* 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::unsafe_code;
use crate::SharedAddressRange;
use crate::SharedMemRef;
use crate::ShmemAllocator;
use crate::Volatile;
use crate::ALLOCATOR;
use log::debug;
use shared_memory::SharedMemCast;
use std::marker::PhantomData;
use std::mem;
use std::ops::Deref;
use std::ptr;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

/// An owned pointer into an array of shared memory.
pub struct SharedVec<T: SharedMemCast> {
    address: SharedAddressRange,
    length: AtomicUsize,
    marker: PhantomData<T>,
}

impl<T: SharedMemCast> SharedVec<T> {
    pub(crate) fn from_iter_in<C>(collection: C, alloc: &ShmemAllocator) -> Option<SharedVec<T>>
    where
        C: IntoIterator<Item = T>,
        C::IntoIter: ExactSizeIterator,
    {
        let iter = collection.into_iter();
        let length = iter.len();
        debug!("Allocating vector of length {}", length);
        let size = mem::size_of::<T>() * length;
        let address = alloc.alloc_bytes(size)?;
        let bytes = alloc.get_bytes(address)?;
        let slice = Volatile::<T>::slice_from_volatile_bytes(bytes, length)?;
        debug!("Initializing vector");
        for (item, volatile) in iter.zip(slice) {
            volatile.write_volatile(item);
        }
        let length = AtomicUsize::new(length);
        let marker = PhantomData;
        Some(SharedVec {
            address,
            length,
            marker,
        })
    }

    pub(crate) fn as_ptr_in(&self, alloc: &ShmemAllocator) -> *mut T {
        alloc
            .get_bytes(self.address)
            .map(|bytes| bytes.as_ptr() as *mut T)
            .unwrap_or(ptr::null_mut())
    }

    pub fn try_from_iter<C>(collection: C) -> Option<SharedVec<T>>
    where
        C: IntoIterator<Item = T>,
        C::IntoIter: ExactSizeIterator,
    {
        SharedVec::from_iter_in(collection, &ALLOCATOR)
    }

    pub fn from_iter<C>(collection: C) -> SharedVec<T>
    where
        C: IntoIterator<Item = T>,
        C::IntoIter: ExactSizeIterator,
    {
        SharedVec::try_from_iter(collection).expect("Failed to allocate shared vec")
    }

    pub fn as_ptr(&self) -> *mut T {
        self.as_ptr_in(&ALLOCATOR)
    }

    pub(crate) fn get_in<'a>(&'a self, alloc: &'a ShmemAllocator) -> Option<&'a [Volatile<T>]> {
        let bytes = alloc.get_bytes(self.address)?;
        let length = self.length.load(Ordering::SeqCst);
        Volatile::slice_from_volatile_bytes(bytes, length)
    }

    pub fn try_get(&self) -> Option<&[Volatile<T>]> {
        self.get_in(&ALLOCATOR)
    }

    pub fn get(&self) -> &[Volatile<T>] {
        self.try_get().expect("Failed to deref shared vec")
    }

    pub fn address(&self) -> SharedAddressRange {
        self.address
    }

    pub fn len(&self) -> usize {
        self.length.load(Ordering::Relaxed)
    }
}

impl<T: SharedMemCast + SharedMemRef> Deref for SharedVec<T> {
    type Target = [T];
    fn deref(&self) -> &[T] {
        if let Some(volatile) = self.try_get() {
            unsafe_code::slice_from_volatile(volatile)
        } else {
            unsafe_code::slice_empty()
        }
    }
}

impl<T: SharedMemCast> Drop for SharedVec<T> {
    fn drop(&mut self) {
        // TODO
    }
}

#[test]
fn test_vector() {
    let vec = SharedVec::from_iter((0..37).map(|i| AtomicUsize::new(i + 1)));
    let mut last = 0;
    for (i, atomic) in vec.iter().enumerate() {
        let val = atomic.load(Ordering::SeqCst);
        assert_eq!(val, i + 1);
        assert_eq!(last, i);
        last = val;
    }
    assert_eq!(last, 37);
}