Skip to main content

rumtk_arena/mem/
traits.rs

1/*
2 *     rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 *     This toolkit aims to be reliable, simple, performant, and standards compliant.
4 *     Copyright (C) 2026  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
5 *     Copyright (C) 2026  MedicalMasses L.L.C. <contact@medicalmasses.com>
6 *
7 *     This program is free software: you can redistribute it and/or modify
8 *     it under the terms of the GNU General Public License as published by
9 *     the Free Software Foundation, either version 3 of the License, or
10 *     (at your option) any later version.
11 *
12 *     This program is distributed in the hope that it will be useful,
13 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
14 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 *     GNU General Public License for more details.
16 *
17 *     You should have received a copy of the GNU General Public License
18 *     along with this program.  If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use crate::base::*;
22
23pub trait AsPtr {
24    #[inline(always)]
25    fn as_ptr(&self) -> *const u8 {
26        self as *const _ as *const u8
27    }
28    #[inline(always)]
29    fn as_mut_ptr(&mut self) -> *mut u8 {
30        self as *mut _ as *mut u8
31    }
32}
33
34pub trait SizedType {
35    #[inline(always)]
36    fn size(&self) -> usize;
37}
38
39impl SizedType for [u8] { fn size(&self) -> usize { self.len() } }
40impl SizedType for &[u8] { fn size(&self) -> usize { self.len() } }
41impl SizedType for RUMVec<u8> { fn size(&self) -> usize { self.len() } }
42impl SizedType for &RUMVec<u8> { fn size(&self) -> usize { self.len() } }
43impl SizedType for RUMString { fn size(&self) -> usize { self.len() } }
44
45pub trait AsSlice: AsPtr + SizedType {
46    #[inline(always)]
47    fn as_slice(&self) -> &[u8] { as_slice(self.as_ptr(),  self.size()) }
48    #[inline(always)]
49    fn as_slice_mut(&mut self) -> &mut [u8] {  as_slice_mut(self.as_mut_ptr(),  self.size()) }
50
51    #[inline(always)]
52    fn contains(&self, x: &u8) -> bool {
53        self.as_slice().contains(x)
54    }
55}
56
57#[inline]
58pub fn as_slice<'a>(src: *const u8, size: usize) -> &'a [u8] {
59    unsafe { std::slice::from_raw_parts(src, size) }
60}
61
62#[inline]
63pub fn as_slice_mut<'a>(src: *mut u8, size: usize) -> &'a mut [u8] {
64    unsafe { std::slice::from_raw_parts_mut(src, size) }
65}