cranpose-ui-graphics 0.30.0

Geometry, units, paths and render data for Cranpose UI
Documentation
//! The sources of runtime shaders: their hashes, and one shared copy of
//! each source text however many shaders a call site builds from it.

use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};

/// The hash [`crate::RuntimeShader::source_hash`] gives a shader built from
/// `source`.
pub fn runtime_shader_source_hash(source: &str) -> u64 {
    hash_shader_bytes(source.bytes())
}

/// The hash [`crate::DrawSpecialization::overrides_hash`] gives a non-empty
/// override set, its overrides in name order.
pub fn runtime_shader_overrides_hash<'a>(
    overrides: impl IntoIterator<Item = (&'a str, f64)>,
) -> u64 {
    hash_shader_bytes(
        overrides
            .into_iter()
            .flat_map(|(name, value)| name.bytes().chain([0]).chain(value.to_bits().to_le_bytes())),
    )
}

pub(crate) fn hash_shader_bytes(bytes: impl IntoIterator<Item = u8>) -> u64 {
    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    bytes.into_iter().fold(FNV_OFFSET_BASIS, |hash, byte| {
        (hash ^ u64::from(byte)).wrapping_mul(FNV_PRIME)
    })
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ShaderSourceCallsite {
    file: &'static str,
    line: u32,
    column: u32,
}

struct CachedShaderSource {
    callsite: ShaderSourceCallsite,
    source_hash: u64,
    source: Arc<str>,
}

struct CachedSharedShaderSourceHash {
    byte_ptr: usize,
    len: usize,
    source_hash: u64,
    source: Weak<str>,
}

pub(crate) fn cached_shared_shader_source_hash(source: &Arc<str>) -> u64 {
    static CACHE: OnceLock<Mutex<Vec<CachedSharedShaderSourceHash>>> = OnceLock::new();
    let byte_ptr = source.as_ptr() as usize;
    let len = source.len();
    let mut cache = CACHE
        .get_or_init(|| Mutex::new(Vec::new()))
        .lock()
        .unwrap_or_else(PoisonError::into_inner);

    cache.retain(|entry| entry.source.strong_count() > 0);
    if let Some(entry) = cache.iter().find(|entry| {
        entry.byte_ptr == byte_ptr
            && entry.len == len
            && entry
                .source
                .upgrade()
                .is_some_and(|cached| Arc::ptr_eq(&cached, source))
    }) {
        return entry.source_hash;
    }

    let source_hash = runtime_shader_source_hash(source);
    cache.push(CachedSharedShaderSourceHash {
        byte_ptr,
        len,
        source_hash,
        source: Arc::downgrade(source),
    });
    source_hash
}

pub(crate) fn cached_shader_source(
    location: &'static std::panic::Location<'static>,
    source: &str,
) -> (Arc<str>, u64) {
    static CACHE: OnceLock<Mutex<Vec<CachedShaderSource>>> = OnceLock::new();
    let callsite = ShaderSourceCallsite {
        file: location.file(),
        line: location.line(),
        column: location.column(),
    };
    let mut cache = CACHE
        .get_or_init(|| Mutex::new(Vec::new()))
        .lock()
        .unwrap_or_else(PoisonError::into_inner);

    if let Some(entry) = cache.iter_mut().find(|entry| entry.callsite == callsite) {
        if entry.source.as_ref() == source {
            let hit = (Arc::clone(&entry.source), entry.source_hash);
            drop(cache);
            return hit;
        }
        let source_hash = runtime_shader_source_hash(source);
        entry.source_hash = source_hash;
        entry.source = Arc::<str>::from(source);
        let hit = (Arc::clone(&entry.source), entry.source_hash);
        drop(cache);
        return hit;
    }

    let source_hash = runtime_shader_source_hash(source);
    let shared = Arc::<str>::from(source);
    cache.push(CachedShaderSource {
        callsite,
        source_hash,
        source: Arc::clone(&shared),
    });
    drop(cache);
    (shared, source_hash)
}