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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//! A library of _C-slices_: slices with a stable ABI for interfacing with C.
//!
//! This library provides two types, `CSlice` and `CMutSlice`, for communicating
//! with C about Rust slices or foreign slice-like data structures. Both types
//! have a stable ABI consisting of exactly two pointer-sized words:
//!
//! ```c
//! struct {
//!     void *base;
//!     size_t len;
//! }
//! ```
//!
//! C-slices and Rust slices are interchangeable, with conversion methods in both
//! directions.
//!
//! This makes it possible to construct slices from foreign code, as well as to
//! communicate Rust slices to foreign code conveniently.

#![no_std]

use core::{ptr, slice};
use core::marker::PhantomData;
use core::ops::{Index, IndexMut};

/// An immutable slice, equivalent to `&'a T`.
///
/// A `CSlice` can be constructed from a corresponding Rust slice via the `AsCSlice` trait.
///
/// A Rust slice can be constructed from a corresponding `CSlice` via `as_ref`.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct CSlice<'a, T> {
    base: *const T,
    len: usize,
    marker: PhantomData<&'a ()>
}

impl<'a, T> CSlice<'a, T> {
    /// Create a `CSlice` from raw data.
    ///
    /// # Safety
    ///
    /// The region of memory from `base` (inclusive) to `base + len * sizeof<T>`
    /// (exclusive) must be valid for the duration of lifetime `'a`.
    pub unsafe fn new(base: *const T, len: usize) -> Self {
        assert!(base != ptr::null());
        CSlice {
            base: base,
            len: len,
            marker: PhantomData
        }
    }

    /// Produces a raw pointer to the slice's buffer.
    pub fn as_ptr(&self) -> *const T {
        self.base
    }

    /// Returns the number of elements in the slice.
    pub fn len(&self) -> usize {
        self.len
    }
}

impl<'a, T> AsRef<[T]> for CSlice<'a, T> {
    fn as_ref(&self) -> &[T] {
        unsafe {
            slice::from_raw_parts(self.base, self.len)
        }
    }
}

/// A mutable slice, equivalent to `&'a mut T`.
///
/// A `CMutSlice` can be constructed from a corresponding Rust slice via the `AsCMutSlice` trait.
///
/// A Rust slice can be constructed from a corresponding `CMutSlice` via `as_mut`.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct CMutSlice<'a, T> {
    base: *mut T,
    len: usize,
    marker: PhantomData<&'a ()>
}

impl<'a, T> CMutSlice<'a, T> {
    /// Create a `CSlice` from raw data.
    ///
    /// # Safety
    ///
    /// The region of memory from `base` (inclusive) to `base + len * sizeof<T>`
    /// (exclusive) must be valid for the duration of lifetime `'a`.
    pub unsafe fn new(base: *mut T, len: usize) -> Self {
        assert!(base != ptr::null_mut());
        CMutSlice {
            base: base,
            len: len,
            marker: PhantomData
        }
    }

    /// Produces a raw pointer to the slice's buffer.
    pub fn as_ptr(&self) -> *const T {
        self.base
    }

    /// Produces a raw pointer to the slice's buffer.
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.base
    }

    /// A cheap conversion to a Rust slice. This is slightly more general than `as_ref`.
    pub fn as_slice(&self) -> &'a [T] {
        unsafe {
            slice::from_raw_parts(self.base, self.len)
        }
    }

    /// A cheap conversion to a mutable Rust slice. This is slightly more general than `as_mut`.
    pub fn as_mut_slice(&mut self) -> &'a mut [T] {
        unsafe {
            slice::from_raw_parts_mut(self.base, self.len)
        }
    }

    /// Returns the number of elements in the slice.
    pub fn len(&self) -> usize {
        self.len
    }
}

impl<'a, T> AsRef<[T]> for CMutSlice<'a, T> {
    fn as_ref(&self) -> &[T] {
        unsafe {
            slice::from_raw_parts(self.base, self.len)
        }
    }
}

impl<'a, T> AsMut<[T]> for CMutSlice<'a, T> {
    fn as_mut(&mut self) -> &mut [T] {
        unsafe {
            slice::from_raw_parts_mut(self.base, self.len)
        }
    }
}

unsafe impl<'a, T: Sync> Sync for CSlice<'a, T> { }

unsafe impl<'a, T: Sync> Send for CSlice<'a, T> { }

unsafe impl<'a, T: Sync> Sync for CMutSlice<'a, T> { }

unsafe impl<'a, T: Send> Send for CMutSlice<'a, T> { }

impl<'a, T> Index<usize> for CSlice<'a, T> {
    type Output = T;

    fn index(&self, i: usize) -> &T {
        self.as_ref().index(i)
    }
}

impl<'a, T> Index<usize> for CMutSlice<'a, T> {
    type Output = T;

    fn index(&self, i: usize) -> &T {
        self.as_ref().index(i)
    }
}

impl<'a, T> IndexMut<usize> for CMutSlice<'a, T> {
    fn index_mut(&mut self, i: usize) -> &mut T {
        self.as_mut().index_mut(i)
    }
}

/// A cheap conversion to a `CSlice`.
pub trait AsCSlice<'a, T> {
    /// Performs the conversion.
    fn as_c_slice(&'a self) -> CSlice<'a, T>;
}

/// A cheap conversion to a `CMutSlice`.
pub trait AsCMutSlice<'a, T> {
    /// Performs the conversion.
    fn as_c_mut_slice(&'a mut self) -> CMutSlice<'a, T>;
}

impl<'a> AsCSlice<'a, u8> for str {
    fn as_c_slice(&'a self) -> CSlice<'a, u8> {
        CSlice {
            base: self.as_ptr(),
            len: self.len(),
            marker: PhantomData
        }
    }
}

impl<'a, T> AsCSlice<'a, T> for [T] {
    fn as_c_slice(&'a self) -> CSlice<'a, T> {
        CSlice {
            base: self.as_ptr(),
            len: self.len(),
            marker: PhantomData
        }
    }
}

impl<'a, T> AsCMutSlice<'a, T> for [T] {
    fn as_c_mut_slice(&'a mut self) -> CMutSlice<'a, T> {
        CMutSlice {
            base: self.as_mut_ptr(),
            len: self.len(),
            marker: PhantomData
        }
    }
}