vzense-rust 0.4.2

High-level library for Vzense cameras
Documentation
//! Common utilities used by all APIs.

pub mod buffer_text;
pub mod color_map;
pub mod touch_detector;

use std::time::Instant;

/// Creates a new vector of length `size` with capacity set to `size` and initializes it with `init`.
pub fn new_fixed_vec<T: Clone>(size: usize, init: T) -> Vec<T> {
    let mut v = Vec::<T>::with_capacity(size);
    v.resize(size, init);
    v
}

/// A counter to be used in the main loop to get fps and frame count info.
/// `fps_frame_count_info()` will advance `count` by one and return
/// new info every `info_interval`'th time.
pub struct Counter {
    count: u64,
    now: Instant,
    info_interval: u64,
}
impl Counter {
    pub fn new(info_interval: u64) -> Self {
        Self {
            count: 0,
            now: Instant::now(),
            info_interval,
        }
    }

    pub fn fps_frame_count_info(&mut self) -> Option<String> {
        self.count += 1;
        if self.count.is_multiple_of(self.info_interval) {
            let elapsed = self.now.elapsed().as_secs_f64();
            self.now = Instant::now();
            return Some(format!(
                "{:>9.1} fps  {:>9} frames",
                self.info_interval as f64 / elapsed,
                self.count
            ));
        }
        None
    }
}

const UPSCALE: u32 = 1 << 16; // 2^16
const BIAS: u32 = 1 << 15; // 2^15

/// 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
pub fn normalize_u16_to_u8_integer_arithmetic(input: &[u8], min: u16, max: u16, norm: &mut [u8]) {
    // upscale by 2^16
    let scale = (255 * UPSCALE) / (max - min) as u32;

    for (norm, input) in std::iter::zip(norm, input.chunks_exact(2)) {
        let value = u16::from_le_bytes([input[0], input[1]]);

        let clamped = (value.clamp(min, max) - min) as u32;

        // add rounding bias of 2^15 and finally divide by 2^16
        *norm = ((clamped * scale + BIAS) >> 16) as u8;
    }
}