euv-core 0.46.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Construction helpers for `TextShapingKey`.
impl TextShapingKey {
    /// Computes dual 64-bit FNV-1a hashes over `bytes` to form a 128-bit collision-resistant digest.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input UTF-8 byte slice.
    ///
    /// # Returns
    ///
    /// - `(u64, u64)` - Dual 64-bit hash pair `(hash_a, hash_b)`.
    #[must_use]
    pub fn hash_bytes_128(bytes: &[u8]) -> (u64, u64) {
        let mut ha: u64 = SHAPING_FNV_OFFSET_A;
        let mut hb: u64 = SHAPING_FNV_OFFSET_B;
        for (idx, &b) in bytes.iter().enumerate() {
            ha ^= b as u64;
            ha = ha.wrapping_mul(SHAPING_FNV_PRIME);
            hb ^= (b as u64).wrapping_add((idx as u64).wrapping_mul(31));
            hb = hb.wrapping_mul(SHAPING_FNV_PRIME);
        }
        (ha, hb)
    }

    /// Builds a DPI- and wrap-width-independent `TextShapingKey` from `text`, `style`, locale, direction, and font-chain revision.
    ///
    /// # Arguments
    ///
    /// - `&str` - Source UTF-8 text content.
    /// - `TextStyle` - Typography style (color, alignment, and overflow are intentionally excluded).
    /// - `&str` - Active BCP-47 locale identifier.
    /// - `bool` - Whether right-to-left base direction is enabled.
    /// - `u64` - Active font fallback chain revision.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed shaping cache key.
    #[must_use]
    pub fn from_text(
        text: &str,
        style: TextStyle,
        locale: &str,
        rtl: bool,
        font_chain_revision: u64,
    ) -> Self {
        let (text_hash_a, text_hash_b): (u64, u64) = Self::hash_bytes_128(text.as_bytes());
        let (locale_hash, _): (u64, u64) = Self::hash_bytes_128(locale.as_bytes());
        Self {
            text_hash_a,
            text_hash_b,
            text_len: text.len() as u32,
            font_size_bits: style.get_font_size().to_bits(),
            family: style.get_family(),
            weight: style.get_weight(),
            italic: style.get_italic(),
            letter_spacing_bits: style.get_letter_spacing().to_bits(),
            locale_hash,
            rtl,
            font_chain_revision,
        }
    }

    /// Builds a paired `LineBreakKey` binding this shaping key to `max_width`, `line_height`, and `overflow`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Base shaping key.
    /// - `Option<f32>` - Optional logical wrap width limit.
    /// - `TextStyle` - Typography style providing `line_height` and `overflow`.
    ///
    /// # Returns
    ///
    /// - `LineBreakKey` - Line-break cache key independent of DPI scale and text color.
    #[must_use]
    pub fn line_break_key(&self, max_width: Option<f32>, style: TextStyle) -> LineBreakKey {
        let width_bits: u32 = match max_width {
            Some(w) if w.is_finite() => ((w.max(0.0) * 10.0).round() as u32).min(u32::MAX - 1),
            _ => u32::MAX,
        };
        let mut ha: u64 = self.get_text_hash_a();
        let mut hb: u64 = self.get_text_hash_b();
        let meta: u64 =
            ((self.get_font_size_bits() as u64) << 32) | (self.get_letter_spacing_bits() as u64);
        ha = (ha ^ meta).wrapping_mul(SHAPING_FNV_PRIME);
        hb = (hb ^ self.get_locale_hash() ^ ((self.get_family() as u64) << 8))
            .wrapping_mul(SHAPING_FNV_PRIME);
        LineBreakKey {
            shaping_hash_a: ha,
            shaping_hash_b: hb,
            max_width_bits: width_bits,
            line_height_bits: style.get_line_height().to_bits(),
            overflow: style.get_overflow(),
            font_chain_revision: self.get_font_chain_revision(),
        }
    }
}

/// Default bounded text shaping cache initialized with `TEXT_SHAPING_DEFAULT_BUDGET_BYTES`.
impl Default for TextShapingCache {
    /// Creates an empty bounded `TextShapingCache` with the default 4 MiB budget.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty text shaping cache.
    fn default() -> Self {
        Self::with_budget(TEXT_SHAPING_DEFAULT_BUDGET_BYTES)
    }
}

/// Split shaping & line-break caching, independent font-chain invalidation, and bounded LRU eviction for `TextShapingCache`.
impl TextShapingCache {
    /// Creates a `TextShapingCache` enforcing `budget_bytes` across shaping runs and wrapped line layouts.
    ///
    /// # Arguments
    ///
    /// - `usize` - Resident byte ceiling (clamped to `>= TEXT_SHAPING_MIN_BUDGET_BYTES`).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured empty shaping cache.
    #[must_use]
    pub fn with_budget(budget_bytes: usize) -> Self {
        Self {
            budget_bytes: budget_bytes.max(TEXT_SHAPING_MIN_BUDGET_BYTES),
            resident_bytes: 0,
            font_chain_revision: 1,
            lru_clock: 0,
            shaped_runs: HashMap::new(),
            line_breaks: HashMap::new(),
            shaping_hits: 0,
            shaping_misses: 0,
            line_break_hits: 0,
            line_break_misses: 0,
            evictions: 0,
        }
    }

    /// Updates the resident byte budget and immediately evicts cold entries if currently over budget.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `usize` - New maximum resident bytes.
    pub fn set_memory_budget(&mut self, max_bytes: usize) {
        self.set_budget_bytes(max_bytes.max(TEXT_SHAPING_MIN_BUDGET_BYTES));
        self.evict_if_over_budget();
    }

    /// Advances the font fallback chain revision and invalidates all cached shaping and line-break entries.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `u64` - New monotonic font fallback chain revision.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the revision changed and entries were invalidated.
    pub fn invalidate_font_chain(&mut self, new_revision: u64) -> bool {
        if self.get_font_chain_revision() == new_revision {
            return false;
        }
        let Self {
            font_chain_revision,
            shaped_runs,
            line_breaks,
            resident_bytes,
            ..
        } = self;
        *font_chain_revision = new_revision;
        shaped_runs.clear();
        line_breaks.clear();
        *resident_bytes = 0;
        true
    }

    /// Looks up or computes a DPI- and wrap-width-independent `ShapedGlyphRun` for `key`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `TextShapingKey` - Shaping lookup key.
    /// - `F` - Lazy shaping function returning `(cluster_advances, total_width)` on a miss.
    ///
    /// # Returns
    ///
    /// - `&ShapedGlyphRun` - Cached shaping run reference.
    pub fn get_or_shape<F>(&mut self, key: TextShapingKey, shape_fn: F) -> &ShapedGlyphRun
    where
        F: FnOnce() -> (Vec<f32>, f32),
    {
        let hit: bool = self.get_shaped_runs().contains_key(&key);
        if hit {
            let Self {
                shaped_runs,
                lru_clock,
                shaping_hits,
                ..
            } = self;
            *lru_clock = lru_clock.wrapping_add(1);
            *shaping_hits = shaping_hits.saturating_add(1);
            let tick: u64 = *lru_clock;
            if let Some(entry) = shaped_runs.get_mut(&key) {
                entry.set_last_used_tick(tick);
            }
            return &shaped_runs[&key];
        }
        let (advances, total_width): (Vec<f32>, f32) = shape_fn();
        let cluster_count: usize = advances.len();
        let entry_bytes: usize =
            TEXT_SHAPING_ENTRY_OVERHEAD_BYTES.saturating_add(cluster_count.saturating_mul(4));
        self.evict_to_make_room(entry_bytes);
        let Self {
            shaped_runs,
            resident_bytes,
            lru_clock,
            shaping_misses,
            ..
        } = self;
        *lru_clock = lru_clock.wrapping_add(1);
        *shaping_misses = shaping_misses.saturating_add(1);
        let run: ShapedGlyphRun = ShapedGlyphRun {
            cluster_advances: advances,
            total_width,
            cluster_count,
            byte_size: entry_bytes,
            last_used_tick: *lru_clock,
        };
        let _: Option<ShapedGlyphRun> = shaped_runs.insert(key, run);
        *resident_bytes = resident_bytes.saturating_add(entry_bytes);
        &shaped_runs[&key]
    }

    /// Looks up or computes a DPI- and color-independent wrapped `TextLayoutResult` for `key`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `LineBreakKey` - Line-break lookup key.
    /// - `F` - Lazy line-break computation invoked only on cache miss.
    ///
    /// # Returns
    ///
    /// - `&TextLayoutResult` - Cached wrapped layout result.
    pub fn get_or_break_lines<F>(&mut self, key: LineBreakKey, break_fn: F) -> &TextLayoutResult
    where
        F: FnOnce() -> TextLayoutResult,
    {
        let hit: bool = self.get_line_breaks().contains_key(&key);
        if hit {
            let Self {
                line_breaks,
                lru_clock,
                line_break_hits,
                ..
            } = self;
            *lru_clock = lru_clock.wrapping_add(1);
            *line_break_hits = line_break_hits.saturating_add(1);
            let tick: u64 = *lru_clock;
            if let Some(entry) = line_breaks.get_mut(&key) {
                entry.set_last_used_tick(tick);
            }
            return line_breaks[&key].get_layout();
        }
        let layout: TextLayoutResult = break_fn();
        let mut entry_bytes: usize = TEXT_SHAPING_ENTRY_OVERHEAD_BYTES;
        for line in layout.get_lines().iter() {
            entry_bytes = entry_bytes
                .saturating_add(32)
                .saturating_add(line.get_text().len());
        }
        self.evict_to_make_room(entry_bytes);
        let Self {
            line_breaks,
            resident_bytes,
            lru_clock,
            line_break_misses,
            ..
        } = self;
        *lru_clock = lru_clock.wrapping_add(1);
        *line_break_misses = line_break_misses.saturating_add(1);
        let entry: CachedLineBreakEntry = CachedLineBreakEntry {
            layout,
            byte_size: entry_bytes,
            last_used_tick: *lru_clock,
        };
        let _: Option<CachedLineBreakEntry> = line_breaks.insert(key, entry);
        *resident_bytes = resident_bytes.saturating_add(entry_bytes);
        line_breaks[&key].get_layout()
    }

    /// Evicts coldest entries across shaping and line-break tables when `resident_bytes + incoming_bytes > budget_bytes`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `usize` - Size in bytes of the incoming entry.
    fn evict_to_make_room(&mut self, incoming_bytes: usize) {
        let budget: usize = self.get_budget_bytes();
        if self.get_resident_bytes().saturating_add(incoming_bytes) <= budget {
            return;
        }
        let target: usize = budget
            .saturating_mul(3)
            .saturating_div(4)
            .saturating_sub(incoming_bytes);
        self.evict_lru_to_target(target);
    }

    /// Evicts coldest entries whenever current resident bytes exceed the configured budget.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    pub fn evict_if_over_budget(&mut self) {
        let budget: usize = self.get_budget_bytes();
        if self.get_resident_bytes() <= budget {
            return;
        }
        let target: usize = (budget.saturating_mul(3) / 4).max(TEXT_SHAPING_ENTRY_OVERHEAD_BYTES);
        self.evict_lru_to_target(target);
    }

    /// Evicts least-recently-used shaping and line-break entries until `resident_bytes <= target_bytes`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `usize` - Target post-eviction resident byte ceiling.
    fn evict_lru_to_target(&mut self, target_bytes: usize) {
        let Self {
            shaped_runs,
            line_breaks,
            resident_bytes,
            evictions,
            ..
        } = self;
        let mut victims: Vec<ShapingEvictVictim> =
            Vec::with_capacity(shaped_runs.len() + line_breaks.len());
        for (k, v) in shaped_runs.iter() {
            victims.push(ShapingEvictVictim {
                last_used_tick: v.get_last_used_tick(),
                is_shape: true,
                shape_key: *k,
                line_break_key: LineBreakKey::default(),
                byte_size: v.get_byte_size(),
            });
        }
        for (k, v) in line_breaks.iter() {
            victims.push(ShapingEvictVictim {
                last_used_tick: v.get_last_used_tick(),
                is_shape: false,
                shape_key: TextShapingKey::default(),
                line_break_key: *k,
                byte_size: v.get_byte_size(),
            });
        }
        victims.sort_unstable_by_key(|item: &ShapingEvictVictim| item.last_used_tick);
        for victim in victims.into_iter() {
            if *resident_bytes <= target_bytes {
                break;
            }
            if victim.is_shape {
                if shaped_runs.remove(&victim.shape_key).is_some() {
                    *resident_bytes = resident_bytes.saturating_sub(victim.byte_size);
                    *evictions = evictions.saturating_add(1);
                }
            } else if line_breaks.remove(&victim.line_break_key).is_some() {
                *resident_bytes = resident_bytes.saturating_sub(victim.byte_size);
                *evictions = evictions.saturating_add(1);
            }
        }
    }

    /// Returns total cached entry count combining shaping runs and wrapped line-break entries.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Shaping cache reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Total cached entries.
    #[must_use]
    pub fn total_entries(&self) -> usize {
        self.get_shaped_runs()
            .len()
            .saturating_add(self.get_line_breaks().len())
    }
}