• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! The following is derived from Rust's
2 //! library/std/src/sys/unix/io.rs
3 //! dca3f1b786efd27be3b325ed1e01e247aa589c3b.
4 
5 #![allow(missing_docs)]
6 
7 use super::super::c;
8 use core::marker::PhantomData;
9 use core::slice;
10 
11 #[derive(Copy, Clone)]
12 #[repr(transparent)]
13 pub struct IoSlice<'a> {
14     vec: c::iovec,
15     _p: PhantomData<&'a [u8]>,
16 }
17 
18 impl<'a> IoSlice<'a> {
19     #[inline]
new(buf: &'a [u8]) -> IoSlice<'a>20     pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
21         IoSlice {
22             vec: c::iovec {
23                 iov_base: buf.as_ptr() as *mut u8 as *mut c::c_void,
24                 iov_len: buf.len(),
25             },
26             _p: PhantomData,
27         }
28     }
29 
30     #[inline]
advance(&mut self, n: usize)31     pub fn advance(&mut self, n: usize) {
32         if self.vec.iov_len < n {
33             panic!("advancing IoSlice beyond its length");
34         }
35 
36         unsafe {
37             self.vec.iov_len -= n;
38             self.vec.iov_base = self.vec.iov_base.add(n);
39         }
40     }
41 
42     #[inline]
as_slice(&self) -> &[u8]43     pub fn as_slice(&self) -> &[u8] {
44         unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) }
45     }
46 }
47 
48 #[repr(transparent)]
49 pub struct IoSliceMut<'a> {
50     vec: c::iovec,
51     _p: PhantomData<&'a mut [u8]>,
52 }
53 
54 impl<'a> IoSliceMut<'a> {
55     #[inline]
new(buf: &'a mut [u8]) -> IoSliceMut<'a>56     pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
57         IoSliceMut {
58             vec: c::iovec {
59                 iov_base: buf.as_mut_ptr() as *mut c::c_void,
60                 iov_len: buf.len(),
61             },
62             _p: PhantomData,
63         }
64     }
65 
66     #[inline]
advance(&mut self, n: usize)67     pub fn advance(&mut self, n: usize) {
68         if self.vec.iov_len < n {
69             panic!("advancing IoSliceMut beyond its length");
70         }
71 
72         unsafe {
73             self.vec.iov_len -= n;
74             self.vec.iov_base = self.vec.iov_base.add(n);
75         }
76     }
77 
78     #[inline]
as_slice(&self) -> &[u8]79     pub fn as_slice(&self) -> &[u8] {
80         unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) }
81     }
82 
83     #[inline]
as_mut_slice(&mut self) -> &mut [u8]84     pub fn as_mut_slice(&mut self) -> &mut [u8] {
85         unsafe { slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) }
86     }
87 }
88