mod3d_base/
byte_buffer.rs

1//a ByteBuffer
2//tp ByteBuffer
3/// A trait for all types that are to be used as sources of data for
4/// buffers of, e.g. vertex data, indices, etc
5///
6/// The data is viewed by OpenGL as a pointer and byte length; these
7/// methods provide access to the data in that way.
8///
9/// These methods are all safe - any use of the information they
10/// provide may be unsafe.
11pub trait ByteBuffer {
12    /// Get the length of the data buffer in bytes
13    fn byte_length(&self) -> usize;
14    /// Borrow the data as an array of bytes
15    fn borrow_bytes(&self) -> &[u8];
16    /// Return a pointer to the first byte of the data contents
17    fn as_u8_ptr(&self) -> *const u8;
18}
19
20//ti ByteBuffer for [T; N]
21/// Implement ByteBuffer for slice of T
22impl<T, const N: usize> ByteBuffer for [T; N] {
23    //fp byte_length
24    fn byte_length(&self) -> usize {
25        std::mem::size_of::<T>() * N
26    }
27
28    //fp borrow_bytes
29    fn borrow_bytes(&self) -> &[u8] {
30        let len = std::mem::size_of::<T>() * self.len();
31        let data = self.as_u8_ptr();
32        unsafe { std::slice::from_raw_parts(data, len) }
33    }
34
35    //fp as_u8_ptr
36    fn as_u8_ptr(&self) -> *const u8 {
37        let data: *const T = &self[0];
38        unsafe { std::mem::transmute::<_, *const u8>(data) }
39    }
40
41    //zz All done
42}
43
44//ti ByteBuffer for Vec
45/// Implement ByteBuffer for Vec
46impl<T> ByteBuffer for Vec<T> {
47    //fp byte_length
48    fn byte_length(&self) -> usize {
49        std::mem::size_of::<T>() * self.len()
50    }
51
52    //fp borrow_bytes
53    fn borrow_bytes(&self) -> &[u8] {
54        let len = std::mem::size_of::<T>() * self.len();
55        let data = self.as_u8_ptr();
56        unsafe { std::slice::from_raw_parts(data, len) }
57    }
58
59    //fp as_u8_ptr
60    fn as_u8_ptr(&self) -> *const u8 {
61        let data: *const T = &self[0];
62        unsafe { std::mem::transmute::<_, *const u8>(data) }
63    }
64
65    //zz All done
66}
67
68//ti ByteBuffer for &[T]
69/// Implement ByteBuffer for &[T]
70impl<T> ByteBuffer for &[T] {
71    //fp byte_length
72    fn byte_length(&self) -> usize {
73        std::mem::size_of_val(*self)
74    }
75
76    //fp borrow_bytes
77    fn borrow_bytes(&self) -> &[u8] {
78        let len = std::mem::size_of_val(*self);
79        let data = self.as_u8_ptr();
80        unsafe { std::slice::from_raw_parts(data, len) }
81    }
82
83    //fp as_u8_ptr
84    fn as_u8_ptr(&self) -> *const u8 {
85        let data: *const T = self.as_ptr();
86        unsafe { std::mem::transmute::<_, *const u8>(data) }
87    }
88
89    //zz All done
90}