workflow_core/
utils.rs

1//! buffer slicing and other utilities
2
3/// Takes a `&[u8]` buffer slice and returns a slice `&[T]`
4/// with a given number of elements of type `T`
5pub fn buffer_as_slice<'data, T: 'data>(
6    data: &'data [u8],
7    byte_offset: usize,
8    elements: usize,
9) -> &'data [T] {
10    unsafe {
11        std::slice::from_raw_parts::<T>(
12            std::mem::transmute::<*const u8, *const T>(data.as_ptr().add(byte_offset)),
13            elements,
14        )
15    }
16}
17
18/// Takes a mutable `&[u8]` buffer slice and returns a
19/// mutable slice `&[T]` with a given number of elements
20/// of type `T`
21pub fn buffer_as_slice_mut<'data, T: 'data>(
22    data: &'data mut [u8],
23    byte_offset: usize,
24    elements: usize,
25) -> &mut [T] {
26    unsafe {
27        std::slice::from_raw_parts_mut::<T>(
28            std::mem::transmute::<*mut u8, *mut T>(data.as_mut_ptr().add(byte_offset)),
29            elements,
30        )
31    }
32}
33
34/// Takes a reference to a struct of type `T` and returns
35/// a raw `&[u8]` slice with byte length of the type `T`
36pub fn struct_as_slice_u8<'data, T: 'data>(data: &T) -> &'data [u8] {
37    unsafe {
38        std::slice::from_raw_parts::<u8>(data as *const T as *const u8, std::mem::size_of::<T>())
39    }
40}
41
42/// Extract a substring starting at 0 and truncating it
43/// to `min(length,str.len())`.
44pub fn substring(str: &str, start: usize, length: usize) -> String {
45    str[start..length.min(str.len())].to_string()
46}
47
48/// Truncate a string, optionally appending another string
49/// or appending `"..."` if the `append` string is `None`
50pub fn substr(str: &str, start: usize, length: usize, append: Option<&str>) -> String {
51    let len = str.len();
52    let str = str[start..length.min(len)].to_string();
53    if len > length {
54        str + append.unwrap_or("...")
55    } else {
56        str
57    }
58}