blake2/
as_bytes.rs

1// Copyright 2016 blake2-rfc Developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use core::mem;
9use core::slice;
10
11#[allow(clippy::missing_safety_doc)]
12pub unsafe trait Safe {}
13
14pub trait AsBytes {
15    fn as_bytes(&self) -> &[u8];
16    fn as_mut_bytes(&mut self) -> &mut [u8];
17}
18
19impl<T: Safe> AsBytes for [T] {
20    #[inline]
21    fn as_bytes(&self) -> &[u8] {
22        unsafe {
23            slice::from_raw_parts(self.as_ptr() as *const u8, self.len() * mem::size_of::<T>())
24        }
25    }
26
27    #[inline]
28    fn as_mut_bytes(&mut self) -> &mut [u8] {
29        unsafe {
30            slice::from_raw_parts_mut(
31                self.as_mut_ptr() as *mut u8,
32                self.len() * mem::size_of::<T>(),
33            )
34        }
35    }
36}
37
38unsafe impl Safe for u8 {}
39unsafe impl Safe for u16 {}
40unsafe impl Safe for u32 {}
41unsafe impl Safe for u64 {}
42unsafe impl Safe for i8 {}
43unsafe impl Safe for i16 {}
44unsafe impl Safe for i32 {}
45unsafe impl Safe for i64 {}