summaryrefslogtreecommitdiff
path: root/monoio/src/buf/slice.rs
blob: 6ff70f6dec6b51480803fadd9cfab564d468b4e5 (plain)
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
use std::ops;

use super::{IoVecBuf, IoVecBufMut};
use crate::buf::{IoBuf, IoBufMut};

/// An owned view into a contiguous sequence of bytes.
/// SliceMut implements IoBuf and IoBufMut.
///
/// This is similar to Rust slices (`&buf[..]`) but owns the underlying buffer.
/// This type is useful for performing io_uring read and write operations using
/// a subset of a buffer.
///
/// Slices are created using [`IoBuf::slice`].
///
/// # Examples
///
/// Creating a slice
///
/// ```
/// use monoio::buf::{IoBuf, IoBufMut};
///
/// let buf = b"hello world".to_vec();
/// let slice = buf.slice_mut(..5);
///
/// assert_eq!(&slice[..], b"hello");
/// ```
pub struct SliceMut<T> {
    buf: T,
    begin: usize,
    end: usize,
}

impl<T: IoBuf + IoBufMut> SliceMut<T> {
    /// Create a SliceMut from a buffer and range.
    pub fn new(mut buf: T, begin: usize, end: usize) -> Self {
        assert!(end <= buf.bytes_total());
        assert!(begin <= buf.bytes_init());
        assert!(begin <= end);
        Self { buf, begin, end }
    }
}

impl<T> SliceMut<T> {
    /// Create a SliceMut from a buffer and range without boundary checking.
    ///
    /// # Safety
    /// begin must be initialized, and end must be within the buffer capacity.
    #[inline]
    pub unsafe fn new_unchecked(buf: T, begin: usize, end: usize) -> Self {
        Self { buf, begin, end }
    }

    /// Offset in the underlying buffer at which this slice starts.
    ///
    /// # Examples
    ///
    /// ```
    /// use monoio::buf::IoBuf;
    ///
    /// let buf = b"hello world".to_vec();
    /// let slice = buf.slice(1..5);
    ///
    /// assert_eq!(1, slice.begin());
    /// ```
    #[inline]
    pub fn begin(&self) -> usize {
        self.begin
    }

    /// Offset in the underlying buffer at which this slice ends.
    ///
    /// # Examples
    ///
    /// ```
    /// use monoio::buf::IoBuf;
    ///
    /// let buf = b"hello world".to_vec();
    /// let slice = buf.slice(1..5);
    ///
    /// assert_eq!(5, slice.end());
    /// ```
    #[inline]
    pub fn end(&self) -> usize {
        self.end
    }

    /// Gets a reference to the underlying buffer.
    ///
    /// This method escapes the slice's view.
    ///
    /// # Examples
    ///
    /// ```
    /// use monoio::buf::{IoBuf, IoBufMut};
    ///
    /// let buf = b"hello world".to_vec();
    /// let slice = buf.slice_mut(..5);
    ///
    /// assert_eq!(slice.get_ref(), b"hello world");
    /// assert_eq!(&slice[..], b"hello");
    /// ```
    #[inline]
    pub fn get_ref(&self) -> &T {
        &self.buf
    }

    /// Gets a mutable reference to the underlying buffer.
    ///
    /// This method escapes the slice's view.
    ///
    /// # Examples
    ///
    /// ```
    /// use monoio::buf::{IoBuf, IoBufMut};
    ///
    /// let buf = b"hello world".to_vec();
    /// let mut slice = buf.slice_mut(..5);
    ///
    /// slice.get_mut()[0] = b'b';
    ///
    /// assert_eq!(slice.get_mut(), b"bello world");
    /// assert_eq!(&slice[..], b"bello");
    /// ```
    #[inline]
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.buf
    }

    /// Unwraps this `Slice`, returning the underlying buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use monoio::buf::IoBuf;
    ///
    /// let buf = b"hello world".to_vec();
    /// let slice = buf.slice(..5);
    ///
    /// let buf = slice.into_inner();
    /// assert_eq!(buf, b"hello world");
    /// ```
    pub fn into_inner(self) -> T {
        self.buf
    }
}

impl<T: IoBuf> ops::Deref for SliceMut<T> {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &[u8] {
        let buf_bytes = super::deref(&self.buf);
        let end = std::cmp::min(self.end, buf_bytes.len());
        &buf_bytes[self.begin..end]
    }
}

unsafe impl<T: IoBuf> IoBuf for SliceMut<T> {
    #[inline]
    fn read_ptr(&self) -> *const u8 {
        super::deref(&self.buf)[self.begin..].as_ptr()
    }

    #[inline]
    fn bytes_init(&self) -> usize {
        ops::Deref::deref(self).len()
    }
}

unsafe impl<T: IoBufMut> IoBufMut for SliceMut<T> {
    #[inline]
    fn write_ptr(&mut self) -> *mut u8 {
        unsafe { self.buf.write_ptr().add(self.begin) }
    }

    #[inline]
    fn bytes_total(&mut self) -> usize {
        self.end - self.begin
    }

    #[inline]
    unsafe fn set_init(&mut self, n: usize) {
        self.buf.set_init(self.begin + n);
    }
}

/// An owned view into a contiguous sequence of bytes.
/// Slice implements IoBuf.
pub struct Slice<T> {
    buf: T,
    begin: usize,
    end: usize,
}

impl<T: IoBuf> Slice<T> {
    /// Create a Slice from a buffer and range.
    #[inline]
    pub fn new(buf: T, begin: usize, end: usize) -> Self {
        assert!(end <= buf.bytes_init());
        assert!(begin <= end);
        Self { buf, begin, end }
    }
}

impl<T> Slice<T> {
    /// Create a Slice from a buffer and range without boundary checking.
    ///
    /// # Safety
    /// begin and end must be within the buffer initialized range.
    #[inline]
    pub unsafe fn new_unchecked(buf: T, begin: usize, end: usize) -> Self {
        Self { buf, begin, end }
    }

    /// Offset in the underlying buffer at which this slice starts.
    #[inline]
    pub fn begin(&self) -> usize {
        self.begin
    }

    /// Ofset in the underlying buffer at which this slice ends.
    #[inline]
    pub fn end(&self) -> usize {
        self.end
    }

    /// Gets a reference to the underlying buffer.
    #[inline]
    pub fn get_ref(&self) -> &T {
        &self.buf
    }

    /// Gets a mutable reference to the underlying buffer.
    #[inline]
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.buf
    }

    /// Unwraps this `Slice`, returning the underlying buffer.
    #[inline]
    pub fn into_inner(self) -> T {
        self.buf
    }
}

unsafe impl<T: IoBuf> IoBuf for Slice<T> {
    #[inline]
    fn read_ptr(&self) -> *const u8 {
        unsafe { self.buf.read_ptr().add(self.begin) }
    }

    #[inline]
    fn bytes_init(&self) -> usize {
        self.end - self.begin
    }
}

/// A wrapper to make IoVecBuf impl IoBuf.
pub struct IoVecWrapper<T> {
    // we must make sure raw contains at least one iovec.
    raw: T,
}

impl<T: IoVecBuf> IoVecWrapper<T> {
    /// Create a new IoVecWrapper with something that impl IoVecBuf.
    pub fn new(buf: T) -> Result<Self, T> {
        #[cfg(unix)]
        if buf.read_iovec_len() == 0 {
            return Err(buf);
        }
        #[cfg(windows)]
        if buf.read_wsabuf_len() == 0 {
            return Err(buf);
        }
        Ok(Self { raw: buf })
    }

    /// Consume self and return raw iovec buf.
    pub fn into_inner(self) -> T {
        self.raw
    }
}

unsafe impl<T: IoVecBuf> IoBuf for IoVecWrapper<T> {
    #[inline]
    fn read_ptr(&self) -> *const u8 {
        #[cfg(unix)]
        {
            let iovec = unsafe { *self.raw.read_iovec_ptr() };
            iovec.iov_base as *const u8
        }
        #[cfg(windows)]
        {
            let wsabuf = unsafe { *self.raw.read_wsabuf_ptr() };
            wsabuf.buf as *const u8
        }
    }

    #[inline]
    fn bytes_init(&self) -> usize {
        #[cfg(unix)]
        {
            let iovec = unsafe { *self.raw.read_iovec_ptr() };
            iovec.iov_len
        }
        #[cfg(windows)]
        {
            let wsabuf = unsafe { *self.raw.read_wsabuf_ptr() };
            wsabuf.len
        }
    }
}

/// A wrapper to make IoVecBufMut impl IoBufMut.
pub struct IoVecWrapperMut<T> {
    // we must make sure raw contains at least one iovec.
    raw: T,
}

impl<T: IoVecBufMut> IoVecWrapperMut<T> {
    /// Create a new IoVecWrapperMut with something that impl IoVecBufMut.
    pub fn new(mut iovec_buf: T) -> Result<Self, T> {
        if iovec_buf.write_iovec_len() == 0 {
            return Err(iovec_buf);
        }
        Ok(Self { raw: iovec_buf })
    }

    /// Consume self and return raw iovec buf.
    pub fn into_inner(self) -> T {
        self.raw
    }
}

unsafe impl<T: IoVecBufMut> IoBufMut for IoVecWrapperMut<T> {
    fn write_ptr(&mut self) -> *mut u8 {
        #[cfg(unix)]
        {
            let iovec = unsafe { *self.raw.write_iovec_ptr() };
            iovec.iov_base as *mut u8
        }
        #[cfg(windows)]
        {
            let wsabuf = unsafe { *self.raw.write_wsabuf_ptr() };
            wsabuf.buf as *mut u8
        }
    }

    fn bytes_total(&mut self) -> usize {
        #[cfg(unix)]
        {
            let iovec = unsafe { *self.raw.write_iovec_ptr() };
            iovec.iov_len
        }
        #[cfg(windows)]
        {
            let wsabuf = unsafe { *self.raw.write_wsabuf_ptr() };
            wsabuf.len
        }
    }

    unsafe fn set_init(&mut self, _pos: usize) {}
}