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

/// Special marker trait implemented only for `std140` types.
pub unsafe trait Std140: AsStd140<Std140 = Self> {}

/// Structure to transform data from rust's structure to the raw data ready to upload to UBO.
/// Users should prefer to use `derive(AsStd140)` instead of implementing this manually.
pub unsafe trait AsStd140 {
    /// ZST that enforces alignment required for this type.
    type Align: Copy + Default;

    /// Type that contain same data with memory layout matching glsl's `layout(std140)`.
    type Std140: Std140 + ?Sized;

    /// Get aligned data from structure.
    fn std140(&self) -> Self::Std140
    where
        Self::Std140: Sized,
    ;
}

/// Convert reference to bytes slice.
pub fn as_bytes<T>(value: &T) -> &[u8]
where
    T: ?Sized,
{
    unsafe {
        // Inspecting any value as bytes should be safe.
        std::slice::from_raw_parts(value as *const T as *const u8, std::mem::size_of_val(value))
    }
}