wasmer_runtime_core_fl/memory/
view.rs

1use crate::types::ValueType;
2
3use std::sync::atomic::{
4    AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicU16, AtomicU32, AtomicU64, AtomicU8,
5};
6use std::{cell::Cell, marker::PhantomData, ops::Deref, slice};
7
8pub trait Atomic {
9    type Output;
10}
11impl Atomic for i8 {
12    type Output = AtomicI8;
13}
14impl Atomic for i16 {
15    type Output = AtomicI16;
16}
17impl Atomic for i32 {
18    type Output = AtomicI32;
19}
20impl Atomic for i64 {
21    type Output = AtomicI64;
22}
23impl Atomic for u8 {
24    type Output = AtomicU8;
25}
26impl Atomic for u16 {
27    type Output = AtomicU16;
28}
29impl Atomic for u32 {
30    type Output = AtomicU32;
31}
32impl Atomic for u64 {
33    type Output = AtomicU64;
34}
35impl Atomic for f32 {
36    type Output = AtomicU32;
37}
38impl Atomic for f64 {
39    type Output = AtomicU64;
40}
41
42/// A trait that represants an atomic type.
43pub trait Atomicity {}
44/// Atomically.
45pub struct Atomically;
46impl Atomicity for Atomically {}
47/// Non-atomically.
48pub struct NonAtomically;
49impl Atomicity for NonAtomically {}
50
51/// A view into a memory.
52pub struct MemoryView<'a, T: 'a, A = NonAtomically> {
53    ptr: *mut T,
54    length: usize,
55    _phantom: PhantomData<(&'a [Cell<T>], A)>,
56}
57
58impl<'a, T> MemoryView<'a, T, NonAtomically>
59where
60    T: ValueType,
61{
62    /// Creates new memory view from raw parts.
63    pub unsafe fn new(ptr: *mut T, length: u32) -> Self {
64        Self {
65            ptr,
66            length: length as usize,
67            _phantom: PhantomData,
68        }
69    }
70}
71
72impl<'a, T: Atomic> MemoryView<'a, T> {
73    /// Get atomic access to a memory view.
74    pub fn atomically(&self) -> MemoryView<'a, T::Output, Atomically> {
75        MemoryView {
76            ptr: self.ptr as *mut T::Output,
77            length: self.length,
78            _phantom: PhantomData,
79        }
80    }
81}
82
83impl<'a, T> Deref for MemoryView<'a, T, NonAtomically> {
84    type Target = [Cell<T>];
85    fn deref(&self) -> &[Cell<T>] {
86        let mut_slice: &mut [T] = unsafe { slice::from_raw_parts_mut(self.ptr, self.length) };
87        let cell_slice: &Cell<[T]> = Cell::from_mut(mut_slice);
88        cell_slice.as_slice_of_cells()
89    }
90}
91
92impl<'a, T> Deref for MemoryView<'a, T, Atomically> {
93    type Target = [T];
94    fn deref(&self) -> &[T] {
95        unsafe { slice::from_raw_parts(self.ptr as *const T, self.length) }
96    }
97}