blob: ec7a6a8af22c9822171f4b96fbbed1b499080b9a [file] [log] [blame]
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use core::mem;
use core::slice;
/// Trigger an assertion if "cond" fails in debug builds, return an error in
/// release builds.
macro_rules! dcheck {
($cond:expr, $err:expr) => {
let cond = $cond;
debug_assert!(cond);
if !(cond) {
return Err($err);
}
};
}
pub(crate) use dcheck;
/// Assert that a Result is_ok(). Why is this not in the standard library?
#[cfg(test)]
macro_rules! assert_ok {
($cond:expr) => {
let result = $cond;
assert!(result.is_ok());
};
}
#[cfg(test)]
pub(crate) use assert_ok;
/// Assert that a Result is_err(). Why is this not in the standard library?
#[cfg(test)]
macro_rules! assert_err {
($cond:expr) => {
let result = $cond;
assert!(result.is_err());
};
}
#[cfg(test)]
pub(crate) use assert_err;
// FIXME these are quick and dirty hacks to make serialization of POD types
// easier
pub fn as_unsafe_blob<T: Sized>(p: &T) -> &[u8] {
unsafe {
let tp: *const T = p as *const T;
let pp: *const u8 = tp as *const u8;
slice::from_raw_parts(pp, mem::size_of::<T>())
}
}
pub fn as_unsafe_blob_mut<T: Sized>(p: &mut T) -> &mut [u8] {
unsafe {
let tp: *mut T = p as *mut T;
let pp: *mut u8 = tp as *mut u8;
slice::from_raw_parts_mut(pp, mem::size_of::<T>())
}
}
pub fn from_unsafe_blob<T: Sized>(p: &[u8]) -> &T {
unsafe {
let pp: *const u8 = p.as_ptr();
let tp: *const T = pp as *const T;
return &*tp;
}
}
pub fn from_unsafe_blob_mut<T: Sized>(p: &mut [u8]) -> &mut T {
unsafe {
let pp: *mut u8 = p.as_mut_ptr();
let tp: *mut T = pp as *mut T;
return &mut *tp;
}
}
pub fn slice_as_unsafe_blob_mut<T: Sized>(p: &mut [T]) -> &mut [u8] {
unsafe {
let tp: *mut T = p.as_mut_ptr();
let pp: *mut u8 = tp as *mut u8;
slice::from_raw_parts_mut(pp, mem::size_of::<T>())
}
}
pub fn slice_as_unsafe_blob<T: Sized>(p: &[T]) -> &[u8] {
unsafe {
let tp: *const T = p.as_ptr();
let pp: *const u8 = tp as *const u8;
slice::from_raw_parts(pp, mem::size_of::<T>())
}
}