Skip to main content

vzense_rust/util/
mod.rs

1//! Common utilities used by all APIs.
2
3pub mod buffer_text;
4pub mod color_map;
5pub mod touch_detector;
6
7use std::time::Instant;
8
9/// Creates a new vector of length `size` with capacity set to `size` and initializes it with `init`.
10pub fn new_fixed_vec<T: Clone>(size: usize, init: T) -> Vec<T> {
11    let mut v = Vec::<T>::with_capacity(size);
12    v.resize(size, init);
13    v
14}
15
16/// A counter to be used in the main loop to get fps and frame count info.
17/// `fps_frame_count_info()` will advance `count` by one and return
18/// new info every `info_interval`'th time.
19pub struct Counter {
20    count: u64,
21    now: Instant,
22    info_interval: u64,
23}
24impl Counter {
25    pub fn new(info_interval: u64) -> Self {
26        Self {
27            count: 0,
28            now: Instant::now(),
29            info_interval,
30        }
31    }
32
33    pub fn fps_frame_count_info(&mut self) -> Option<String> {
34        self.count += 1;
35        if self.count.is_multiple_of(self.info_interval) {
36            let elapsed = self.now.elapsed().as_secs_f64();
37            self.now = Instant::now();
38            return Some(format!(
39                "{:>9.1} fps  {:>9} frames",
40                self.info_interval as f64 / elapsed,
41                self.count
42            ));
43        }
44        None
45    }
46}
47
48const UPSCALE: u32 = 1 << 16; // 2^16
49const BIAS: u32 = 1 << 15; // 2^15
50
51/// optimized function based on u32 integer arithmetic taking two consecutive u8 values as one u16 value as input and performing a normalization according to min and max
52pub fn normalize_u16_to_u8_integer_arithmetic(input: &[u8], min: u16, max: u16, norm: &mut [u8]) {
53    // upscale by 2^16
54    let scale = (255 * UPSCALE) / (max - min) as u32;
55
56    for (norm, input) in std::iter::zip(norm, input.chunks_exact(2)) {
57        let value = u16::from_le_bytes([input[0], input[1]]);
58
59        let clamped = (value.clamp(min, max) - min) as u32;
60
61        // add rounding bias of 2^15 and finally divide by 2^16
62        *norm = ((clamped * scale + BIAS) >> 16) as u8;
63    }
64}