Skip to main content

rumtk_arena/buffers/
rumbuffer.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 */
20use crate::base::{RUMResult, RUMVec};
21use crate::buffers::buffer_to_str;
22use crate::mem::{as_slice_mut, copy_from_slice, AsRUMPtr, AsRUMSlice};
23use crate::{rumtk_mem_layout, SizedRUMType};
24use std::alloc::{alloc, dealloc, Layout};
25use std::cmp::PartialEq;
26use std::ops::DerefMut;
27use std::ops::IndexMut;
28use std::ops::{Deref, RangeTo, RangeToInclusive};
29use std::ops::{Index, Range, RangeFull};
30use std::sync::LazyLock;
31
32const EMPTY_BUFFER_DATA: [u8;0] = [0;0];
33static EMPTY_RUMBUFFER: LazyLock<RUMBuffer> = LazyLock::new(|| RUMBuffer::new());
34
35///
36/// The [RUMBuffer] type is meant to be a very lightweight owned buffer pointer. The impetus for building
37/// this type is that benchmarking showed a potential vector getting allocated by the **bytes** crate.
38/// I was using the bytes crate before because it is a very solid crate. However, the vector allocations worried me.
39/// It was likely part of that crates interior mutability strategy with vtables but it was one of a few
40/// areas consuming a lot of time and most importantly consuming kernel time by invoking malloc.
41///
42/// ## Example
43/// ### Creation
44/// ```
45/// use rumtk_arena::buffers::*;
46///
47/// let buffer = RUMBuffer::from("Hello World!");
48/// let expected = b"Hello World!";
49///
50/// assert_eq!(&buffer[..], expected, "Could not create RUMBuffer!");
51/// ```
52///
53/// ### Split Buffer
54/// ```
55/// use rumtk_arena::buffers::*;
56///
57/// let mut buffer = RUMBuffer::from("Hello World!");
58/// let section = buffer.split_to(5).unwrap();
59/// let expected = b"Hello";
60///
61/// assert_eq!(&section[..], expected, "Could not create RUMBuffer!");
62/// ```
63///
64#[derive(Debug)]
65pub struct RUMBuffer {
66    data: *const u8,
67    size: u32,
68    dealloc: bool,
69}
70
71impl RUMBuffer {
72    #[inline]
73    pub const fn new() -> Self {
74        Self {
75            data: EMPTY_BUFFER_DATA.as_ptr(),
76            size: 0,
77            dealloc: false,
78        }
79    }
80
81    #[inline]
82    pub fn from_slice(data: &[u8]) -> Self {
83        if data.is_empty() {
84            return Self::new();
85        }
86
87        let data_length = data.len();
88        let ptr = unsafe { alloc(Layout::from_size_align_unchecked(data_length, size_of::<u8>())) };
89        let dst = as_slice_mut(ptr, data_length);
90        copy_from_slice(&data[..], dst);
91        Self {
92            data: ptr,
93            size: data_length as u32,
94            dealloc: true,
95        }
96    }
97
98    #[inline]
99    pub fn from_static(mut data: &'static [u8]) -> Self {
100        let ptr = data.as_ptr();
101        let size = data.len();
102        Self {
103            data: ptr,
104            size: size as u32,
105            dealloc: false,
106        }
107    }
108
109    #[inline]
110    pub fn from_parts(data: *const u8, length: usize, dealloc: bool) -> Self {
111        Self {
112            data,
113            size: length as u32,
114            dealloc,
115        }
116    }
117
118    #[inline]
119    pub fn into_raw_parts(mut self) -> (*mut u8, usize, usize) {
120        self.dealloc = false;
121        (self.as_mut_ptr(), self.len(), self.len())
122    }
123
124    #[inline]
125    pub fn split_to(&mut self, offset: usize) -> Option<Self> {
126        if offset <= self.size as usize {
127            let ptr = self.as_ptr();
128            let new_ptr = unsafe { ptr.add(offset) };
129            let copy = Self {
130                data: ptr,
131                size: offset as u32,
132                dealloc: false,
133            };
134            self.data = new_ptr;
135            self.size -= (offset as u32);
136            Some(copy)
137        } else {
138            None
139        }
140    }
141
142    #[inline]
143    pub fn freeze(&self) -> Self {
144        Self {
145            data: self.as_ptr(),
146            size: self.size,
147            dealloc: false,
148        }
149    }
150
151    #[inline]
152    pub fn to_vec(&self) -> RUMVec<u8> {
153        self.as_slice().to_vec()
154    }
155
156    #[inline]
157    pub fn as_str(&self) -> RUMResult<&str> {
158        buffer_to_str(self)
159    }
160
161    #[inline]
162    pub fn truncate(&mut self, len: usize) {
163        self.size = len as u32;
164    }
165
166    #[inline]
167    pub fn is_empty(&self) -> bool {
168        self.size == 0
169    }
170
171    #[inline]
172    pub fn is_buffer(&self) -> bool {
173        self.dealloc
174    }
175
176    #[inline]
177    pub fn is_view(&self) -> bool {
178        !self.dealloc
179    }
180}
181
182impl Iterator for RUMBuffer {
183    type Item = u8;
184
185    #[inline]
186    fn next(&mut self) -> Option<Self::Item> {
187        if self.size == 0 { return None };
188
189        let v = self[0];
190        self.data = unsafe { self.as_ptr().add(1) };
191        Some(v)
192    }
193}
194
195impl SizedRUMType for RUMBuffer {
196    fn size(&self) -> usize {
197        self.size as usize
198    }
199}
200
201impl SizedRUMType for &RUMBuffer {
202    fn size(&self) -> usize {
203        self.size as usize
204    }
205}
206
207impl SizedRUMType for &&RUMBuffer {
208    fn size(&self) -> usize {
209        self.size as usize
210    }
211}
212
213impl AsRUMPtr for RUMBuffer {
214    #[inline(always)]
215    fn as_rum_ptr(&self) -> *const u8 {
216        self.data
217    }
218    #[inline(always)]
219    fn as_mut_rum_ptr(&mut self) -> *mut u8 {
220        self.data as *mut u8
221    }
222}
223
224impl AsRUMPtr for &RUMBuffer {
225    #[inline(always)]
226    fn as_rum_ptr(&self) -> *const u8 {
227        self.data
228    }
229    #[inline(always)]
230    fn as_mut_rum_ptr(&mut self) -> *mut u8 {
231        self.data as *mut u8
232    }
233}
234
235impl AsRUMPtr for &&RUMBuffer {
236    #[inline(always)]
237    fn as_rum_ptr(&self) -> *const u8 {
238        self.data
239    }
240    #[inline(always)]
241    fn as_mut_rum_ptr(&mut self) -> *mut u8 {
242        self.data as *mut u8
243    }
244}
245
246impl AsRUMSlice for RUMBuffer {  }
247impl AsRUMSlice for &RUMBuffer {  }
248impl AsRUMSlice for &&RUMBuffer {  }
249
250impl AsRef<[u8]> for RUMBuffer {
251    #[inline]
252    fn as_ref(&self) -> &[u8] {
253        self.as_slice()
254    }
255}
256
257impl Deref for RUMBuffer {
258    type Target = [u8];
259    #[inline]
260    fn deref(&self) -> &Self::Target {
261        self.as_rum_slice()
262    }
263}
264
265impl DerefMut for RUMBuffer {
266    #[inline]
267    fn deref_mut(&mut self) -> &mut [u8] {
268        self.as_rum_slice_mut()
269    }
270}
271
272impl PartialEq for RUMBuffer {
273    #[inline]
274    fn eq(&self, other: &Self) -> bool {
275        self.as_slice() == other.as_slice()
276    }
277}
278
279impl Default for RUMBuffer {
280    #[inline]
281    fn default() -> Self {
282        Self::new()
283    }
284}
285
286impl Clone for RUMBuffer {
287    #[inline]
288    fn clone(&self) -> Self {
289        self.freeze()
290    }
291}
292
293impl Drop for RUMBuffer {
294    #[inline]
295    fn drop(&mut self) {
296        if self.dealloc {
297            unsafe {
298                dealloc(self.as_mut_ptr(), rumtk_mem_layout!(self.size as usize))
299            }
300        }
301    }
302}
303
304unsafe impl Send for RUMBuffer {}
305unsafe impl Sync for RUMBuffer {}
306
307///////////////////// Indexing ////////////////////////////////////
308
309impl Index<usize> for RUMBuffer {
310    type Output = u8;
311    #[inline]
312    fn index(&self, i: usize) -> &Self::Output {
313        &self.as_slice()[i]
314    }
315}
316
317impl Index<Range<usize>> for RUMBuffer {
318    type Output = [u8];
319    #[inline]
320    fn index(&self, i: Range<usize>) -> &Self::Output {
321        &self.as_slice()[i.start..i.end]
322    }
323}
324
325impl Index<RangeTo<usize>> for RUMBuffer {
326    type Output = [u8];
327    #[inline]
328    fn index(&self, i: RangeTo<usize>) -> &Self::Output {
329        &self.as_slice()[..i.end]
330    }
331}
332
333impl Index<RangeToInclusive<usize>> for RUMBuffer {
334    type Output = [u8];
335    #[inline]
336    fn index(&self, i: RangeToInclusive<usize>) -> &Self::Output {
337        &self.as_slice()[..=i.end]
338    }
339}
340
341impl Index<RangeFull> for RUMBuffer {
342    type Output = [u8];
343    #[inline]
344    fn index(&self, i: RangeFull) -> &Self::Output {
345        self.as_slice()
346    }
347}
348
349///////////////////// Indexing (Mut) ////////////////////////////////////
350
351impl IndexMut<usize> for RUMBuffer {
352    #[inline]
353    fn index_mut(&mut self, i: usize) -> &mut Self::Output {
354        &mut self.as_rum_slice_mut()[i]
355    }
356}
357
358impl IndexMut<Range<usize>> for RUMBuffer {
359    #[inline]
360    fn index_mut(&mut self, i: Range<usize>) -> &mut Self::Output {
361        &mut self.as_rum_slice_mut()[i.start..i.end]
362    }
363}
364
365impl IndexMut<RangeTo<usize>> for RUMBuffer {
366    #[inline]
367    fn index_mut(&mut self, i: RangeTo<usize>) -> &mut Self::Output {
368        &mut self.as_rum_slice_mut()[..i.end]
369    }
370}
371
372impl IndexMut<RangeToInclusive<usize>> for RUMBuffer {
373    #[inline]
374    fn index_mut(&mut self, i: RangeToInclusive<usize>) -> &mut Self::Output {
375        &mut self.as_rum_slice_mut()[..=i.end]
376    }
377}
378
379impl IndexMut<RangeFull> for RUMBuffer {
380    #[inline]
381    fn index_mut(&mut self, i: RangeFull) -> &mut Self::Output {
382        self.as_rum_slice_mut()
383    }
384}
385
386/////////////////////// Conversions ////////////////////////////////
387impl From<String> for RUMBuffer {
388    #[inline]
389    fn from(mut data: String) -> Self {
390        let (s, l, c) = data.into_raw_parts();
391        Self::from_parts(s, l, true)
392    }
393}
394impl From<Vec<u8>> for RUMBuffer {
395    #[inline]
396    fn from(mut data: Vec<u8>) -> Self {
397        let (s, l, c) = data.into_raw_parts();
398        Self::from_parts(s, l, true)
399    }
400}
401
402impl From<&RUMVec<u8>> for RUMBuffer {
403    #[inline]
404    fn from(data: &RUMVec<u8>) -> Self {
405        Self::from_slice(data.as_slice())
406    }
407}
408
409impl From<&[u8]> for RUMBuffer {
410    #[inline]
411    fn from(data: &[u8]) -> Self {
412        Self::from_slice(data)
413    }
414}
415
416impl<const N: usize> From<&[u8; N]> for RUMBuffer {
417    #[inline]
418    fn from(data: &[u8; N]) -> Self {
419        Self::from(data.as_slice())
420    }
421}
422
423impl From<&str> for RUMBuffer {
424    #[inline]
425    fn from(data: &str) -> Self {
426        Self::from(data.as_bytes())
427    }
428}