Skip to main content

rumtk_arena/
cpu.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::RUMVec;
21use crate::rumtk_mem_quick_array_init;
22pub use branches::{likely as cpu_likely_branch, prefetch_read_data, unlikely as cpu_unlikely_branch};
23pub use std::simd::prelude::*;
24
25pub const CPU_L1_PREFETCH: i32 = 0;
26pub const CPU_L2_PREFETCH: i32 = 1;
27pub const CPU_L3_PREFETCH: i32 = 2;
28pub const CPU_NONTEMPORAL_PREFETCH: i32 = 3;
29pub const CPU_L1_CACHE_LINE_SIZE: usize = 64; // Number of bytes in a typical x86_64 CPU L1 cache line.
30pub const CPU_L1_CACHE_SIZE: usize = 32 * 1024; // Number of bytes in a typical x86_64 CPU L1 cache per core.
31pub const CPU_PAGE_SIZE: usize = 4 * 1024; // Typical CPU page size
32pub const CPU_SIMD_64_SIZE: usize = 64;
33pub const CPU_SIMD_32_SIZE: usize = 32;
34pub const CPU_SIMD_16_SIZE: usize = 16;
35pub const CPU_SIMD_8_SIZE: usize = 8;
36pub const CPU_SIMD_AVERAGE_ALU_COUNT: usize = 4;
37pub const CPU_SEARCH_WINDOW_1024_SIZE: usize = 1024;
38pub const CPU_SEARCH_WINDOW_512_SIZE: usize = 512;
39pub const CPU_SEARCH_WINDOW_256_SIZE: usize = 256;
40pub const CPU_SEARCH_WINDOW_128_SIZE: usize = 128;
41pub const CPU_SEARCH_WINDOW_64_SIZE: usize = 64;
42pub const CPU_SEARCH_WINDOW_32_SIZE: usize = 32;
43pub const CPU_SEARCH_WINDOW_16_SIZE: usize = 16;
44
45
46#[cfg(feature = "simd")]
47pub type u8xN<const SEARCH_WINDOW_SIZE: usize> = Simd<u8, SEARCH_WINDOW_SIZE>;
48
49////////////////////////////////////////CPU CACHE HINTS///////////////////////////////
50#[inline]
51pub fn cpu_l3_prefetch(data: *const u8) {
52    prefetch_read_data::<u8, CPU_L3_PREFETCH>(data);
53}
54
55#[inline]
56pub fn cpu_l2_prefetch(data: *const u8) {
57    prefetch_read_data::<u8, CPU_L2_PREFETCH>(data);
58}
59
60#[inline]
61pub fn cpu_l1_prefetch(data: *const u8) {
62    prefetch_read_data::<u8, CPU_L1_PREFETCH>(data);
63}
64
65#[inline(always)]
66pub fn cpu_slice_to_array<const SLICE_SIZE: usize>(chunk: &[u8]) -> [u8; SLICE_SIZE] {
67    chunk.try_into().expect("length mismatch")
68}
69
70#[inline(always)]
71pub fn cpu_slice_to_array_padded<const SLICE_SIZE: usize, const PAD: u8>(chunk: &[u8]) -> [u8; SLICE_SIZE] {
72    let mut result = [PAD; SLICE_SIZE];
73    result[..chunk.len()].copy_from_slice(chunk);
74    result
75}
76
77#[cfg(feature = "simd")]
78#[inline(always)]
79pub fn cpu_slice_to_simd<const SLICE_SIZE: usize>(chunk: &[u8]) -> u8xN<SLICE_SIZE> {
80    u8xN::from_slice(chunk)
81}
82
83#[cfg(feature = "simd")]
84#[inline(always)]
85pub fn cpu_slice_to_simd_padded<const SLICE_SIZE: usize, const PAD: u8>(chunk: &[u8]) -> u8xN<SLICE_SIZE> {
86    u8xN::from_array(cpu_slice_to_array_padded::<SLICE_SIZE, 0>(chunk))
87}
88
89#[cfg(feature = "simd")]
90#[inline(always)]
91pub fn cpu_simd_splat<const SLICE_SIZE: usize>(byte: u8) -> u8xN<SLICE_SIZE> {
92    u8xN::splat(byte)
93}
94
95#[inline(always)]
96pub fn cpu_slice_splat<const SLICE_SIZE: usize>(input: &[u8]) -> [u8; SLICE_SIZE] {
97    let mut result = [0u8; SLICE_SIZE];
98
99    for chunk in result.chunks_mut(input.len()) {
100        chunk.copy_from_slice(&input[..chunk.len()]);
101    }
102
103    result
104}
105
106////////////////////////////////////////SIMD MASKS//////////////////////////////////////////
107#[cfg(feature = "simd")]
108#[inline(always)]
109pub fn cpu_simd_shift_right_n<const LANE_SIZE: usize, const SHIFT: usize, const PAD: u8>(item: &u8xN<LANE_SIZE>) -> u8xN<LANE_SIZE> {
110    item.shift_elements_right::<SHIFT>(PAD)
111}
112
113#[cfg(feature = "simd")]
114#[inline(always)]
115pub fn cpu_simd_masks<const LANE_SIZE: usize>(pattern: &[u8]) -> RUMVec<u8xN<LANE_SIZE>> {
116    let mask = u8xN::<LANE_SIZE>::from_array(cpu_slice_splat(pattern));
117    let mut masks = RUMVec::<u8xN<LANE_SIZE>>::with_capacity(pattern.len());
118
119    masks.push(mask);
120
121    for i in 1..pattern.len() {
122        let shifted = cpu_simd_shift_right_n::<LANE_SIZE, 1, 0>(&mask);
123        masks.push(shifted);
124    }
125
126    masks
127}
128
129////////////////////////////////////////SIMD COMP OPS//////////////////////////////////////////
130#[cfg(feature = "simd")]
131#[inline(always)]
132pub fn cpu_simd_less_than_index<const LANE_SIZE: usize>(item: &u8xN<LANE_SIZE>, byte: u8) -> Option<usize> {
133    let mask = cpu_simd_splat::<LANE_SIZE>(byte);
134    let result = item.simd_lt(mask);
135    
136    if result.any() {
137        let bitmap = result.to_bitmask();
138        return Some(bitmap.leading_zeros() as usize)
139    }
140    
141    None
142}
143
144#[cfg(feature = "simd")]
145#[inline(always)]
146pub fn cpu_simd_greater_than_index<const LANE_SIZE: usize>(item: &u8xN<LANE_SIZE>, byte: u8) -> Option<usize> {
147    let mask = cpu_simd_splat::<LANE_SIZE>(byte);
148    let result = item.simd_ge(mask);
149
150    if result.any() {
151        let bitmap = result.to_bitmask();
152        return Some(bitmap.leading_zeros() as usize)
153    }
154
155    None
156}
157
158////////////////////////////////////////SEARCH FOR NEEDLE IN HAYSTACK///////////////////////////////
159
160#[inline(always)]
161pub fn cpu_find_fallback(chunk: &[u8], byte: u8) -> Option<usize> {
162    chunk.iter().position(|c| *c==byte)
163}
164
165#[cfg(feature = "simd")]
166#[inline(always)]
167fn cpu_find_simd_avx2_n<const SEARCH_WINDOW_SIZE: usize>(data_vec: u8xN<SEARCH_WINDOW_SIZE>, target: u8xN<SEARCH_WINDOW_SIZE>) -> Option<usize> {
168    let mask = data_vec.simd_eq(target);
169
170    if mask.any() {
171        let bitmask = mask.to_bitmask();
172        let lane_i = bitmask.trailing_zeros() as usize;
173        return Some(lane_i);
174    }
175
176    None
177}
178
179#[cfg(feature = "simd")]
180#[inline(always)]
181fn cpu_find_simd_avx2_unpadded<const SEARCH_WINDOW_SIZE: usize>(chunk: &[u8], target: u8xN<SEARCH_WINDOW_SIZE>) -> Option<usize> {
182    let data_vec = cpu_slice_to_simd::<SEARCH_WINDOW_SIZE>(chunk);
183    cpu_find_simd_avx2_n(data_vec, target)
184}
185
186#[cfg(feature = "simd")]
187#[inline(always)]
188fn cpu_find_simd_avx2_padded<const SEARCH_WINDOW_SIZE: usize>(chunk: &[u8], target: u8xN<SEARCH_WINDOW_SIZE>) -> Option<usize> {
189    let data_vec = cpu_slice_to_simd_padded::<SEARCH_WINDOW_SIZE, 0>(chunk);
190    cpu_find_simd_avx2_n(data_vec, target)
191}
192
193///
194/// Use SIMD to find the index of a byte in a byte slice.
195///
196///
197#[cfg(feature = "simd")]
198#[inline(always)]
199pub fn cpu_find_simd_n<const LANE_SIZE: usize>
200(
201    chunk: &[u8],
202    byte: u8,
203) -> Option<usize>
204{
205    let mask = u8xN::<LANE_SIZE>::splat(byte);
206    let needs_padding = chunk.len() % LANE_SIZE;
207    let unpadded = chunk.len() - needs_padding; // The compiler will optimize this with a constant per my compiler explorer experiment
208    // https://godbolt.org/z/fhh5nG34f
209
210    for (i,window) in chunk[..unpadded].chunks(LANE_SIZE).enumerate() {
211        cpu_l1_prefetch(window.as_ptr());
212        if let Some(lane_i) = cpu_find_simd_avx2_unpadded::<LANE_SIZE>(window, mask) {
213            return Some(i * LANE_SIZE + lane_i);
214        }
215    }
216
217    cpu_find_simd_avx2_padded::<LANE_SIZE>(&chunk[unpadded..], mask).map(|idx| unpadded + idx)
218}
219
220#[cfg(feature = "simd")]
221#[inline(always)]
222pub fn cpu_find(window: &[u8], byte: u8) -> Option<usize> {
223    cpu_find_simd_n::<CPU_SIMD_64_SIZE>(
224        window,
225        byte,
226    )
227}
228
229#[cfg(not(feature = "simd"))]
230#[inline]
231pub fn cpu_find(window: &[u8], byte: u8) -> Option<usize> {
232    cpu_find_fallback(
233        window,
234        byte,
235    )
236}
237
238////////////////////////////////////////SEARCH FOR CONTINUOUS SLICE OF NEEDLES///////////////////////////////
239#[inline(always)]
240pub fn cpu_continuous_count_fallback(chunk: &[u8], byte: u8) -> Option<usize> {
241    let mut count = 0;
242    for i in 0..chunk.len() {
243        if cpu_unlikely_branch(chunk[i] != byte) {
244            return Some(count);
245        }
246        count += 1;
247    }
248    Some(count)
249}
250
251#[cfg(feature = "simd")]
252#[inline]
253fn cpu_continuous_count_simd_avx2_n<const SEARCH_WINDOW_SIZE: usize>(data_vec: u8xN<SEARCH_WINDOW_SIZE>, target: u8xN<SEARCH_WINDOW_SIZE>) -> usize {
254    let mask = data_vec.simd_eq(target);
255
256    let bitmask = mask.to_bitmask();
257    bitmask.trailing_zeros() as usize
258}
259
260#[cfg(feature = "simd")]
261#[inline]
262fn cpu_continuous_count_simd_avx2_unpadded<const SEARCH_WINDOW_SIZE: usize>(chunk: &[u8], target: u8xN<SEARCH_WINDOW_SIZE>) -> usize {
263    let data_vec = cpu_slice_to_simd::<SEARCH_WINDOW_SIZE>(chunk);
264    cpu_continuous_count_simd_avx2_n(data_vec, target)
265}
266
267#[cfg(feature = "simd")]
268#[inline]
269fn cpu_continuous_count_simd_avx2_padded<const SEARCH_WINDOW_SIZE: usize>(chunk: &[u8], target: u8xN<SEARCH_WINDOW_SIZE>) -> usize {
270    let data_vec = cpu_slice_to_simd_padded::<SEARCH_WINDOW_SIZE, 0>(chunk);
271    cpu_continuous_count_simd_avx2_n(data_vec, target)
272}
273
274///
275/// Use SIMD to find the index of a byte in a byte slice.
276///
277/// ## Note
278///
279/// We try saturating the CPU SIMD ports with ops. If we had to do all [CPU_SIMD_AVERAGE_ALU_COUNT]
280/// passes to find the needle, we essentially speculatively precomputed the index. Our worst case
281/// is if we only had to do one pass to find the needle, but we are relying on out-of-order execution
282/// and the cheapness of SIMD to hide the latency. This also serves as a form of prefetching the
283/// byte slice into the cache lines, so beware of thrashing it.
284///
285///
286#[cfg(feature = "simd")]
287#[inline]
288pub fn cpu_continuous_count_simd_n<const LANE_SIZE: usize>
289(
290    chunk: &[u8],
291    byte: u8,
292) -> Option<usize>
293{
294    let mask = u8xN::<LANE_SIZE>::splat(byte);
295    let mut iter = chunk.chunks(LANE_SIZE);
296    let max_iter = iter.len();
297    let large_steps = max_iter / CPU_SIMD_AVERAGE_ALU_COUNT; // div here so consider changing to shifts for extra ns perf
298    let mut indx = 0;
299
300    // Try saturating the CPU SIMD ports with ops. If we had to do all 4 passes to find the needle,
301    // we essentially speculatively precomputed the index. Our worst case is if we only had to do
302    // one pass to find the needle but we are relying on out of order execution and the cheapness of
303    // SIMD to hide the latency. This also serves as a form of prefetching byte slice.
304    for _ in 0..large_steps {
305        let mut sizes = rumtk_mem_quick_array_init!(usize, CPU_SIMD_AVERAGE_ALU_COUNT);
306        sizes[0] = cpu_continuous_count_simd_avx2_unpadded::<LANE_SIZE>(iter.next().unwrap_or_default(), mask);
307        sizes[1] = cpu_continuous_count_simd_avx2_unpadded::<LANE_SIZE>(iter.next().unwrap_or_default(), mask);
308        sizes[2] = cpu_continuous_count_simd_avx2_unpadded::<LANE_SIZE>(iter.next().unwrap_or_default(), mask);
309        sizes[3] = cpu_continuous_count_simd_avx2_unpadded::<LANE_SIZE>(iter.next().unwrap_or_default(), mask);
310
311        for s in sizes {
312            if s < LANE_SIZE {
313                return Some(indx + s);
314            }
315            indx += LANE_SIZE;
316        }
317    }
318
319    match iter.next() {
320        Some(window) => {
321            Some(indx + cpu_continuous_count_simd_avx2_padded::<LANE_SIZE>(window, mask))
322        },
323        None => Some(indx),
324    }
325}
326
327#[cfg(feature = "simd")]
328#[inline]
329pub fn cpu_continuous_count(window: &[u8], byte: u8) -> Option<usize> {
330    let start = cpu_find(window, byte)?;
331    cpu_continuous_count_simd_n::<CPU_SIMD_64_SIZE>(
332        &window[start..],
333        byte,
334    )
335}
336
337#[cfg(not(feature = "simd"))]
338#[inline]
339pub fn cpu_continuous_count(window: &[u8], byte: u8) -> Option<usize> {
340    let start = cpu_find(window, byte)?;
341    cpu_continuous_count_fallback(
342        &window[start..],
343        byte,
344    )
345}
346
347/////////////////////////////Replacement Helpers///////////////////////////////
348#[inline(always)]
349pub fn cpu_replace_fallback(data: &mut [u8], pattern: u8, replacement: u8) {
350    for i in 0..data.len() {
351        if data[i] == pattern {
352            data[i] = replacement;
353        }
354    }
355}
356
357#[cfg(feature = "simd")]
358#[inline(always)]
359pub fn cpu_find_replace_simd_n<const LANE_SIZE: usize>(chunk: &mut [u8], pattern: u8xN<LANE_SIZE>, replacement: u8xN<LANE_SIZE>) {
360    let simd_chunk = u8xN::<LANE_SIZE>::from_array(cpu_slice_to_array_padded::<LANE_SIZE, 0>(chunk));
361    let bitmask = simd_chunk.simd_eq(pattern);
362
363    if bitmask.any() {
364        replacement.store_select(chunk, bitmask);
365    }
366}
367
368#[cfg(feature = "simd")]
369#[inline(always)]
370pub fn cpu_replace_simd_n<const LANE_SIZE: usize>(data: &mut [u8], pattern: u8, replacement: u8) {
371    let mask = u8xN::<LANE_SIZE>::splat(pattern);
372    let simd_replacement = u8xN::<LANE_SIZE>::splat(replacement);
373
374    for chunk in data.chunks_mut(LANE_SIZE) {
375        cpu_find_replace_simd_n::<LANE_SIZE>(chunk, mask, simd_replacement);
376    }
377}
378
379#[cfg(feature = "simd")]
380#[inline(always)]
381pub fn cpu_replace_byte(data: &mut [u8], pattern: u8, replacement: u8) {
382    cpu_replace_simd_n::<CPU_SIMD_64_SIZE>(data, pattern, replacement)
383}
384
385#[cfg(not(feature = "simd"))]
386#[inline(always)]
387pub fn cpu_replace_byte(data: &mut [u8], pattern: u8, replacement: u8) {
388    cpu_replace_fallback(data, pattern, replacement)
389}
390
391/////////////////////////////GATHER ALL INDICES OF NEEDLE IN HAYSTACK///////////////////////////////
392pub type CPUTokenStackIndex<const LANE_SIZE: usize> = [u32; LANE_SIZE];
393pub type CPUTokenRelativeStackInfo<const LANE_SIZE: usize> = (usize, CPUTokenStackIndex<LANE_SIZE>);
394pub type CPUTokenIndexCollection = RUMVec<u32>;
395pub type CPUTokenIndexSet = (u8, RUMVec<u32>);
396pub type CPUTokenSet = (u8, u32);
397pub type CPUTokenSetCollection = RUMVec<CPUTokenSet>;
398
399#[inline(always)]
400pub fn cpu_collect_fallback(chunk: &[u8], byte: u8, offset: usize) -> CPUTokenIndexCollection {
401    let mut results: CPUTokenStackIndex<CPU_SIMD_64_SIZE> = [0; CPU_SIMD_64_SIZE];
402    let mut length = 0;
403
404    for i in 0..chunk.len() {
405        if chunk[i]==byte {
406            let pos = offset + i;
407            results[length] = pos as u32;
408            length += 1;
409        }
410    }
411
412    CPUTokenIndexCollection::from(&results[..length])
413}
414
415#[cfg(feature = "simd")]
416#[inline]
417fn cpu_collect_simd_avx2_n<const LANE_SIZE: usize>(data_vec: &u8xN<LANE_SIZE>, target: u8xN<LANE_SIZE>, offset: usize) -> Option<CPUTokenRelativeStackInfo<LANE_SIZE>> {
418    let mut results: CPUTokenStackIndex<LANE_SIZE> = [0; LANE_SIZE];
419    let mut length = 0;
420
421    let mask = data_vec.simd_eq(target);
422
423    if mask.any() {
424        let items = mask.to_array();
425
426        for i in 0..items.len() {
427            if items[i] {
428                let pos = offset + i;
429                results[length] = pos as u32;
430                length += 1;
431            }
432        }
433
434        return Some((length, results));
435    }
436
437    None
438}
439
440#[cfg(feature = "simd")]
441#[inline]
442pub fn cpu_collect_simd_n<const LANE_SIZE: usize>
443(
444    chunk: &[u8],
445    byte: u8,
446    offset: usize
447) -> CPUTokenIndexCollection
448{
449    let mask = u8xN::<LANE_SIZE>::splat(byte);
450    let (prefix, middle, postfix) = chunk.as_simd::<LANE_SIZE>();
451
452    let mut local_offset: usize = offset;
453    let data: CPUTokenIndexCollection = cpu_collect_fallback(prefix, byte, local_offset);
454    let mut positions: CPUTokenIndexCollection = CPUTokenIndexCollection::from(data);
455    local_offset += prefix.len();
456
457    for window in middle.into_iter() {
458        match cpu_collect_simd_avx2_n::<LANE_SIZE>(window, mask, local_offset) {
459            Some((len, data)) => {
460                positions.extend_from_slice(&data[..len]);
461            },
462            None => {},
463        };
464        local_offset += LANE_SIZE;
465    }
466
467    let data: CPUTokenIndexCollection = cpu_collect_fallback(postfix, byte, local_offset);
468    positions.extend_from_slice(&data);
469
470    positions
471}
472
473#[cfg(feature = "simd")]
474#[inline]
475pub fn cpu_collect(window: &[u8], byte: u8, offset: usize) -> CPUTokenIndexSet {
476    let indx = cpu_collect_simd_n::<CPU_SIMD_64_SIZE>(
477        window,
478        byte,
479        offset
480    );
481    (byte, indx)
482}
483
484#[cfg(not(feature = "simd"))]
485#[inline]
486pub fn cpu_collect(window: &[u8], byte: u8, offset: usize) -> CPUTokenIndexSet {
487    let indx = cpu_collect_fallback(
488        window,
489        byte,
490        offset
491    );
492    (byte, indx)
493}
494
495#[inline]
496pub fn cpu_tokenize<const WINDOW_SIZE: usize>(haystack: &[u8], bytes: &[u8]) -> CPUTokenSetCollection
497{
498    let mut results = CPUTokenSetCollection::with_capacity(haystack.len() * size_of::<CPUTokenSet>());
499    let mut offset = 0;
500
501    for window in haystack.chunks(WINDOW_SIZE) {
502        for byte in bytes {
503            let (b, indx) = cpu_collect(window, *byte, offset);
504
505            if !indx.is_empty() {
506                for tok_indx in indx {
507                    results.push((b, tok_indx));
508                }
509            }
510        }
511        offset += window.len();
512    }
513
514    results.sort_unstable_by(|a,b| a.1.cmp(&b.1));
515
516    results
517}
518
519#[inline]
520pub fn cpu_tokenize_rev<const WINDOW_SIZE: usize>(haystack: &[u8], bytes: &[u8]) -> CPUTokenSetCollection
521{
522    let reversed: Vec<u8> = bytes.iter().rev().cloned().collect();
523    cpu_tokenize::<WINDOW_SIZE>(haystack, &reversed)
524}