app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
[package]
name = "rune-taffy"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Compact retained layout store driving Taffy's Flexbox, Grid, and Block solvers for Rune."
[features]
default = []
# Use upstream `taffy::TaffyTree` instead of `LayoutStore` for A/B benchmarks and parity checks.
# Upstream `taffy::Style` has no `whole_rows` bit, so `whole_rows` trees lay out unrounded here.
baseline-taffy = []
[dependencies]
taffy = { workspace = true, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "content_size"] }
[target.'cfg(any(windows, target_os = "macos", target_os = "linux"))'.dependencies]
stacker = "0.1"
[lints]
workspace = true
+380
View File
@@ -0,0 +1,380 @@
//! Upstream `taffy::TaffyTree` wrapper implementing the [`crate::LayoutStore`] commit interface
//! for `--features baseline-taffy` parity checks and A/B benchmarks (`taffy::Style` has no
//! `whole_rows` bit, so `whole_rows` columns lay out without rounding under this feature).
#![allow(clippy::unwrap_used)]
#![forbid(unsafe_code)]
use std::collections::HashMap;
use taffy::geometry::Size;
use taffy::style::{AvailableSpace, Style};
use taffy::tree::{DetailedLayoutInfo, Layout, LayoutInput, LayoutOutput, NodeId, TraversePartialTree};
use crate::BaselineTaffyTree;
use crate::store::{BoxLayout, SlotId, StorageStats};
use crate::style::CompactStyle;
/// Estimates retained heap bytes for a baseline `taffy::TaffyTree<NodeContext>` with `live_nodes`
/// and `peak_nodes`, accounting for `SlotMap`'s power-of-two slot buffers (`nodes`, `children`,
/// `parents`, `node_context_data`) and per-container `Vec<NodeId>` allocations.
pub fn baseline_storage_stats<NodeContext>(
tree: &taffy::TaffyTree<NodeContext>,
root: Option<NodeId>,
peak_nodes: usize,
) -> StorageStats {
let live_nodes = tree.total_node_count();
let slot_cap = peak_nodes.max(live_nodes).max(16).next_power_of_two();
let node_data_bytes = core::mem::size_of::<Style>()
+ core::mem::size_of::<taffy::Cache>()
+ 2 * core::mem::size_of::<Layout>()
+ core::mem::size_of::<Vec<NodeId>>()
+ core::mem::size_of::<DetailedLayoutInfo>()
+ 16;
let children_slot_bytes = core::mem::size_of::<Vec<NodeId>>() + 8;
let parents_slot_bytes = core::mem::size_of::<Option<NodeId>>() + 8;
let context_slot_bytes = core::mem::size_of::<NodeContext>() + 16;
let bytes_per_slot = node_data_bytes + children_slot_bytes + parents_slot_bytes + context_slot_bytes;
let inline_buffer_bytes = slot_cap * bytes_per_slot;
let mut child_heap_bytes = 0usize;
if let Some(root_id) = root {
let mut stack = vec![root_id];
while let Some(id) = stack.pop() {
let count = tree.child_count(id);
if count > 0 {
let cap = count.max(4).next_power_of_two();
child_heap_bytes += cap * core::mem::size_of::<NodeId>();
for i in 0..count {
stack.push(tree.get_child_id(id, i));
}
}
}
}
StorageStats {
live_nodes,
slot_capacity: slot_cap,
sparse_capacity: slot_cap,
bytes_per_slot,
inline_buffer_bytes,
child_heap_bytes,
cold_style_bytes: 0,
cold_cache_bytes: 0,
cold_aux_bytes: 0,
total_retained_bytes: inline_buffer_bytes + child_heap_bytes,
}
}
#[derive(Debug, Clone)]
struct BaselineSlot {
taffy_id: NodeId,
style: CompactStyle,
measure: Option<u64>,
node_idx: u32,
used: bool,
mutated: bool,
}
/// Drop-in `LayoutStore` equivalent backed by upstream `taffy::TaffyTree<usize>`.
#[derive(Debug, Clone)]
pub struct BaselineLayoutStore {
tree: BaselineTaffyTree<usize>,
slots: Vec<Option<BaselineSlot>>,
by_key: HashMap<u64, u32>,
free: Vec<u32>,
child_scratch: Vec<u32>,
last_root: Option<NodeId>,
peak_nodes: usize,
}
impl Default for BaselineLayoutStore {
fn default() -> Self {
Self::new()
}
}
impl BaselineLayoutStore {
#[must_use]
pub fn new() -> Self {
Self::with_capacity(32)
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
let mut tree = BaselineTaffyTree::with_capacity(capacity);
tree.disable_rounding();
Self {
tree,
slots: Vec::with_capacity(capacity),
by_key: HashMap::with_capacity(capacity),
free: Vec::new(),
child_scratch: Vec::with_capacity(64),
last_root: None,
peak_nodes: 0,
}
}
#[inline]
pub fn live_count(&self) -> usize {
self.by_key.len()
}
pub fn begin_commit(&mut self) {
self.child_scratch.clear();
for s in self.slots.iter_mut().flatten() {
s.used = false;
}
}
#[inline(always)]
pub fn begin_children(&self) -> usize {
self.child_scratch.len()
}
#[inline(always)]
pub fn push_child(&mut self, child: SlotId) {
self.child_scratch.push(child.0);
}
#[inline]
pub fn can_reuse(&self, key: u64, slot: SlotId) -> bool {
self.by_key.get(&key) == Some(&slot.0)
&& self
.slots
.get(slot.0 as usize)
.and_then(Option::as_ref)
.is_some_and(|e| !e.used && !e.mutated)
}
#[inline]
pub fn is_used_this_commit(&self, key: u64) -> bool {
self.by_key.get(&key).is_some_and(|&s| {
self.slots
.get(s as usize)
.and_then(Option::as_ref)
.is_some_and(|e| e.used)
})
}
#[inline]
pub fn reuse_slot(&mut self, slot: SlotId, node_idx: u32) {
let entry = self.slots[slot.0 as usize].as_mut().unwrap();
entry.used = true;
entry.node_idx = node_idx;
if entry.measure.is_some() {
*self.tree.get_node_context_mut(entry.taffy_id).unwrap() = node_idx as usize;
}
}
pub fn rekey_and_reuse_batch(
&mut self,
items: impl ExactSizeIterator<Item = (u64, u64, SlotId, u32)> + Clone,
) {
let mut first = true;
for (old_key, _, slot, _) in items.clone() {
if first {
first = false;
let tid = self.slots[slot.0 as usize].as_ref().unwrap().taffy_id;
if let Some(old_p) = self.tree.parent(tid) {
drop(self.tree.remove_child(old_p, tid));
}
}
let removed = self.by_key.remove(&old_key);
debug_assert_eq!(removed, Some(slot.0));
}
for (_, new_key, slot, node_idx) in items {
if let Some(stale) = self.by_key.remove(&new_key) {
if let Some(old) = self.slots[stale as usize].take() {
drop(self.tree.set_children(old.taffy_id, &[]));
self.tree.remove(old.taffy_id).unwrap();
}
self.free.push(stale);
}
self.by_key.insert(new_key, slot.0);
self.reuse_slot(slot, node_idx);
}
}
#[allow(clippy::too_many_arguments)]
pub fn sync_node(
&mut self,
key: u64,
node_idx: u32,
style: CompactStyle,
measure: Option<u64>,
force_measure_dirty: bool,
child_mark: usize,
_children_dirty: bool,
) -> (SlotId, bool) {
let kids: Vec<NodeId> = self.child_scratch[child_mark..]
.iter()
.map(|&s| self.slots[s as usize].as_ref().unwrap().taffy_id)
.collect();
self.child_scratch.truncate(child_mark);
let me = node_idx as usize;
let measured = measure.is_some();
if let Some(&s) = self.by_key.get(&key) {
let slot = self.slots[s as usize].as_mut().unwrap();
let id = slot.taffy_id;
let mut dirty = false;
if slot.style != style {
self.tree.set_style(id, style.to_style()).unwrap();
slot.style = style;
dirty = true;
}
if !self.tree.child_ids(id).eq(kids.iter().copied()) {
self.tree.set_children(id, &kids).unwrap();
dirty = true;
}
if slot.measure.is_some() != measured {
self.tree.set_node_context(id, measured.then_some(me)).unwrap();
dirty = true;
} else if measured {
*self.tree.get_node_context_mut(id).unwrap() = me;
}
if force_measure_dirty || slot.measure != measure {
self.tree.mark_dirty(id).unwrap();
dirty = true;
}
if dirty {
slot.mutated = true;
}
slot.measure = measure;
slot.node_idx = node_idx;
slot.used = true;
(SlotId(s), dirty)
} else {
let full = style.to_style();
let id = if !kids.is_empty() {
self.tree.new_with_children(full, &kids).unwrap()
} else if measured {
self.tree.new_leaf_with_context(full, me).unwrap()
} else {
self.tree.new_leaf(full).unwrap()
};
if measured && self.tree.get_node_context(id).is_none() {
self.tree.set_node_context(id, Some(me)).unwrap();
}
let entry = BaselineSlot {
taffy_id: id,
style,
measure,
node_idx,
used: true,
mutated: true,
};
let s = if let Some(free_s) = self.free.pop() {
self.slots[free_s as usize] = Some(entry);
free_s
} else {
let s = self.slots.len() as u32;
self.slots.push(Some(entry));
s
};
self.by_key.insert(key, s);
(SlotId(s), true)
}
}
pub fn finish_flatten(&mut self) {
self.peak_nodes = self.peak_nodes.max(self.by_key.len());
let Self {
tree,
slots,
by_key,
free,
..
} = self;
by_key.retain(|_, &mut s| {
let keep = slots[s as usize].as_ref().is_some_and(|e| e.used);
if !keep {
if let Some(old) = slots[s as usize].take() {
tree.remove(old.taffy_id).unwrap();
}
free.push(s);
}
keep
});
self.peak_nodes = self.peak_nodes.max(self.by_key.len());
}
pub fn compact_if_sparse(&mut self, _remap: impl FnMut(u32, SlotId)) {
for s in self.slots.iter_mut().flatten() {
s.mutated = false;
}
}
pub fn end_commit(&mut self, _root: &mut SlotId, _remap: impl FnMut(u32, SlotId)) {
self.finish_flatten();
for s in self.slots.iter_mut().flatten() {
s.mutated = false;
}
}
#[inline]
pub fn style(&self, id: SlotId) -> &CompactStyle {
&self.slots[id.0 as usize].as_ref().unwrap().style
}
#[inline]
pub fn box_layout(&self, id: SlotId) -> BoxLayout {
let tid = self.slots[id.0 as usize].as_ref().unwrap().taffy_id;
BoxLayout::from_taffy(self.tree.layout(tid).unwrap())
}
#[inline]
pub fn mounted_node_index(&self, key: u64) -> Option<usize> {
let &s = self.by_key.get(&key)?;
let slot = self.slots.get(s as usize)?.as_ref()?;
slot.used.then_some(slot.node_idx as usize)
}
pub fn measure_hash(&self, key: u64) -> Option<Option<u64>> {
let &s = self.by_key.get(&key)?;
Some(self.slots[s as usize].as_ref()?.measure)
}
pub fn set_style_and_mark_ancestors(
&mut self,
id: SlotId,
style: CompactStyle,
_ancestors: impl IntoIterator<Item = SlotId>,
) {
let slot = self.slots[id.0 as usize].as_mut().unwrap();
self.tree.set_style(slot.taffy_id, style.to_style()).unwrap();
slot.style = style;
slot.mutated = true;
}
pub fn mark_dirty_and_ancestors(&mut self, id: SlotId, _ancestors: impl IntoIterator<Item = SlotId>) {
let tid = self.slots[id.0 as usize].as_ref().unwrap().taffy_id;
drop(self.tree.mark_dirty(tid));
}
pub fn mark_all_dirty(&mut self) {
for s in self.slots.iter().flatten() {
if s.measure.is_some() {
drop(self.tree.mark_dirty(s.taffy_id));
}
}
}
pub fn compute_layout<F>(&mut self, root: SlotId, available_space: Size<AvailableSpace>, mut measure_leaf: F)
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
let root_id = self.slots[root.0 as usize].as_ref().unwrap().taffy_id;
self.last_root = Some(root_id);
self.tree
.compute_layout_with_measure(root_id, available_space, |inputs, _id, ctx, style| {
let cs = CompactStyle::from_style(style.clone());
measure_leaf(inputs, ctx.copied(), &cs)
})
.unwrap();
}
pub fn storage_stats(&self) -> StorageStats {
baseline_storage_stats(&self.tree, self.last_root, self.peak_nodes.max(self.by_key.len()))
}
}
+505
View File
@@ -0,0 +1,505 @@
//! Compact layout cache (96 bytes inline vs 408 bytes in `taffy::Cache`) with the exact 9-slot
//! second-chance clock semantics of `taffy::Cache`.
//!
//! Stores the final-layout entry and the first two `ComputeSize` entries inline (since Flexbox
//! measures a child at most twice per pass), and lazily allocates slots 2..9 or cold final-layout
//! fields (`oof_candidates`, non-zero top/left overflow, `baselines.last`, collapsible margins)
//! only when needed.
#![forbid(unsafe_code)]
use taffy::geometry::{Point, Rect, Size};
use taffy::style::AvailableSpace;
use taffy::tree::{
Baselines, ClearState, CollapsibleMarginSet, LayoutInput, LayoutOutput, OofCandidates, RequestedAxis, RunMode,
SizingMode,
};
const CACHE_SIZE: usize = 9;
const INLINE_MEASURES: usize = 2;
const OVERFLOW_MEASURES: usize = CACHE_SIZE - INLINE_MEASURES;
const MEASURE_MASK_BITS: u32 = (1 << CACHE_SIZE) - 1; // bits 0..9
const FINAL_VALID_BIT: u32 = 1 << 9; // bit 9
const VALID_BITS_MASK: u32 = MEASURE_MASK_BITS | FINAL_VALID_BIT; // bits 0..10
const RECENT_SHIFT: u32 = 10; // bits 10..19
const NEXT_SHIFT: u32 = 19; // bits 19..23 (0..9)
const MODE_SHIFT: u32 = 23; // bits 23..26 (0..8)
const M0_DEF_SHIFT: u32 = 26; // bits 26..28
const M1_DEF_SHIFT: u32 = 28; // bits 28..30
const FINAL_DEF_SHIFT: u32 = 30; // bits 30..32
const INFINITY_BITS: u32 = f32::INFINITY.to_bits();
const NEG_INFINITY_BITS: u32 = f32::NEG_INFINITY.to_bits();
const SIGN_BIT_1: u64 = 1u64 << 63;
const SIGN_BIT_2: u64 = 1u64 << 31;
const BOTH_SIGN_BITS_MASK: u64 = SIGN_BIT_1 | SIGN_BIT_2;
const NON_SIGN_BITS_MASK: u64 = !BOTH_SIGN_BITS_MASK;
const X_AXIS_VALUE_MASK: u64 = (u32::MAX as u64) << 32;
#[inline(always)]
fn option_cache_key(input: Option<f32>) -> u32 {
match input {
Some(value) => value.to_bits(),
None => INFINITY_BITS,
}
}
#[inline(always)]
fn size_option_cache_key(input: Size<Option<f32>>) -> u64 {
(option_cache_key(input.width) as u64) << 32 | option_cache_key(input.height) as u64
}
#[inline(always)]
fn available_space_cache_key(input: AvailableSpace) -> u32 {
match input {
AvailableSpace::Definite(value) => (-value).to_bits(),
AvailableSpace::MinContent => NEG_INFINITY_BITS,
AvailableSpace::MaxContent => INFINITY_BITS,
}
}
#[inline(always)]
fn mixed_cache_key(kd: Option<f32>, avs: AvailableSpace) -> u32 {
kd.map(f32::to_bits).unwrap_or_else(|| available_space_cache_key(avs))
}
#[inline(always)]
fn size_mixed_cache_key(kd: Size<Option<f32>>, avs: Size<AvailableSpace>) -> u64 {
(mixed_cache_key(kd.width, avs.width) as u64) << 32 | mixed_cache_key(kd.height, avs.height) as u64
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CacheKey {
kd_available_space: u64,
parent_size: u64,
kd_def: u8,
}
impl CacheKey {
#[inline(always)]
fn from_input(input: &LayoutInput) -> Self {
let extra_bits = match input.axis {
RequestedAxis::Horizontal => SIGN_BIT_1,
RequestedAxis::Vertical => SIGN_BIT_2,
RequestedAxis::Both => SIGN_BIT_1 | SIGN_BIT_2,
};
let def_w = input.known_dimensions_are_definite.width || input.known_dimensions.width.is_none();
let def_h = input.known_dimensions_are_definite.height || input.known_dimensions.height.is_none();
Self {
kd_available_space: size_mixed_cache_key(input.known_dimensions, input.available_space),
parent_size: (size_option_cache_key(input.parent_size) & NON_SIGN_BITS_MASK) | extra_bits,
kd_def: (def_w as u8) | ((def_h as u8) << 1),
}
}
#[inline(always)]
fn x_axis_parent_size(parent_size: u64) -> u64 {
parent_size & (X_AXIS_VALUE_MASK & NON_SIGN_BITS_MASK)
}
#[inline(always)]
fn requested_axis_bits(parent_size: u64) -> u64 {
parent_size & BOTH_SIGN_BITS_MASK
}
#[inline(always)]
fn size_is_valid_for(entry_parent_size: u64, query_parent_size: u64) -> bool {
let entry_axis = Self::requested_axis_bits(entry_parent_size);
entry_axis == BOTH_SIGN_BITS_MASK || entry_axis == Self::requested_axis_bits(query_parent_size)
}
}
#[inline(always)]
fn cache_mode(input: &LayoutInput) -> u8 {
let inherent = matches!(input.sizing_mode, SizingMode::InherentSize) as u8;
let c = input.vertical_margins_are_collapsible;
inherent | ((c.start as u8) << 1) | ((c.end as u8) << 2)
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct CompactMeasureEntry {
kd_available_space: u64,
parent_size: u64,
size: Size<f32>,
}
impl CompactMeasureEntry {
const ZERO: Self = Self {
kd_available_space: 0,
parent_size: 0,
size: Size::ZERO,
};
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct CompactFinalEntry {
kd_available_space: u64,
parent_size: u64,
size: Size<f32>,
overflow_br: Size<f32>,
baseline_first: f32,
meta: u32,
}
impl CompactFinalEntry {
const ZERO: Self = Self {
kd_available_space: 0,
parent_size: 0,
size: Size::ZERO,
overflow_br: Size::ZERO,
baseline_first: f32::NAN,
meta: 0,
};
}
#[derive(Debug, Clone, PartialEq)]
struct ColdFinalOutput {
overflow_lt: Point<f32>,
baseline_last: Option<f32>,
top_margin: CollapsibleMarginSet,
bottom_margin: CollapsibleMarginSet,
margins_can_collapse_through: bool,
oof_candidates: OofCandidates,
}
#[derive(Debug, Clone, PartialEq)]
struct CacheOverflow {
measures: [CompactMeasureEntry; OVERFLOW_MEASURES],
/// 2-bit `kd_def` for overflow slots `2..9` (14 bits used).
kd_defs: u16,
cold_final: Option<ColdFinalOutput>,
}
impl Default for CacheOverflow {
fn default() -> Self {
Self {
measures: [CompactMeasureEntry::ZERO; OVERFLOW_MEASURES],
kd_defs: 0,
cold_final: None,
}
}
}
/// Compact per-node layout cache (96 bytes inline).
#[derive(Debug, Clone, PartialEq)]
pub struct CompactCache {
final_entry: CompactFinalEntry,
measures: [CompactMeasureEntry; INLINE_MEASURES],
overflow: Option<Box<CacheOverflow>>,
}
const _: () = assert!(core::mem::size_of::<CompactCache>() <= 96);
#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<CompactCache>() == 96);
impl Default for CompactCache {
fn default() -> Self {
Self::new()
}
}
impl CompactCache {
pub const fn new() -> Self {
Self {
final_entry: CompactFinalEntry::ZERO,
measures: [CompactMeasureEntry::ZERO; INLINE_MEASURES],
overflow: None,
}
}
#[inline(always)]
fn kd_def(&self, slot: usize) -> u8 {
match slot {
0 => ((self.final_entry.meta >> M0_DEF_SHIFT) & 0b11) as u8,
1 => ((self.final_entry.meta >> M1_DEF_SHIFT) & 0b11) as u8,
CACHE_SIZE => ((self.final_entry.meta >> FINAL_DEF_SHIFT) & 0b11) as u8,
_ => self
.overflow
.as_ref()
.map_or(0, |ov| ((ov.kd_defs >> ((slot - INLINE_MEASURES) * 2)) & 0b11) as u8),
}
}
#[inline(always)]
fn set_kd_def(&mut self, slot: usize, kd_def: u8) {
let bits = (kd_def & 0b11) as u32;
match slot {
0 => self.final_entry.meta = (self.final_entry.meta & !(0b11 << M0_DEF_SHIFT)) | (bits << M0_DEF_SHIFT),
1 => self.final_entry.meta = (self.final_entry.meta & !(0b11 << M1_DEF_SHIFT)) | (bits << M1_DEF_SHIFT),
CACHE_SIZE => {
self.final_entry.meta = (self.final_entry.meta & !(0b11 << FINAL_DEF_SHIFT)) | (bits << FINAL_DEF_SHIFT);
}
_ => {
let shift = (slot - INLINE_MEASURES) * 2;
let ov = self.overflow.get_or_insert_with(Default::default);
ov.kd_defs = (ov.kd_defs & !(0b11 << shift)) | ((bits as u16) << shift);
}
}
}
#[inline(always)]
fn next_measure_entry(&self) -> u8 {
((self.final_entry.meta >> NEXT_SHIFT) & 0xF) as u8
}
#[inline(always)]
fn set_next_measure_entry(&mut self, next: u8) {
self.final_entry.meta =
(self.final_entry.meta & !(0xF << NEXT_SHIFT)) | (((next & 0xF) as u32) << NEXT_SHIFT);
}
#[inline(always)]
fn mode(&self) -> u8 {
((self.final_entry.meta >> MODE_SHIFT) & 0x7) as u8
}
#[inline(always)]
fn set_mode(&mut self, mode: u8) {
self.final_entry.meta =
(self.final_entry.meta & !(0x7 << MODE_SHIFT)) | (((mode & 0x7) as u32) << MODE_SHIFT);
}
#[inline(always)]
fn measure_slot(&self, index: usize) -> Option<&CompactMeasureEntry> {
if index < INLINE_MEASURES {
Some(&self.measures[index])
} else {
self.overflow.as_ref().map(|ov| &ov.measures[index - INLINE_MEASURES])
}
}
#[inline(always)]
fn measure_slot_mut(&mut self, index: usize) -> &mut CompactMeasureEntry {
if index < INLINE_MEASURES {
&mut self.measures[index]
} else {
&mut self.overflow.get_or_insert_with(Default::default).measures[index - INLINE_MEASURES]
}
}
#[inline]
pub fn get(&mut self, input: &LayoutInput) -> Option<LayoutOutput> {
let meta = self.final_entry.meta;
if (meta & VALID_BITS_MASK) == 0 || self.mode() != cache_mode(input) {
return None;
}
let key = CacheKey::from_input(input);
match input.run_mode {
RunMode::PerformLayout => {
if (meta & FINAL_VALID_BIT) == 0 {
return None;
}
if self.final_entry.kd_available_space != key.kd_available_space
|| self.final_entry.parent_size != key.parent_size
|| self.kd_def(CACHE_SIZE) != key.kd_def
{
return None;
}
let by0 = self.final_entry.baseline_first;
let cold = self.overflow.as_ref().and_then(|ov| ov.cold_final.as_ref());
let (lt, baseline_last) = match cold {
Some(c) => (c.overflow_lt, c.baseline_last),
None => (Point::ZERO, None),
};
let baselines = Baselines {
first: (!by0.is_nan()).then_some(by0),
last: baseline_last,
};
let rect = Rect {
left: lt.x,
top: lt.y,
right: self.final_entry.overflow_br.width,
bottom: self.final_entry.overflow_br.height,
};
let mut out = LayoutOutput::from_sizes_and_baselines(self.final_entry.size, rect, baselines);
if let Some(c) = cold {
out.top_margin = c.top_margin;
out.bottom_margin = c.bottom_margin;
out.margins_can_collapse_through = c.margins_can_collapse_through;
out.oof_candidates = c.oof_candidates.clone();
}
Some(out)
}
RunMode::ComputeSize => {
let measure_mask = meta & MEASURE_MASK_BITS;
if measure_mask == 0 {
return None;
}
if self.overflow.is_none() {
if (measure_mask & 1) != 0 {
let entry = &self.measures[0];
if entry.kd_available_space == key.kd_available_space
&& self.kd_def(0) == key.kd_def
&& CacheKey::x_axis_parent_size(entry.parent_size)
== CacheKey::x_axis_parent_size(key.parent_size)
&& CacheKey::size_is_valid_for(entry.parent_size, key.parent_size)
{
self.final_entry.meta |= 1 << RECENT_SHIFT;
return Some(LayoutOutput::from_outer_size(entry.size));
}
}
if (measure_mask & 2) != 0 {
let entry = &self.measures[1];
if entry.kd_available_space == key.kd_available_space
&& self.kd_def(1) == key.kd_def
&& CacheKey::x_axis_parent_size(entry.parent_size)
== CacheKey::x_axis_parent_size(key.parent_size)
&& CacheKey::size_is_valid_for(entry.parent_size, key.parent_size)
{
self.final_entry.meta |= 2 << RECENT_SHIFT;
return Some(LayoutOutput::from_outer_size(entry.size));
}
}
return None;
}
for index in 0..CACHE_SIZE {
if (measure_mask & (1 << index)) == 0 {
continue;
}
let Some(entry) = self.measure_slot(index) else { continue };
if entry.kd_available_space == key.kd_available_space
&& self.kd_def(index) == key.kd_def
&& CacheKey::x_axis_parent_size(entry.parent_size)
== CacheKey::x_axis_parent_size(key.parent_size)
&& CacheKey::size_is_valid_for(entry.parent_size, key.parent_size)
{
let size = entry.size;
self.final_entry.meta |= 1 << (RECENT_SHIFT + index as u32);
return Some(LayoutOutput::from_outer_size(size));
}
}
None
}
RunMode::PerformHiddenLayout => None,
}
}
pub fn store(&mut self, input: &LayoutInput, layout_output: LayoutOutput) {
if input.run_mode == RunMode::PerformHiddenLayout {
return;
}
let mode = cache_mode(input);
if self.mode() != mode {
self.clear();
self.set_mode(mode);
}
let key = CacheKey::from_input(input);
match input.run_mode {
RunMode::PerformLayout => {
self.final_entry.meta |= FINAL_VALID_BIT;
self.set_kd_def(CACHE_SIZE, key.kd_def);
let meta = self.final_entry.meta;
let r = layout_output.scrollable_overflow_rect;
self.final_entry = CompactFinalEntry {
kd_available_space: key.kd_available_space,
parent_size: key.parent_size,
size: layout_output.size,
overflow_br: Size {
width: r.right,
height: r.bottom,
},
baseline_first: layout_output.baselines.first.unwrap_or(f32::NAN),
meta,
};
let needs_cold = r.left != 0.0
|| r.top != 0.0
|| layout_output.baselines.last.is_some()
|| layout_output.margins_can_collapse_through
|| layout_output.top_margin != CollapsibleMarginSet::ZERO
|| layout_output.bottom_margin != CollapsibleMarginSet::ZERO
|| !layout_output.oof_candidates.is_empty();
if needs_cold {
self.overflow.get_or_insert_with(Default::default).cold_final = Some(ColdFinalOutput {
overflow_lt: Point { x: r.left, y: r.top },
baseline_last: layout_output.baselines.last,
top_margin: layout_output.top_margin,
bottom_margin: layout_output.bottom_margin,
margins_can_collapse_through: layout_output.margins_can_collapse_through,
oof_candidates: layout_output.oof_candidates,
});
} else if let Some(ov) = &mut self.overflow {
ov.cold_final = None;
}
}
RunMode::ComputeSize => {
if layout_output.margins_can_collapse_through
|| layout_output.top_margin != CollapsibleMarginSet::ZERO
|| layout_output.bottom_margin != CollapsibleMarginSet::ZERO
{
return;
}
let measure_mask = self.final_entry.meta & MEASURE_MASK_BITS;
if measure_mask != 0 {
let limit = if self.overflow.is_some() { CACHE_SIZE } else { INLINE_MEASURES };
for index in 0..limit {
if (measure_mask & (1 << index)) == 0 {
continue;
}
if let Some(entry) = self.measure_slot(index)
&& entry.kd_available_space == key.kd_available_space
&& entry.parent_size == key.parent_size
&& self.kd_def(index) == key.kd_def
{
self.measure_slot_mut(index).size = layout_output.size;
self.final_entry.meta |= 1 << (RECENT_SHIFT + index as u32);
return;
}
}
}
let mut next = self.next_measure_entry();
while (self.final_entry.meta & (1 << (RECENT_SHIFT + next as u32))) != 0 {
self.final_entry.meta &= !(1 << (RECENT_SHIFT + next as u32));
next += 1;
if next == CACHE_SIZE as u8 {
next = 0;
}
}
let entry_index = next as usize;
self.final_entry.meta |= (1 << entry_index) | (1 << (RECENT_SHIFT + entry_index as u32));
self.set_kd_def(entry_index, key.kd_def);
*self.measure_slot_mut(entry_index) = CompactMeasureEntry {
kd_available_space: key.kd_available_space,
parent_size: key.parent_size,
size: layout_output.size,
};
next += 1;
if next == CACHE_SIZE as u8 {
next = 0;
}
self.set_next_measure_entry(next);
}
RunMode::PerformHiddenLayout => {}
}
}
#[inline]
pub fn clear(&mut self) -> ClearState {
if (self.final_entry.meta & VALID_BITS_MASK) == 0 {
return ClearState::AlreadyEmpty;
}
// Keep `mode` bits intact (same as upstream `taffy::Cache::clear`), clear valid + recent + next + kd_def.
self.final_entry.meta &= 0x7 << MODE_SHIFT;
if let Some(ov) = &mut self.overflow {
ov.kd_defs = 0;
ov.cold_final = None;
}
ClearState::Cleared
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
(self.final_entry.meta & VALID_BITS_MASK) == 0
}
pub fn heap_bytes(&self) -> usize {
self.overflow.as_ref().map_or(0, |ov| {
let oof_bytes = ov
.cold_final
.as_ref()
.map_or(0, |c| core::mem::size_of_val(c.oof_candidates.as_slice()));
core::mem::size_of::<CacheOverflow>() + oof_bytes
})
}
}
+37
View File
@@ -0,0 +1,37 @@
//! Compact retained layout store (`LayoutStore`) driving Taffy 0.15's solver directly.
//!
//! Keeps Taffy's Flexbox, CSS Grid, Block, out-of-flow positioning, and intrinsic sizing
//! algorithms while replacing `TaffyTree`'s `SlotMap`s, 552-byte inline `Style`, 408-byte
//! inline `Cache`, dual 92-byte `Layout`s, and per-node child `Vec`s with 216-byte dense
//! `RetainedSlot`s, 64-byte `CompactStyle`, 96-byte `CompactCache`, and flat child arenas.
// Every module except Windows' `SetThreadStackGuarantee` FFI in `stack` forbids `unsafe`.
#![cfg_attr(not(windows), forbid(unsafe_code))]
mod baseline_store;
mod cache;
pub mod prelude;
mod stack;
mod store;
mod style;
#[cfg(test)]
mod tests;
mod view;
pub use baseline_store::BaselineLayoutStore;
pub use baseline_store::baseline_storage_stats;
pub use cache::CompactCache;
pub use stack::stack_grow_count;
pub use store::BoxLayout;
pub use store::LayoutStore;
pub use store::SlotChildIter;
pub use store::SlotId;
pub use store::StorageStats;
pub use style::CompactStyle;
pub use taffy::TaffyTree as BaselineTaffyTree;
#[cfg(not(feature = "baseline-taffy"))]
pub type LayoutEngine = LayoutStore;
#[cfg(feature = "baseline-taffy")]
pub type LayoutEngine = BaselineLayoutStore;
+27
View File
@@ -0,0 +1,27 @@
//! Drop-in prelude matching `taffy::prelude`, re-exporting [`crate::LayoutEngine`] and compact types.
#![forbid(unsafe_code)]
pub use crate::{BoxLayout, CompactStyle, LayoutEngine, SlotId};
pub use taffy::{
geometry::{Line, Rect, Size},
style::{
AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, AvailableSpace,
BoxSizing, CompactLength, Dimension, Display, FlexboxItemStyle, JustifyContent, JustifyItems, JustifySelf,
LengthPercentage, LengthPercentageAuto, Position, Style,
},
style_helpers::{
FromFr, FromLength, FromPercent, TaffyAuto, TaffyFitContent, TaffyMaxContent, TaffyMinContent, TaffyZero, auto,
fit_content, length, max_content, min_content, percent, zero,
},
tree::{Layout, LayoutPartialTree, NodeId, PrintTree, RoundTree, TraversePartialTree, TraverseTree},
};
pub use taffy::style::{FlexDirection, FlexWrap};
pub use taffy::style::{
GridAutoFlow, GridPlacement, GridTemplateComponent, MaxTrackSizingFunction, MinTrackSizingFunction,
RepetitionCount, TrackSizingFunction,
};
pub use taffy::style_helpers::{
TaffyGridLine, TaffyGridSpan, evenly_sized_tracks, flex, fr, line, minmax, repeat, span,
};
+73
View File
@@ -0,0 +1,73 @@
//! Stack segment continuation for deep recursive container layout.
use std::sync::atomic::{AtomicU64, Ordering};
/// Minimum remaining stack bytes before continuing container layout on a new stack segment.
///
/// Sized with ~3× headroom above the largest measured leaf call chain under
/// `LayoutStoreView::compute_child_layout_inner` on x86_64 (~5.3 KiB Taffy container frame +
/// ~9 KiB Parley shaping/line-breaking + 16 KiB `skrifa` outline scratch + OS/unwind slack ≈
/// 44 KiB; `8 KiB` of the margin also absorbs the `16 KiB` fiber stack guarantee on Windows),
/// while leaving ~720 KiB on a 1 MiB thread stack so ordinary trees up to ~50 nested list levels
/// (~150 flex nodes) allocate zero segments.
#[cfg_attr(not(any(windows, target_os = "macos", target_os = "linux")), allow(dead_code))]
pub(crate) const STACK_RED_ZONE: usize = 128 * 1024;
/// Size argument passed to `stacker::grow` when remaining stack drops below [`STACK_RED_ZONE`].
///
/// On macOS and Linux, `stacker` maps `1 MiB` demand-paged with guard pages at both ends. On
/// Windows, `CreateFiber` commits `1 MiB` up front and reserves the executable's default stack
/// size (`/STACK`).
#[cfg_attr(not(any(windows, target_os = "macos", target_os = "linux")), allow(dead_code))]
pub(crate) const STACK_SEGMENT_SIZE: usize = 1024 * 1024;
static STACK_GROW_COUNT: AtomicU64 = AtomicU64::new(0);
/// Total number of stack segment continuations allocated by `rune-taffy` in this process,
/// exposed for launch/frame diagnostics and depth probes.
#[inline]
pub fn stack_grow_count() -> u64 {
STACK_GROW_COUNT.load(Ordering::Relaxed)
}
#[cfg(windows)]
#[inline]
#[allow(unsafe_code)]
fn reserve_fiber_stack_guarantee() {
#[link(name = "kernel32")]
unsafe extern "system" {
fn SetThreadStackGuarantee(StackSizeInBytes: *mut u32) -> i32;
}
let mut bytes = 16 * 1024u32;
// SAFETY: `bytes` is a live writable `u32` on the newly allocated fiber's stack.
unsafe {
let _ = SetThreadStackGuarantee(&raw mut bytes);
}
}
/// Runs `f` on the current stack when at least [`STACK_RED_ZONE`] bytes remain, or continues on
/// a new segment on Windows, macOS, and Linux.
///
/// Every other target (`wasm32`, `android`, `ios`, `tvos`, `watchos`, `visionos`, etc.) runs `f`
/// directly rather than hitting `stacker`'s fallback path, which cannot query stack bounds and
/// would allocate a segment on every uncached container layout.
#[inline(always)]
pub(crate) fn maybe_grow<R>(f: impl FnOnce() -> R) -> R {
#[cfg(any(windows, target_os = "macos", target_os = "linux"))]
{
if stacker::remaining_stack().is_none_or(|rem| rem >= STACK_RED_ZONE) {
f()
} else {
STACK_GROW_COUNT.fetch_add(1, Ordering::Relaxed);
stacker::grow(STACK_SEGMENT_SIZE, || {
#[cfg(windows)]
reserve_fiber_stack_guarantee();
f()
})
}
}
#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
{
f()
}
}
+624
View File
@@ -0,0 +1,624 @@
//! Retained no-second-tree layout store (`LayoutStore`) driving Taffy 0.15's solver directly.
//!
//! Instead of maintaining a general-purpose `TaffyTree` (`SlotMap`s / `SparseSet`, parent links,
//! per-node child `Vec`s, dual 92-byte `Layout`s, and `Option<NodeContext>`), `LayoutStore` holds:
//! - Dense 216-byte `RetainedSlot`s indexed directly by `SlotId(u32)` (`NodeId`).
//! - Double-buffered flat `Vec<u32>` child arenas (`prev_children` / `curr_children`) plus a
//! reusable DFS `child_scratch` stack so `flatten` allocates zero child `Vec`s.
//! - Single-pass post-order dirty propagation during `flatten`, with an `O(1)` warm unmount check
//! when the mounted key count is unchanged.
#![forbid(unsafe_code)]
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use taffy::DetailedGridInfo;
use taffy::compute::compute_root_layout;
use taffy::geometry::Size;
use taffy::style::AvailableSpace;
use taffy::tree::{ClearState, DetailedLayoutInfo, Layout, LayoutInput, LayoutOutput, NodeId};
use crate::cache::CompactCache;
use crate::style::CompactStyle;
use crate::view::LayoutStoreView;
/// Memory breakdown for a layout store instance.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct StorageStats {
pub live_nodes: usize,
pub slot_capacity: usize,
pub sparse_capacity: usize,
pub bytes_per_slot: usize,
pub inline_buffer_bytes: usize,
pub child_heap_bytes: usize,
pub cold_style_bytes: usize,
pub cold_cache_bytes: usize,
pub cold_aux_bytes: usize,
pub total_retained_bytes: usize,
}
const UNMOUNTED: u32 = u32::MAX;
#[derive(Default)]
struct FxU64(u64);
impl Hasher for FxU64 {
#[inline(always)]
fn finish(&self) -> u64 {
self.0
}
#[inline(always)]
fn write(&mut self, bytes: &[u8]) {
let mut h = self.0;
for &b in bytes {
h = (h.rotate_left(5) ^ (b as u64)).wrapping_mul(0x517c_c1b7_2722_0a95);
}
self.0 = h;
}
#[inline(always)]
fn write_u64(&mut self, i: u64) {
self.0 = (self.0.rotate_left(5) ^ i).wrapping_mul(0x517c_c1b7_2722_0a95);
}
}
type KeyMap<V> = HashMap<u64, V, BuildHasherDefault<FxU64>>;
/// Direct index into [`LayoutStore`]'s dense slot array.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct SlotId(pub u32);
impl SlotId {
#[inline(always)]
pub const fn to_taffy(self) -> NodeId {
NodeId::new(self.0 as u64)
}
#[inline(always)]
pub fn from_taffy(id: NodeId) -> Self {
Self(u64::from(id) as u32)
}
}
/// Unrounded box geometry and combined `padding + border` insets (32 bytes vs 92 bytes for `taffy::Layout`).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct BoxLayout {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
/// `[left, top, right, bottom]` = `padding + border`.
pub inset: [f32; 4],
}
const _: () = assert!(core::mem::size_of::<BoxLayout>() == 32);
impl BoxLayout {
pub const ZERO: Self = Self {
x: 0.0,
y: 0.0,
w: 0.0,
h: 0.0,
inset: [0.0; 4],
};
#[inline(always)]
pub fn from_taffy(l: &Layout) -> Self {
Self {
x: l.location.x,
y: l.location.y,
w: l.size.width,
h: l.size.height,
inset: [
l.padding.left + l.border.left,
l.padding.top + l.border.top,
l.padding.right + l.border.right,
l.padding.bottom + l.border.bottom,
],
}
}
#[inline(always)]
pub const fn size(&self) -> Size<f32> {
Size {
width: self.w,
height: self.h,
}
}
}
const HAS_CTX_BIT: u32 = 1 << 31;
const MUTATED_BIT: u32 = 1 << 30;
const CHILD_LEN_MASK: u32 = !(HAS_CTX_BIT | MUTATED_BIT);
#[derive(Debug, Clone)]
pub(crate) struct RetainedSlot {
pub(crate) style: CompactStyle,
pub(crate) cache: CompactCache,
pub(crate) box_layout: BoxLayout,
pub(crate) measure: u64,
pub(crate) grid_info: Option<Box<DetailedLayoutInfo>>,
pub(crate) child_start: u32,
pub(crate) child_len_and_flags: u32,
}
const _: () = assert!(core::mem::size_of::<RetainedSlot>() <= 216);
#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<RetainedSlot>() == 216);
impl RetainedSlot {
#[inline(always)]
fn empty() -> Self {
Self {
style: CompactStyle::default(),
cache: CompactCache::new(),
box_layout: BoxLayout::ZERO,
measure: 0,
grid_info: None,
child_start: 0,
child_len_and_flags: 0,
}
}
#[inline(always)]
pub(crate) fn child_len(&self) -> u32 {
self.child_len_and_flags & CHILD_LEN_MASK
}
#[inline(always)]
pub(crate) fn has_context(&self) -> bool {
(self.child_len_and_flags & HAS_CTX_BIT) != 0
}
#[inline(always)]
fn has_mutated(&self) -> bool {
(self.child_len_and_flags & MUTATED_BIT) != 0
}
}
/// Contiguous slice iterator over a node's child [`SlotId`]s for the current commit.
#[derive(Debug, Clone)]
pub struct SlotChildIter<'a>(pub(crate) core::slice::Iter<'a, u32>);
impl Iterator for SlotChildIter<'_> {
type Item = NodeId;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|&s| NodeId::new(s as u64))
}
#[inline(always)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl ExactSizeIterator for SlotChildIter<'_> {
#[inline(always)]
fn len(&self) -> usize {
self.0.len()
}
}
/// Retained layout store integrated directly with Rune's commit pass.
#[derive(Debug, Clone, Default)]
pub struct LayoutStore {
pub(crate) slots: Vec<RetainedSlot>,
pub(crate) node_idx: Vec<u32>,
by_key: KeyMap<u32>,
free: Vec<u32>,
prev_children: Vec<u32>,
pub(crate) curr_children: Vec<u32>,
child_scratch: Vec<u32>,
mutated_slots: Vec<u32>,
prev_live: usize,
visited_existing: usize,
}
impl LayoutStore {
#[must_use]
pub fn new() -> Self {
Self::with_capacity(32)
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
slots: Vec::with_capacity(capacity),
node_idx: Vec::with_capacity(capacity),
by_key: KeyMap::with_capacity_and_hasher(capacity, Default::default()),
free: Vec::new(),
prev_children: Vec::with_capacity(capacity),
curr_children: Vec::with_capacity(capacity),
child_scratch: Vec::with_capacity(64),
mutated_slots: Vec::new(),
prev_live: 0,
visited_existing: 0,
}
}
#[inline]
pub fn live_count(&self) -> usize {
self.by_key.len()
}
/// Starts a new flatten pass, swapping the flat child arena without deallocating.
#[inline]
pub fn begin_commit(&mut self) {
core::mem::swap(&mut self.prev_children, &mut self.curr_children);
self.curr_children.clear();
self.child_scratch.clear();
self.node_idx.fill(UNMOUNTED);
self.prev_live = self.by_key.len();
self.visited_existing = 0;
}
#[inline(always)]
pub fn begin_children(&self) -> usize {
self.child_scratch.len()
}
#[inline(always)]
pub fn push_child(&mut self, child: SlotId) {
self.child_scratch.push(child.0);
}
/// Whether `key` still owns `slot` and has not been claimed or mutated earlier in this commit.
#[inline]
pub fn can_reuse(&self, key: u64, slot: SlotId) -> bool {
let idx = slot.0 as usize;
self.by_key.get(&key) == Some(&slot.0)
&& self.node_idx.get(idx).copied() == Some(UNMOUNTED)
&& self.slots.get(idx).is_some_and(|s| !s.has_mutated())
}
/// Whether `key` has already been claimed earlier in this commit.
#[inline]
pub fn is_used_this_commit(&self, key: u64) -> bool {
self.by_key
.get(&key)
.is_some_and(|&s| self.node_idx.get(s as usize).copied() != Some(UNMOUNTED))
}
/// Reuses an unchanged slot (`memo_reuse`) by copying its previous child slice into
/// `curr_children` and updating its `node_idx` without re-checking style or cache.
#[inline]
pub fn reuse_slot(&mut self, slot: SlotId, node_idx: u32) {
let idx = slot.0 as usize;
debug_assert!(idx < self.slots.len());
if self.node_idx[idx] == UNMOUNTED {
self.visited_existing += 1;
}
self.node_idx[idx] = node_idx;
let old_start = self.slots[idx].child_start as usize;
let len = self.slots[idx].child_len() as usize;
let new_start = self.curr_children.len() as u32;
if len > 0 {
self.curr_children
.extend_from_slice(&self.prev_children[old_start..old_start + len]);
}
self.slots[idx].child_start = new_start;
}
/// Rebases a slice of `(old_key, new_key, slot, node_idx)` entries when a memoized subtree
/// moves to a new parent path, preserving each slot's warm cache and children.
pub fn rekey_and_reuse_batch(
&mut self,
items: impl ExactSizeIterator<Item = (u64, u64, SlotId, u32)> + Clone,
) {
for (old_key, _, slot, _) in items.clone() {
let removed = self.by_key.remove(&old_key);
debug_assert_eq!(removed, Some(slot.0));
}
for (_, new_key, slot, node_idx) in items {
if let Some(stale) = self.by_key.remove(&new_key) {
self.slots[stale as usize] = RetainedSlot::empty();
self.free.push(stale);
self.prev_live = self.prev_live.saturating_sub(1);
}
self.by_key.insert(new_key, slot.0);
self.reuse_slot(slot, node_idx);
}
}
/// Reconciles one node in post-order after its children have pushed onto `child_scratch[child_mark..]`.
/// Returns `(slot_id, subtree_dirty)` and clears this slot's cache immediately if dirty.
#[inline]
#[allow(clippy::too_many_arguments)]
pub fn sync_node(
&mut self,
key: u64,
node_idx: u32,
style: CompactStyle,
measure: Option<u64>,
force_measure_dirty: bool,
child_mark: usize,
children_dirty: bool,
) -> (SlotId, bool) {
let new_kids = &self.child_scratch[child_mark..];
let child_start = self.curr_children.len() as u32;
let child_len = new_kids.len() as u32;
self.curr_children.extend_from_slice(new_kids);
if let Some(&s) = self.by_key.get(&key) {
let idx = s as usize;
let prev_idx = &mut self.node_idx[idx];
let first_visit = *prev_idx == UNMOUNTED;
if first_visit {
self.visited_existing += 1;
}
*prev_idx = node_idx;
let slot = &mut self.slots[idx];
let old_start = slot.child_start as usize;
let old_end = old_start + slot.child_len() as usize;
let kids_changed = if first_visit {
&self.prev_children[old_start..old_end] != new_kids
} else {
self.curr_children[old_start..old_end] != self.curr_children[child_start as usize..]
};
let style_changed = slot.style != style;
if style_changed {
slot.style = style;
}
slot.child_start = child_start;
let had_measure = slot.has_context();
let has_measure = measure.is_some();
let new_m = measure.unwrap_or(0);
let measure_changed =
had_measure != has_measure || (has_measure && (force_measure_dirty || slot.measure != new_m));
let was_mutated = slot.has_mutated();
let now_mutated = was_mutated || style_changed || kids_changed || measure_changed;
slot.child_len_and_flags = child_len
| if has_measure { HAS_CTX_BIT } else { 0 }
| if now_mutated { MUTATED_BIT } else { 0 };
slot.measure = new_m;
let dirty = style_changed || kids_changed || measure_changed || children_dirty;
if dirty {
slot.cache.clear();
}
if now_mutated && !was_mutated {
self.mutated_slots.push(s);
}
self.child_scratch.truncate(child_mark);
(SlotId(s), dirty)
} else {
self.child_scratch.truncate(child_mark);
let new_slot = RetainedSlot {
style,
cache: CompactCache::new(),
box_layout: BoxLayout::ZERO,
measure: measure.unwrap_or(0),
grid_info: None,
child_start,
child_len_and_flags: child_len
| if measure.is_some() { HAS_CTX_BIT } else { 0 }
| MUTATED_BIT,
};
let s = if let Some(free_s) = self.free.pop() {
let idx = free_s as usize;
self.slots[idx] = new_slot;
self.node_idx[idx] = node_idx;
free_s
} else {
let s = self.slots.len() as u32;
self.slots.push(new_slot);
self.node_idx.push(node_idx);
s
};
self.mutated_slots.push(s);
self.by_key.insert(key, s);
(SlotId(s), true)
}
}
/// Frees any slots not visited during `flatten` without renumbering kept `SlotId`s, so
/// measurement retries still see stable `SlotId`s on `old_nodes`.
#[inline]
pub fn finish_flatten(&mut self) {
if self.visited_existing == self.prev_live {
return;
}
let Self {
slots,
node_idx,
by_key,
free,
..
} = self;
by_key.retain(|_, &mut s| {
let idx = s as usize;
if node_idx[idx] == UNMOUNTED {
slots[idx] = RetainedSlot::empty();
free.push(s);
false
} else {
true
}
});
}
/// Shrinks storage when live occupancy drops below 25% of capacity.
#[inline]
pub fn compact_if_sparse(&mut self, remap: impl FnMut(u32, SlotId)) {
let mut dummy = SlotId(UNMOUNTED);
self.compact_with_root(&mut dummy, remap);
}
fn compact_with_root(&mut self, root: &mut SlotId, mut remap: impl FnMut(u32, SlotId)) {
for idx in self.mutated_slots.drain(..) {
if let Some(s) = self.slots.get_mut(idx as usize) {
s.child_len_and_flags &= !MUTATED_BIT;
}
}
let live = self.by_key.len();
if self.slots.capacity() <= 64 || live.saturating_mul(4) > self.slots.capacity() {
return;
}
let Self {
slots,
node_idx,
by_key,
free,
curr_children,
prev_children,
child_scratch,
..
} = self;
let cap = (live * 2).max(32);
let mut remap_table = vec![UNMOUNTED; slots.len()];
let mut new_slots = Vec::with_capacity(cap);
let mut new_node_idx = Vec::with_capacity(cap);
for s_mut in by_key.values_mut() {
let old_s = *s_mut as usize;
let new_s = new_slots.len() as u32;
remap_table[old_s] = new_s;
let mut slot = core::mem::replace(&mut slots[old_s], RetainedSlot::empty());
slot.cache.clear();
let me = node_idx[old_s];
remap(me, SlotId(new_s));
*s_mut = new_s;
new_slots.push(slot);
new_node_idx.push(me);
}
if let Some(&new_root) = remap_table.get(root.0 as usize)
&& new_root != UNMOUNTED
{
root.0 = new_root;
}
for c in curr_children.iter_mut() {
*c = remap_table[*c as usize];
}
*slots = new_slots;
*node_idx = new_node_idx;
*free = Vec::new();
by_key.shrink_to(cap);
curr_children.shrink_to(cap);
*prev_children = Vec::with_capacity(cap);
child_scratch.shrink_to(64);
}
/// Finishes a flatten pass, recycling unvisited slots and compacting when sparse.
#[inline]
pub fn end_commit(&mut self, root: &mut SlotId, remap: impl FnMut(u32, SlotId)) {
if self.visited_existing != self.prev_live {
self.finish_flatten();
}
self.compact_with_root(root, remap);
}
#[inline(always)]
pub fn style(&self, id: SlotId) -> &CompactStyle {
&self.slots[id.0 as usize].style
}
#[inline(always)]
pub fn box_layout(&self, id: SlotId) -> BoxLayout {
self.slots[id.0 as usize].box_layout
}
/// Returns the index in the current commit's `nodes` slice for `key`, if mounted this commit.
#[inline]
pub fn mounted_node_index(&self, key: u64) -> Option<usize> {
let &s = self.by_key.get(&key)?;
let idx = *self.node_idx.get(s as usize)?;
(idx != UNMOUNTED).then_some(idx as usize)
}
pub fn measure_hash(&self, key: u64) -> Option<Option<u64>> {
let &s = self.by_key.get(&key)?;
let slot = &self.slots[s as usize];
Some(slot.has_context().then_some(slot.measure))
}
/// Updates `id`'s style (for intra-commit two-pass refits like `aspect_fit` and `anchored_fit`)
/// and clears `id`'s and its ancestors' layout caches.
#[inline]
pub fn set_style_and_mark_ancestors(
&mut self,
id: SlotId,
style: CompactStyle,
ancestors: impl IntoIterator<Item = SlotId>,
) {
let slot = &mut self.slots[id.0 as usize];
if !slot.has_mutated() {
slot.child_len_and_flags |= MUTATED_BIT;
self.mutated_slots.push(id.0);
}
slot.style = style;
slot.cache.clear();
for anc in ancestors {
if matches!(self.slots[anc.0 as usize].cache.clear(), ClearState::AlreadyEmpty) {
break;
}
}
}
/// Clears `id`'s and its ancestors' layout caches without modifying style.
#[inline]
pub fn mark_dirty_and_ancestors(&mut self, id: SlotId, ancestors: impl IntoIterator<Item = SlotId>) {
self.slots[id.0 as usize].cache.clear();
for anc in ancestors {
if matches!(self.slots[anc.0 as usize].cache.clear(), ClearState::AlreadyEmpty) {
break;
}
}
}
/// Clears every live slot's layout cache (e.g. when switching font families).
pub fn mark_all_dirty(&mut self) {
for &s in self.by_key.values() {
self.slots[s as usize].cache.clear();
}
}
pub fn compute_layout<F>(&mut self, root: SlotId, available_space: Size<AvailableSpace>, measure_leaf: F)
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
let mut view = LayoutStoreView {
store: self,
measure_leaf,
in_whole_rows_col: false,
};
compute_root_layout(&mut view, root.to_taffy(), available_space);
}
pub fn storage_stats(&self) -> StorageStats {
let slot_capacity = self.slots.capacity();
let bytes_per_slot = core::mem::size_of::<RetainedSlot>() + core::mem::size_of::<u32>();
let inline_buffer_bytes = slot_capacity * bytes_per_slot
+ (self.prev_children.capacity() + self.curr_children.capacity() + self.child_scratch.capacity())
* core::mem::size_of::<u32>()
+ self.free.capacity() * core::mem::size_of::<u32>();
let mut cold_style_bytes = 0usize;
let mut cold_cache_bytes = 0usize;
let mut cold_aux_bytes = 0usize;
for &s in self.by_key.values() {
let slot = &self.slots[s as usize];
cold_style_bytes += slot.style.heap_bytes();
cold_cache_bytes += slot.cache.heap_bytes();
if slot.grid_info.is_some() {
cold_aux_bytes += core::mem::size_of::<DetailedLayoutInfo>() + core::mem::size_of::<DetailedGridInfo>();
}
}
StorageStats {
live_nodes: self.by_key.len(),
slot_capacity,
sparse_capacity: self.by_key.capacity(),
bytes_per_slot,
inline_buffer_bytes,
child_heap_bytes: 0,
cold_style_bytes,
cold_cache_bytes,
cold_aux_bytes,
total_retained_bytes: inline_buffer_bytes + cold_style_bytes + cold_cache_bytes + cold_aux_bytes,
}
}
}
+263
View File
@@ -0,0 +1,263 @@
//! Conversions and equality between [`CompactStyle`] and [`taffy::Style`].
use super::*;
impl CompactStyle {
pub fn from_style(s: Style) -> Self {
let mut vals = [0u32; HOT_VAL_COUNT];
let mut len_tags: u16 = 0;
let mut needs_extra = has_cold_fields(&s);
let dims = [
s.size.width.into_raw(),
s.size.height.into_raw(),
s.min_size.width.into_raw(),
s.min_size.height.into_raw(),
s.max_size.width.into_raw(),
s.max_size.height.into_raw(),
];
for (i, raw) in dims.into_iter().enumerate() {
let (v, t) = pack_raw_len(raw);
vals[i] = v;
if let Some(code) = encode_dim_tag(t) {
len_tags |= code << (i * 2);
} else {
needs_extra = true;
}
}
let pads = [
s.padding.left.into_raw(),
s.padding.right.into_raw(),
s.padding.top.into_raw(),
s.padding.bottom.into_raw(),
];
for (i, raw) in pads.into_iter().enumerate() {
let (v, t) = pack_raw_len(raw);
vals[IDX_PAD_L + i] = v;
if t as usize == CompactLength::PERCENT_TAG {
len_tags |= 1 << (12 + i);
} else if t as usize != CompactLength::LENGTH_TAG {
needs_extra = true;
}
}
let (gw_bits, gw_tag) = pack_raw_len(s.gap.width.into_raw());
let (gh_bits, gh_tag) = pack_raw_len(s.gap.height.into_raw());
let gap_w_bf16 = if (gw_bits & 0xFFFF) == 0 {
(gw_bits >> 16) as u16
} else {
needs_extra = true;
0
};
let gap_h_bf16 = if (gh_bits & 0xFFFF) == 0 {
(gh_bits >> 16) as u16
} else {
needs_extra = true;
0
};
let flex_grow_bf16 = match pack_bf16_exact(s.flex_grow) {
Some(b) => b,
None => {
needs_extra = true;
0
}
};
let flex_shrink_bf16 = match pack_bf16_exact(s.flex_shrink) {
Some(b) => b,
None => {
needs_extra = true;
0
}
};
let (basis_bits, basis_tag) = pack_raw_len(s.flex_basis.into_raw());
let pos_code = match encode_position(s.position) {
Some(c) => c,
None => {
needs_extra = true;
0b11
}
};
let mut mode_flags = encode_display(s.display) | (pos_code << MODE_POS_SHIFT);
if gw_tag as usize == CompactLength::PERCENT_TAG {
mode_flags |= MODE_GAP_W_PCT;
} else if gw_tag as usize != CompactLength::LENGTH_TAG {
needs_extra = true;
}
if gh_tag as usize == CompactLength::PERCENT_TAG {
mode_flags |= MODE_GAP_H_PCT;
} else if gh_tag as usize != CompactLength::LENGTH_TAG {
needs_extra = true;
}
if basis_tag as usize == CompactLength::LENGTH_TAG && basis_bits == 0 {
mode_flags |= MODE_BASIS_ZERO;
} else if basis_tag as usize != CompactLength::AUTO_TAG {
needs_extra = true;
}
let box_flags = pack_box_flags(s.flex_direction, s.flex_wrap, s.overflow.x, s.overflow.y);
let align_items_u8 = pack_align_items(s.align_items);
let align_self_u8 = pack_align_self(s.align_self);
let justify_content_u8 = pack_align_content(s.justify_content);
let align_content_u8 = pack_align_content(s.align_content);
let extra = needs_extra.then(|| Box::new(s));
Self {
vals,
gap_w_bf16,
gap_h_bf16,
flex_grow_bf16,
flex_shrink_bf16,
len_tags,
box_flags,
mode_flags,
align_items_u8,
align_self_u8,
justify_content_u8,
align_content_u8,
extra,
}
}
pub fn to_style(&self) -> Style {
if let Some(extra) = &self.extra {
return (**extra).clone();
}
Style {
display: self.display(),
position: self.position(),
overflow: CoreStyle::overflow(self),
size: CoreStyle::size(self),
min_size: CoreStyle::min_size(self),
max_size: CoreStyle::max_size(self),
aspect_ratio: None,
padding: CoreStyle::padding(self),
gap: FlexboxContainerStyle::gap(self),
align_items: unpack_align_items(self.align_items_u8),
align_self: unpack_align_self(self.align_self_u8),
justify_content: unpack_align_content(self.justify_content_u8),
align_content: unpack_align_content(self.align_content_u8),
flex_direction: FlexboxContainerStyle::flex_direction(self),
flex_wrap: FlexboxContainerStyle::flex_wrap(self),
flex_grow: FlexboxItemStyle::flex_grow(self),
flex_shrink: FlexboxItemStyle::flex_shrink(self),
flex_basis: FlexboxItemStyle::flex_basis(self),
..Style::DEFAULT
}
}
pub fn heap_bytes(&self) -> usize {
self.extra.as_ref().map_or(0, |s| {
type Ident = <Style as CoreStyle>::CustomIdent;
core::mem::size_of::<Style>()
+ s.grid_template_rows.capacity() * core::mem::size_of::<taffy::GridTemplateComponent<Ident>>()
+ s.grid_template_columns.capacity() * core::mem::size_of::<taffy::GridTemplateComponent<Ident>>()
})
}
#[inline(always)]
pub fn eq_style(&self, other: &Style) -> bool {
!self.whole_rows() && self.eq_style_ignoring_whole(other)
}
#[inline(always)]
fn eq_style_ignoring_whole(&self, other: &Style) -> bool {
if let Some(extra) = &self.extra {
return &**extra == other;
}
self.display() == other.display
&& self.position() == other.position
&& self.box_flags == pack_box_flags(other.flex_direction, other.flex_wrap, other.overflow.x, other.overflow.y)
&& self.align_items_u8 == pack_align_items(other.align_items)
&& self.align_self_u8 == pack_align_self(other.align_self)
&& (self.justify_content_u8 & !JUSTIFY_WHOLE_ROWS) == pack_align_content(other.justify_content)
&& self.align_content_u8 == pack_align_content(other.align_content)
&& FlexboxItemStyle::flex_grow(self) == other.flex_grow
&& FlexboxItemStyle::flex_shrink(self) == other.flex_shrink
&& other.aspect_ratio.is_none()
&& CoreStyle::size(self) == other.size
&& CoreStyle::min_size(self) == other.min_size
&& CoreStyle::max_size(self) == other.max_size
&& CoreStyle::padding(self) == other.padding
&& FlexboxContainerStyle::gap(self) == other.gap
&& FlexboxItemStyle::flex_basis(self) == other.flex_basis
&& !has_cold_fields(other)
}
}
impl From<Style> for CompactStyle {
#[inline]
fn from(s: Style) -> Self {
Self::from_style(s)
}
}
impl From<&Style> for CompactStyle {
#[inline]
fn from(s: &Style) -> Self {
Self::from_style(s.clone())
}
}
impl From<CompactStyle> for Style {
#[inline]
fn from(s: CompactStyle) -> Self {
match s.extra {
Some(extra) => *extra,
None => s.to_style(),
}
}
}
impl From<&CompactStyle> for Style {
#[inline]
fn from(s: &CompactStyle) -> Self {
s.to_style()
}
}
impl PartialEq for CompactStyle {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
if self.extra.is_none() && other.extra.is_none() {
return self.vals == other.vals
&& self.gap_w_bf16 == other.gap_w_bf16
&& self.gap_h_bf16 == other.gap_h_bf16
&& self.flex_grow_bf16 == other.flex_grow_bf16
&& self.flex_shrink_bf16 == other.flex_shrink_bf16
&& self.len_tags == other.len_tags
&& self.box_flags == other.box_flags
&& self.mode_flags == other.mode_flags
&& self.align_items_u8 == other.align_items_u8
&& self.align_self_u8 == other.align_self_u8
&& self.justify_content_u8 == other.justify_content_u8
&& self.align_content_u8 == other.align_content_u8;
}
self.eq_cold(other)
}
}
impl CompactStyle {
#[cold]
#[inline(never)]
fn eq_cold(&self, other: &Self) -> bool {
if self.whole_rows() != other.whole_rows() {
return false;
}
match (&self.extra, &other.extra) {
(Some(a), Some(b)) => a == b,
(Some(a), None) => (other.justify_content_u8 & !JUSTIFY_WHOLE_ROWS) == pack_align_content(a.justify_content) && other.eq_style_ignoring_whole(a),
(None, Some(b)) => (self.justify_content_u8 & !JUSTIFY_WHOLE_ROWS) == pack_align_content(b.justify_content) && self.eq_style_ignoring_whole(b),
(None, None) => unreachable!(),
}
}
}
impl PartialEq<Style> for CompactStyle {
#[inline(always)]
fn eq(&self, other: &Style) -> bool {
self.eq_style(other)
}
}
+560
View File
@@ -0,0 +1,560 @@
//! Compact node style representation (64 bytes inline — one CPU cache line — vs 552 bytes for `taffy::Style`).
//!
//! Stores the hot Flexbox/Block/Core properties inline in 56 bytes plus an 8-byte `Option<Box<Style>>`
//! for cold CSS properties (Grid tracks/placement, non-zero margin/border/inset, `aspect_ratio`,
//! or exotic sizing keywords).
#![forbid(unsafe_code)]
use taffy::geometry::{Line, Point, Rect, Size};
use taffy::style::{
AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, BlockContainerStyle,
BlockItemStyle, BoxGenerationMode, BoxSizing, CompactLength, Contain, CoreStyle, Dimension, Direction, Display,
FlexDirection, FlexWrap, FlexboxContainerStyle, FlexboxItemStyle, GridAutoFlow, GridContainerStyle, GridItemStyle,
GridPlacement, JustifyContent, LengthPercentage, LengthPercentageAuto, OofItemStyle, Overflow, Position, Style,
TextAlign,
};
use taffy::style_helpers::{TaffyAuto, TaffyZero, fr, line, span};
const IDX_SIZE_W: usize = 0;
const IDX_SIZE_H: usize = 1;
const IDX_MIN_W: usize = 2;
const IDX_MIN_H: usize = 3;
const IDX_MAX_W: usize = 4;
const IDX_MAX_H: usize = 5;
const IDX_PAD_L: usize = 6;
const IDX_PAD_R: usize = 7;
const IDX_PAD_T: usize = 8;
const IDX_PAD_B: usize = 9;
const HOT_VAL_COUNT: usize = 10;
const MODE_DISPLAY_MASK: u8 = 0b0000_0111;
const MODE_POS_SHIFT: u8 = 3;
const MODE_POS_MASK: u8 = 0b0001_1000;
const MODE_GAP_W_PCT: u8 = 1 << 5;
const MODE_GAP_H_PCT: u8 = 1 << 6;
const MODE_BASIS_ZERO: u8 = 1 << 7;
const JUSTIFY_WHOLE_ROWS: u8 = 1 << 7;
const BASE_LEN_TAGS: u16 = 0b0000_1010_1010_1010;
const ONE_BF16: u16 = 0x3F80;
#[inline(always)]
fn pack_raw_len(len: CompactLength) -> (u32, u8) {
(len.value().to_bits(), len.tag() as u8)
}
#[inline(always)]
fn encode_dim_tag(raw_tag: u8) -> Option<u16> {
match raw_tag as usize {
CompactLength::LENGTH_TAG => Some(0),
CompactLength::PERCENT_TAG => Some(1),
CompactLength::AUTO_TAG => Some(2),
CompactLength::MAX_CONTENT_TAG => Some(3),
_ => None,
}
}
#[inline(always)]
fn unpack_dim(bits: u32, code: u16) -> Dimension {
match code & 0b11 {
0 => Dimension::length(f32::from_bits(bits)),
1 => Dimension::percent(f32::from_bits(bits)),
2 => Dimension::auto(),
_ => Dimension::max_content(),
}
}
#[inline(always)]
fn unpack_lpa(bits: u32, code: u16) -> LengthPercentageAuto {
match code & 0b11 {
0 => LengthPercentageAuto::length(f32::from_bits(bits)),
1 => LengthPercentageAuto::percent(f32::from_bits(bits)),
_ => LengthPercentageAuto::auto(),
}
}
#[inline(always)]
fn unpack_lp(bits: u32, is_pct: bool) -> LengthPercentage {
let val = f32::from_bits(bits);
if is_pct {
LengthPercentage::percent(val)
} else {
LengthPercentage::length(val)
}
}
#[inline(always)]
fn pack_bf16_exact(v: f32) -> Option<u16> {
let bits = v.to_bits();
((bits & 0xFFFF) == 0).then_some((bits >> 16) as u16)
}
#[inline(always)]
fn unpack_bf16(b: u16) -> f32 {
f32::from_bits((b as u32) << 16)
}
#[inline(always)]
fn rect_is_zero_lpa(r: &Rect<LengthPercentageAuto>) -> bool {
const ZERO: Rect<LengthPercentageAuto> = Rect {
left: LengthPercentageAuto::ZERO,
right: LengthPercentageAuto::ZERO,
top: LengthPercentageAuto::ZERO,
bottom: LengthPercentageAuto::ZERO,
};
*r == ZERO
}
#[inline(always)]
fn rect_is_zero_lp(r: &Rect<LengthPercentage>) -> bool {
const ZERO: Rect<LengthPercentage> = Rect {
left: LengthPercentage::ZERO,
right: LengthPercentage::ZERO,
top: LengthPercentage::ZERO,
bottom: LengthPercentage::ZERO,
};
*r == ZERO
}
#[inline(always)]
fn rect_is_auto_lpa(r: &Rect<LengthPercentageAuto>) -> bool {
const AUTO: Rect<LengthPercentageAuto> = Rect {
left: LengthPercentageAuto::AUTO,
right: LengthPercentageAuto::AUTO,
top: LengthPercentageAuto::AUTO,
bottom: LengthPercentageAuto::AUTO,
};
*r == AUTO
}
#[inline(always)]
fn has_cold_fields(s: &Style) -> bool {
s.display == Display::Grid
|| s.aspect_ratio.is_some()
|| !rect_is_zero_lpa(&s.margin)
|| !rect_is_auto_lpa(&s.inset)
|| !rect_is_zero_lp(&s.border)
|| s.box_sizing != BoxSizing::BorderBox
|| s.direction != Direction::Ltr
|| s.scrollbar_width != 0.0
|| s.contain != Contain::NONE
|| s.justify_items != AlignItems::NORMAL
|| s.justify_self.is_some()
|| s.text_align != TextAlign::Auto
|| s.item_is_table
|| s.item_is_replaced
|| s.item_is_compressible_replaced
|| s.grid_auto_flow != GridAutoFlow::Row
|| s.grid_row != Line { start: GridPlacement::Auto, end: GridPlacement::Auto }
|| s.grid_column != Line { start: GridPlacement::Auto, end: GridPlacement::Auto }
|| !s.grid_template_rows.is_empty()
|| !s.grid_template_columns.is_empty()
|| !s.grid_auto_rows.is_empty()
|| !s.grid_auto_columns.is_empty()
|| s.grid_template_areas.is_some()
|| !s.grid_template_column_names.is_empty()
|| !s.grid_template_row_names.is_empty()
}
#[inline(always)]
const fn encode_display(d: Display) -> u8 {
match d {
Display::Flex => 0,
Display::Block => 1,
Display::Grid => 2,
Display::FlowRoot => 3,
Display::None => 4,
}
}
#[inline(always)]
const fn decode_display(b: u8) -> Display {
match b & MODE_DISPLAY_MASK {
0 => Display::Flex,
1 => Display::Block,
2 => Display::Grid,
3 => Display::FlowRoot,
_ => Display::None,
}
}
#[inline(always)]
const fn encode_position(p: Position) -> Option<u8> {
match p {
Position::Static => Some(0),
Position::Relative => Some(1),
Position::Absolute => Some(2),
Position::Fixed | Position::Sticky => None,
}
}
#[inline(always)]
fn decode_position(mode_flags: u8, extra: Option<&Style>) -> Position {
match (mode_flags & MODE_POS_MASK) >> MODE_POS_SHIFT {
0 => Position::Static,
1 => Position::Relative,
2 => Position::Absolute,
_ => extra.map_or(Position::Static, |s| s.position),
}
}
const ALIGN_SELF_NONE: u8 = 0xFF;
#[inline(always)]
const fn pack_align_items(a: AlignItems) -> u8 {
((a.safety as u8) << 4) | (a.keyword as u8)
}
#[inline(always)]
const fn unpack_align_items(b: u8) -> AlignItems {
let safety = match (b >> 4) & 0b11 {
0 => AlignmentSafety::Default,
1 => AlignmentSafety::Unsafe,
_ => AlignmentSafety::Safe,
};
let keyword = match b & 0x0F {
0 => AlignItemsKeyword::Normal,
1 => AlignItemsKeyword::Start,
2 => AlignItemsKeyword::End,
3 => AlignItemsKeyword::FlexStart,
4 => AlignItemsKeyword::FlexEnd,
5 => AlignItemsKeyword::SelfStart,
6 => AlignItemsKeyword::SelfEnd,
7 => AlignItemsKeyword::Center,
8 => AlignItemsKeyword::Baseline,
_ => AlignItemsKeyword::Stretch,
};
AlignItems { keyword, safety }
}
#[inline(always)]
const fn pack_align_self(a: Option<AlignSelf>) -> u8 {
match a {
Some(v) => pack_align_items(v),
None => ALIGN_SELF_NONE,
}
}
#[inline(always)]
const fn unpack_align_self(b: u8) -> Option<AlignSelf> {
if b == ALIGN_SELF_NONE {
None
} else {
Some(unpack_align_items(b))
}
}
#[inline(always)]
const fn pack_align_content(a: AlignContent) -> u8 {
((a.safety as u8) << 4) | (a.keyword as u8)
}
#[inline(always)]
const fn unpack_align_content(b: u8) -> AlignContent {
let safety = match (b >> 4) & 0b11 {
0 => AlignmentSafety::Default,
1 => AlignmentSafety::Unsafe,
_ => AlignmentSafety::Safe,
};
let keyword = match b & 0x0F {
0 => AlignContentKeyword::Normal,
1 => AlignContentKeyword::Start,
2 => AlignContentKeyword::End,
3 => AlignContentKeyword::FlexStart,
4 => AlignContentKeyword::FlexEnd,
5 => AlignContentKeyword::Center,
6 => AlignContentKeyword::Stretch,
7 => AlignContentKeyword::SpaceBetween,
8 => AlignContentKeyword::SpaceEvenly,
_ => AlignContentKeyword::SpaceAround,
};
AlignContent { keyword, safety }
}
#[inline(always)]
const fn encode_overflow(o: Overflow) -> u8 {
match o {
Overflow::Visible => 0,
Overflow::Clip => 1,
Overflow::Hidden => 2,
Overflow::Scroll => 3,
}
}
#[inline(always)]
const fn decode_overflow(b: u8) -> Overflow {
match b & 0b11 {
0 => Overflow::Visible,
1 => Overflow::Clip,
2 => Overflow::Hidden,
_ => Overflow::Scroll,
}
}
#[inline(always)]
const fn encode_wrap(w: FlexWrap) -> u8 {
match w {
FlexWrap::NoWrap => 0,
FlexWrap::Wrap => 1,
FlexWrap::WrapReverse => 2,
}
}
#[inline(always)]
const fn decode_wrap(b: u8) -> FlexWrap {
match b & 0b11 {
0 => FlexWrap::NoWrap,
1 => FlexWrap::Wrap,
_ => FlexWrap::WrapReverse,
}
}
#[inline(always)]
const fn encode_dir(d: FlexDirection) -> u8 {
match d {
FlexDirection::Row => 0,
FlexDirection::Column => 1,
FlexDirection::RowReverse => 2,
FlexDirection::ColumnReverse => 3,
}
}
#[inline(always)]
const fn decode_dir(b: u8) -> FlexDirection {
match b & 0b11 {
0 => FlexDirection::Row,
1 => FlexDirection::Column,
2 => FlexDirection::RowReverse,
_ => FlexDirection::ColumnReverse,
}
}
#[inline(always)]
const fn pack_box_flags(dir: FlexDirection, wrap: FlexWrap, ox: Overflow, oy: Overflow) -> u8 {
encode_dir(dir) | (encode_wrap(wrap) << 2) | (encode_overflow(ox) << 4) | (encode_overflow(oy) << 6)
}
/// Compact representation of `taffy::Style` (64 bytes inline — one cache line).
#[derive(Debug)]
pub struct CompactStyle {
vals: [u32; HOT_VAL_COUNT],
gap_w_bf16: u16,
gap_h_bf16: u16,
flex_grow_bf16: u16,
flex_shrink_bf16: u16,
/// Bits 0..12: 2-bit tags for `size.w/h`, `min_size.w/h`, `max_size.w/h`.
/// Bits 12..16: 1-bit tags (`0 = Length`, `1 = Percent`) for `pad.l/r/t/b`.
len_tags: u16,
box_flags: u8,
/// Bits 0..3: `Display`.
/// Bits 3..5: `Position` (`Static`, `Relative`, `Absolute`).
/// Bit 5: `gap.width` is `Percent`.
/// Bit 6: `gap.height` is `Percent`.
/// Bit 7: `flex_basis` is `Length(0.0)` (otherwise `Auto`).
mode_flags: u8,
align_items_u8: u8,
align_self_u8: u8,
justify_content_u8: u8,
align_content_u8: u8,
extra: Option<Box<Style>>,
}
const _: () = assert!(core::mem::size_of::<CompactStyle>() <= 64);
#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<CompactStyle>() == 64);
impl Clone for CompactStyle {
#[inline(always)]
fn clone(&self) -> Self {
if self.extra.is_none() {
Self {
vals: self.vals,
gap_w_bf16: self.gap_w_bf16,
gap_h_bf16: self.gap_h_bf16,
flex_grow_bf16: self.flex_grow_bf16,
flex_shrink_bf16: self.flex_shrink_bf16,
len_tags: self.len_tags,
box_flags: self.box_flags,
mode_flags: self.mode_flags,
align_items_u8: self.align_items_u8,
align_self_u8: self.align_self_u8,
justify_content_u8: self.justify_content_u8,
align_content_u8: self.align_content_u8,
extra: None,
}
} else {
self.clone_cold()
}
}
}
impl Default for CompactStyle {
#[inline(always)]
fn default() -> Self {
Self {
vals: [0; HOT_VAL_COUNT],
gap_w_bf16: 0,
gap_h_bf16: 0,
flex_grow_bf16: 0,
flex_shrink_bf16: ONE_BF16,
len_tags: BASE_LEN_TAGS,
box_flags: 0,
mode_flags: encode_display(Display::Flex),
align_items_u8: pack_align_items(AlignItems::NORMAL),
align_self_u8: ALIGN_SELF_NONE,
justify_content_u8: pack_align_content(JustifyContent::NORMAL),
align_content_u8: pack_align_content(AlignContent::NORMAL),
extra: None,
}
}
}
impl CompactStyle {
/// Base element style used by Rune (`Display::Flex`, `Position::Relative`, `flex_shrink: 0.0`).
#[inline(always)]
pub const fn rune_base(dir: FlexDirection) -> Self {
Self {
vals: [0; HOT_VAL_COUNT],
gap_w_bf16: 0,
gap_h_bf16: 0,
flex_grow_bf16: 0,
flex_shrink_bf16: 0,
len_tags: BASE_LEN_TAGS,
box_flags: encode_dir(dir),
mode_flags: encode_display(Display::Flex) | (1 << MODE_POS_SHIFT),
align_items_u8: pack_align_items(AlignItems::NORMAL),
align_self_u8: ALIGN_SELF_NONE,
justify_content_u8: pack_align_content(JustifyContent::NORMAL),
align_content_u8: pack_align_content(AlignContent::NORMAL),
extra: None,
}
}
#[cold]
#[inline(never)]
fn clone_cold(&self) -> Self {
Self {
vals: self.vals,
gap_w_bf16: self.gap_w_bf16,
gap_h_bf16: self.gap_h_bf16,
flex_grow_bf16: self.flex_grow_bf16,
flex_shrink_bf16: self.flex_shrink_bf16,
len_tags: self.len_tags,
box_flags: self.box_flags,
mode_flags: self.mode_flags,
align_items_u8: self.align_items_u8,
align_self_u8: self.align_self_u8,
justify_content_u8: self.justify_content_u8,
align_content_u8: self.align_content_u8,
extra: self.extra.clone(),
}
}
#[cold]
#[inline(never)]
pub fn modify_cold(&mut self, f: impl FnOnce(&mut Style)) {
let whole = self.whole_rows();
let mut s = match self.extra.take() {
Some(b) => *b,
None => self.to_style(),
};
f(&mut s);
*self = Self::from_style(s);
if whole {
self.justify_content_u8 |= JUSTIFY_WHOLE_ROWS;
}
}
#[inline(always)]
pub fn display(&self) -> Display {
decode_display(self.mode_flags)
}
#[inline(always)]
pub fn position(&self) -> Position {
decode_position(self.mode_flags, self.extra.as_deref())
}
#[inline(always)]
pub fn flex_direction(&self) -> FlexDirection {
decode_dir(self.box_flags)
}
#[inline(always)]
pub fn flex_wrap(&self) -> FlexWrap {
decode_wrap(self.box_flags >> 2)
}
#[inline(always)]
pub fn size(&self) -> Size<Dimension> {
CoreStyle::size(self)
}
#[inline(always)]
pub fn min_size(&self) -> Size<LengthPercentageAuto> {
CoreStyle::min_size(self)
}
#[inline(always)]
pub fn max_size(&self) -> Size<LengthPercentageAuto> {
CoreStyle::max_size(self)
}
#[inline(always)]
pub fn padding(&self) -> Rect<LengthPercentage> {
CoreStyle::padding(self)
}
#[inline(always)]
pub fn inset(&self) -> Rect<LengthPercentageAuto> {
CoreStyle::inset(self)
}
#[inline(always)]
pub fn gap(&self) -> Size<LengthPercentage> {
FlexboxContainerStyle::gap(self)
}
#[inline(always)]
pub fn flex_grow(&self) -> f32 {
FlexboxItemStyle::flex_grow(self)
}
#[inline(always)]
pub fn flex_shrink(&self) -> f32 {
FlexboxItemStyle::flex_shrink(self)
}
#[inline(always)]
pub fn flex_basis(&self) -> Dimension {
FlexboxItemStyle::flex_basis(self)
}
#[inline(always)]
pub fn aspect_ratio(&self) -> Option<f32> {
CoreStyle::aspect_ratio(self)
}
#[inline(always)]
pub fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
#[inline(always)]
pub const fn whole_rows(&self) -> bool {
(self.justify_content_u8 & JUSTIFY_WHOLE_ROWS) != 0
}
#[inline(always)]
pub const fn whole_rows_column(&self) -> bool {
self.whole_rows()
&& matches!(decode_display(self.mode_flags), Display::Flex)
&& matches!(decode_dir(self.box_flags), FlexDirection::Column)
&& matches!(decode_wrap(self.box_flags >> 2), FlexWrap::NoWrap)
}
}
mod convert;
mod setters;
mod traits;
+420
View File
@@ -0,0 +1,420 @@
//! Builder setters for [`CompactStyle`].
use super::*;
impl CompactStyle {
#[inline(always)]
fn set_dim_slot(&mut self, idx: usize, raw: CompactLength, cold_set: impl FnOnce(&mut Style)) {
if self.extra.is_none() {
let (v, t) = pack_raw_len(raw);
if let Some(code) = encode_dim_tag(t) {
self.vals[idx] = v;
let shift = idx * 2;
self.len_tags = (self.len_tags & !(0b11 << shift)) | (code << shift);
return;
}
}
self.modify_cold(cold_set);
}
#[inline(always)]
pub fn set_width(&mut self, d: Dimension) {
self.set_dim_slot(IDX_SIZE_W, d.into_raw(), |s| s.size.width = d);
}
#[inline(always)]
pub fn set_height(&mut self, d: Dimension) {
self.set_dim_slot(IDX_SIZE_H, d.into_raw(), |s| s.size.height = d);
}
#[inline(always)]
pub fn set_size(&mut self, size: Size<Dimension>) {
self.set_width(size.width);
self.set_height(size.height);
}
#[inline(always)]
pub fn set_min_width(&mut self, d: LengthPercentageAuto) {
self.set_dim_slot(IDX_MIN_W, d.into_raw(), |s| s.min_size.width = d);
}
#[inline(always)]
pub fn set_min_height(&mut self, d: LengthPercentageAuto) {
self.set_dim_slot(IDX_MIN_H, d.into_raw(), |s| s.min_size.height = d);
}
#[inline(always)]
pub fn set_max_width(&mut self, d: LengthPercentageAuto) {
self.set_dim_slot(IDX_MAX_W, d.into_raw(), |s| s.max_size.width = d);
}
#[inline(always)]
pub fn set_max_height(&mut self, d: LengthPercentageAuto) {
self.set_dim_slot(IDX_MAX_H, d.into_raw(), |s| s.max_size.height = d);
}
#[inline(always)]
pub fn set_pad_left(&mut self, p: f32) {
if self.extra.is_none() {
self.vals[IDX_PAD_L] = p.to_bits();
self.len_tags &= !(1 << 12);
} else {
self.modify_cold(|s| s.padding.left = LengthPercentage::length(p));
}
}
#[inline(always)]
pub fn set_pad_right(&mut self, p: f32) {
if self.extra.is_none() {
self.vals[IDX_PAD_R] = p.to_bits();
self.len_tags &= !(1 << 13);
} else {
self.modify_cold(|s| s.padding.right = LengthPercentage::length(p));
}
}
#[inline(always)]
pub fn set_pad_top(&mut self, p: f32) {
if self.extra.is_none() {
self.vals[IDX_PAD_T] = p.to_bits();
self.len_tags &= !(1 << 14);
} else {
self.modify_cold(|s| s.padding.top = LengthPercentage::length(p));
}
}
#[inline(always)]
pub fn set_pad_bottom(&mut self, p: f32) {
if self.extra.is_none() {
self.vals[IDX_PAD_B] = p.to_bits();
self.len_tags &= !(1 << 15);
} else {
self.modify_cold(|s| s.padding.bottom = LengthPercentage::length(p));
}
}
#[inline(always)]
pub fn set_padding_all(&mut self, p: f32) {
if self.extra.is_none() {
let bits = p.to_bits();
self.vals[IDX_PAD_L] = bits;
self.vals[IDX_PAD_R] = bits;
self.vals[IDX_PAD_T] = bits;
self.vals[IDX_PAD_B] = bits;
self.len_tags &= !0xF000;
} else {
let lp = LengthPercentage::length(p);
self.modify_cold(|s| s.padding = Rect { left: lp, right: lp, top: lp, bottom: lp });
}
}
#[inline(always)]
pub fn set_gap(&mut self, column: f32, row: f32) {
if self.extra.is_none()
&& let (Some(cw), Some(rh)) = (pack_bf16_exact(column), pack_bf16_exact(row))
{
self.gap_w_bf16 = cw;
self.gap_h_bf16 = rh;
self.mode_flags &= !(MODE_GAP_W_PCT | MODE_GAP_H_PCT);
return;
}
self.modify_cold(|s| {
s.gap = Size {
width: LengthPercentage::length(column),
height: LengthPercentage::length(row),
};
});
}
#[inline(always)]
pub fn set_grow(&mut self, g: f32) {
if self.extra.is_none()
&& let Some(gb) = pack_bf16_exact(g)
{
self.flex_grow_bf16 = gb;
self.flex_shrink_bf16 = ONE_BF16;
self.mode_flags |= MODE_BASIS_ZERO;
return;
}
self.modify_cold(|s| {
s.flex_grow = g;
s.flex_shrink = 1.0;
s.flex_basis = Dimension::ZERO;
});
}
#[inline(always)]
pub fn set_flex_grow(&mut self, g: f32) {
if self.extra.is_none()
&& let Some(gb) = pack_bf16_exact(g)
{
self.flex_grow_bf16 = gb;
return;
}
self.modify_cold(|s| s.flex_grow = g);
}
#[inline(always)]
pub fn set_flex_shrink(&mut self, sh: f32) {
if self.extra.is_none()
&& let Some(sb) = pack_bf16_exact(sh)
{
self.flex_shrink_bf16 = sb;
return;
}
self.modify_cold(|s| s.flex_shrink = sh);
}
#[inline(always)]
pub fn set_flex_basis(&mut self, basis: Dimension) {
if self.extra.is_none() {
let (bits, tag) = pack_raw_len(basis.into_raw());
if tag as usize == CompactLength::AUTO_TAG {
self.mode_flags &= !MODE_BASIS_ZERO;
return;
}
if tag as usize == CompactLength::LENGTH_TAG && bits == 0 {
self.mode_flags |= MODE_BASIS_ZERO;
return;
}
}
self.modify_cold(|s| s.flex_basis = basis);
}
#[inline(always)]
pub fn set_flex_direction(&mut self, dir: FlexDirection) {
self.box_flags = (self.box_flags & !0b11) | encode_dir(dir);
if let Some(s) = &mut self.extra {
s.flex_direction = dir;
}
}
#[inline(always)]
pub fn set_flex_wrap(&mut self, wrap: FlexWrap) {
self.box_flags = (self.box_flags & !(0b11 << 2)) | (encode_wrap(wrap) << 2);
if let Some(s) = &mut self.extra {
s.flex_wrap = wrap;
}
}
#[inline(always)]
pub fn set_overflow(&mut self, x: Overflow, y: Overflow) {
self.box_flags = (self.box_flags & 0x0F) | (encode_overflow(x) << 4) | (encode_overflow(y) << 6);
if let Some(s) = &mut self.extra {
s.overflow = Point { x, y };
}
}
#[inline(always)]
pub fn set_align_items(&mut self, a: AlignItems) {
self.align_items_u8 = pack_align_items(a);
if let Some(s) = &mut self.extra {
s.align_items = a;
}
}
#[inline(always)]
pub fn set_align_self(&mut self, a: Option<AlignSelf>) {
self.align_self_u8 = pack_align_self(a);
if let Some(s) = &mut self.extra {
s.align_self = a;
}
}
#[inline(always)]
pub fn set_justify_content(&mut self, j: JustifyContent) {
self.justify_content_u8 = (self.justify_content_u8 & JUSTIFY_WHOLE_ROWS) | pack_align_content(j);
if let Some(s) = &mut self.extra {
s.justify_content = j;
}
}
#[inline(always)]
pub fn set_whole_rows(&mut self) {
self.justify_content_u8 |= JUSTIFY_WHOLE_ROWS;
}
#[inline(always)]
pub fn set_aspect_ratio(&mut self, ratio: Option<f32>) {
if self.extra.is_none() && ratio.is_none() {
return;
}
self.modify_cold(|s| s.aspect_ratio = ratio);
}
#[inline(always)]
pub fn set_equal_columns(&mut self, n: usize) {
self.modify_cold(|s| {
s.display = Display::Grid;
s.grid_template_columns = vec![fr(1.0); n.max(1)];
});
}
#[inline(always)]
pub fn set_grid_cell(&mut self, column: usize) {
self.modify_cold(|s| {
s.grid_column = Line {
start: line(column as i16 + 1),
end: span(1),
};
s.grid_row = Line {
start: line(1),
end: span(1),
};
});
}
#[inline(always)]
pub fn set_position_absolute(&mut self) {
if let Some(s) = &mut self.extra {
s.position = Position::Absolute;
}
self.mode_flags = (self.mode_flags & !MODE_POS_MASK) | (2 << MODE_POS_SHIFT);
}
#[inline(always)]
pub fn set_absolute_inset(&mut self, inset: Rect<LengthPercentageAuto>) {
if self.extra.is_none() && rect_is_auto_lpa(&inset) {
self.mode_flags = (self.mode_flags & !MODE_POS_MASK) | (2 << MODE_POS_SHIFT);
return;
}
self.modify_cold(|s| {
s.position = Position::Absolute;
s.inset = inset;
});
}
/// Border widths in points, `[top, right, bottom, left]`, which the box's padding and
/// content lay out inside.
#[inline(always)]
pub fn set_border(&mut self, [top, right, bottom, left]: [f32; 4]) {
if self.extra.is_none() && top == 0.0 && right == 0.0 && bottom == 0.0 && left == 0.0 { return; }
let l = LengthPercentage::length;
self.modify_cold(|s| s.border = Rect { left: l(left), right: l(right), top: l(top), bottom: l(bottom) });
}
#[inline(always)]
pub fn set_margin_left(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
self.modify_cold(|s| s.margin.left = LengthPercentageAuto::length(m));
}
#[inline(always)]
pub fn set_margin_right(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
self.modify_cold(|s| s.margin.right = LengthPercentageAuto::length(m));
}
#[inline(always)]
pub fn set_margin_top(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
self.modify_cold(|s| s.margin.top = LengthPercentageAuto::length(m));
}
#[inline(always)]
pub fn set_margin_bottom(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
self.modify_cold(|s| s.margin.bottom = LengthPercentageAuto::length(m));
}
#[inline(always)]
pub fn set_margin_x(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
let v = LengthPercentageAuto::length(m);
self.modify_cold(|s| { s.margin.left = v; s.margin.right = v; });
}
#[inline(always)]
pub fn set_margin_y(&mut self, m: f32) {
if self.extra.is_none() && m == 0.0 { return; }
let v = LengthPercentageAuto::length(m);
self.modify_cold(|s| { s.margin.top = v; s.margin.bottom = v; });
}
/// Moves this style's outer box sizing and placement onto a fresh column wrapper style and
/// resets this style's outer box to fill that column (`flex: 1 1 auto`, `min_size: 0`). The
/// wrapper keeps the overflow too, so a scroll viewport's wrapper is a scroll container: its
/// automatic minimum size is zero and its content doesn't size the ancestors around it.
pub fn take_box_placement(&mut self) -> Self {
if self.extra.is_none() {
let hidden = (self.mode_flags & MODE_DISPLAY_MASK) == encode_display(Display::None);
let mut outer = Self::rune_base(FlexDirection::Column);
outer.vals[..6].copy_from_slice(&self.vals[..6]);
outer.len_tags = (outer.len_tags & !0x0FFF) | (self.len_tags & 0x0FFF);
outer.flex_grow_bf16 = self.flex_grow_bf16;
outer.flex_shrink_bf16 = self.flex_shrink_bf16;
outer.mode_flags = (outer.mode_flags & !(MODE_DISPLAY_MASK | MODE_POS_MASK | MODE_BASIS_ZERO))
| (if hidden { encode_display(Display::None) } else { encode_display(Display::Flex) })
| (self.mode_flags & (MODE_POS_MASK | MODE_BASIS_ZERO));
outer.align_self_u8 = self.align_self_u8;
outer.box_flags = (outer.box_flags & 0x0F) | (self.box_flags & 0xF0);
self.vals[..6].fill(0);
self.len_tags = (self.len_tags & 0xF000) | 0b0000_1010_0000_1010;
self.flex_grow_bf16 = ONE_BF16;
self.flex_shrink_bf16 = ONE_BF16;
self.mode_flags = (self.mode_flags & !(MODE_DISPLAY_MASK | MODE_POS_MASK | MODE_BASIS_ZERO))
| encode_display(Display::Flex)
| (1 << MODE_POS_SHIFT);
self.align_self_u8 = ALIGN_SELF_NONE;
return outer;
}
let whole = self.whole_rows();
let mut s = match self.extra.take() {
Some(b) => *b,
None => self.to_style(),
};
let outer = Style {
display: if s.display == Display::None { Display::None } else { Display::Flex },
flex_direction: FlexDirection::Column,
overflow: s.overflow,
flex_shrink: s.flex_shrink,
flex_grow: s.flex_grow,
flex_basis: s.flex_basis,
position: s.position,
inset: s.inset,
size: s.size,
min_size: s.min_size,
max_size: s.max_size,
margin: s.margin,
align_self: s.align_self,
justify_self: s.justify_self,
aspect_ratio: s.aspect_ratio,
grid_row: s.grid_row,
grid_column: s.grid_column,
..Style::DEFAULT
};
if s.display == Display::None {
s.display = Display::Flex;
}
s.position = Position::Relative;
s.inset = Rect {
left: LengthPercentageAuto::AUTO,
right: LengthPercentageAuto::AUTO,
top: LengthPercentageAuto::AUTO,
bottom: LengthPercentageAuto::AUTO,
};
s.size = Size { width: Dimension::AUTO, height: Dimension::AUTO };
s.min_size = Size { width: LengthPercentageAuto::ZERO, height: LengthPercentageAuto::ZERO };
s.max_size = Size { width: LengthPercentageAuto::AUTO, height: LengthPercentageAuto::AUTO };
s.margin = Rect {
left: LengthPercentageAuto::ZERO,
right: LengthPercentageAuto::ZERO,
top: LengthPercentageAuto::ZERO,
bottom: LengthPercentageAuto::ZERO,
};
s.flex_grow = 1.0;
s.flex_shrink = 1.0;
s.flex_basis = Dimension::AUTO;
s.align_self = None;
s.justify_self = None;
s.aspect_ratio = None;
s.grid_row = Line { start: GridPlacement::Auto, end: GridPlacement::Auto };
s.grid_column = Line { start: GridPlacement::Auto, end: GridPlacement::Auto };
*self = Self::from_style(s);
if whole {
self.justify_content_u8 |= JUSTIFY_WHOLE_ROWS;
}
Self::from_style(outer)
}
}
+391
View File
@@ -0,0 +1,391 @@
//! Taffy style trait implementations (`CoreStyle`, `Flexbox*`, `Grid*`, `Block*`, `OofItemStyle`) for [`CompactStyle`].
use super::*;
impl CoreStyle for CompactStyle {
type CustomIdent = <Style as CoreStyle>::CustomIdent;
#[inline(always)]
fn box_generation_mode(&self) -> BoxGenerationMode {
match self.display() {
Display::None => BoxGenerationMode::None,
_ => BoxGenerationMode::Normal,
}
}
#[inline(always)]
fn is_block(&self) -> bool {
matches!(self.display(), Display::Block)
}
#[inline(always)]
fn is_compressible_replaced(&self) -> bool {
self.extra.as_ref().is_some_and(|s| s.item_is_replaced || s.item_is_compressible_replaced)
}
#[inline(always)]
fn is_replaced(&self) -> bool {
self.extra.as_ref().is_some_and(|s| s.item_is_replaced)
}
#[inline(always)]
fn box_sizing(&self) -> BoxSizing {
self.extra.as_ref().map_or(BoxSizing::BorderBox, |s| s.box_sizing)
}
#[inline(always)]
fn direction(&self) -> Direction {
self.extra.as_ref().map_or(Direction::Ltr, |s| s.direction)
}
#[inline(always)]
fn overflow(&self) -> Point<Overflow> {
Point {
x: decode_overflow(self.box_flags >> 4),
y: decode_overflow(self.box_flags >> 6),
}
}
#[inline(always)]
fn scrollbar_width(&self) -> f32 {
self.extra.as_ref().map_or(0.0, |s| s.scrollbar_width)
}
#[inline(always)]
fn position(&self) -> Position {
decode_position(self.mode_flags, self.extra.as_deref())
}
#[inline(always)]
fn inset(&self) -> Rect<LengthPercentageAuto> {
self.extra.as_ref().map_or(Rect::auto(), |s| s.inset)
}
#[inline(always)]
fn size(&self) -> Size<Dimension> {
if let Some(s) = &self.extra {
return s.size;
}
Size {
width: unpack_dim(self.vals[IDX_SIZE_W], self.len_tags),
height: unpack_dim(self.vals[IDX_SIZE_H], self.len_tags >> 2),
}
}
#[inline(always)]
fn min_size(&self) -> Size<LengthPercentageAuto> {
if let Some(s) = &self.extra {
return s.min_size;
}
Size {
width: unpack_lpa(self.vals[IDX_MIN_W], self.len_tags >> 4),
height: unpack_lpa(self.vals[IDX_MIN_H], self.len_tags >> 6),
}
}
#[inline(always)]
fn max_size(&self) -> Size<LengthPercentageAuto> {
if let Some(s) = &self.extra {
return s.max_size;
}
Size {
width: unpack_lpa(self.vals[IDX_MAX_W], self.len_tags >> 8),
height: unpack_lpa(self.vals[IDX_MAX_H], self.len_tags >> 10),
}
}
#[inline(always)]
fn aspect_ratio(&self) -> Option<f32> {
self.extra.as_ref().and_then(|s| s.aspect_ratio)
}
#[inline(always)]
fn margin(&self) -> Rect<LengthPercentageAuto> {
self.extra.as_ref().map_or(Rect::zero(), |s| s.margin)
}
#[inline(always)]
fn padding(&self) -> Rect<LengthPercentage> {
if let Some(s) = &self.extra {
return s.padding;
}
Rect {
left: unpack_lp(self.vals[IDX_PAD_L], (self.len_tags & (1 << 12)) != 0),
right: unpack_lp(self.vals[IDX_PAD_R], (self.len_tags & (1 << 13)) != 0),
top: unpack_lp(self.vals[IDX_PAD_T], (self.len_tags & (1 << 14)) != 0),
bottom: unpack_lp(self.vals[IDX_PAD_B], (self.len_tags & (1 << 15)) != 0),
}
}
#[inline(always)]
fn border(&self) -> Rect<LengthPercentage> {
self.extra.as_ref().map_or(Rect::zero(), |s| s.border)
}
#[inline(always)]
fn contain(&self) -> Contain {
self.extra.as_ref().map_or(Contain::NONE, |s| s.contain)
}
}
impl OofItemStyle for CompactStyle {
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
#[inline(always)]
fn justify_self(&self) -> Option<AlignSelf> {
self.extra.as_ref().and_then(|s| s.justify_self)
}
#[inline(always)]
fn is_table(&self) -> bool {
self.extra.as_ref().is_some_and(|s| s.item_is_table)
}
#[inline(always)]
fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
self.extra
.as_ref()
.map_or(Line { start: GridPlacement::Auto, end: GridPlacement::Auto }, |s| s.grid_row.clone())
}
#[inline(always)]
fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
self.extra
.as_ref()
.map_or(Line { start: GridPlacement::Auto, end: GridPlacement::Auto }, |s| s.grid_column.clone())
}
}
impl FlexboxContainerStyle for CompactStyle {
#[inline(always)]
fn flex_direction(&self) -> FlexDirection {
decode_dir(self.box_flags)
}
#[inline(always)]
fn flex_wrap(&self) -> FlexWrap {
decode_wrap(self.box_flags >> 2)
}
#[inline(always)]
fn gap(&self) -> Size<LengthPercentage> {
if let Some(s) = &self.extra {
return s.gap;
}
Size {
width: unpack_lp((self.gap_w_bf16 as u32) << 16, (self.mode_flags & MODE_GAP_W_PCT) != 0),
height: unpack_lp((self.gap_h_bf16 as u32) << 16, (self.mode_flags & MODE_GAP_H_PCT) != 0),
}
}
#[inline(always)]
fn align_content(&self) -> AlignContent {
unpack_align_content(self.align_content_u8)
}
#[inline(always)]
fn align_items(&self) -> AlignItems {
unpack_align_items(self.align_items_u8)
}
#[inline(always)]
fn justify_content(&self) -> JustifyContent {
unpack_align_content(self.justify_content_u8)
}
}
impl FlexboxItemStyle for CompactStyle {
#[inline(always)]
fn flex_basis(&self) -> Dimension {
if let Some(s) = &self.extra {
return s.flex_basis;
}
if (self.mode_flags & MODE_BASIS_ZERO) != 0 {
Dimension::ZERO
} else {
Dimension::AUTO
}
}
#[inline(always)]
fn flex_grow(&self) -> f32 {
if let Some(s) = &self.extra {
return s.flex_grow;
}
unpack_bf16(self.flex_grow_bf16)
}
#[inline(always)]
fn flex_shrink(&self) -> f32 {
if let Some(s) = &self.extra {
return s.flex_shrink;
}
unpack_bf16(self.flex_shrink_bf16)
}
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
}
impl GridContainerStyle for CompactStyle {
type Repetition<'a>
= <Style as GridContainerStyle>::Repetition<'a>
where
Self: 'a;
type TemplateTrackList<'a>
= <Style as GridContainerStyle>::TemplateTrackList<'a>
where
Self: 'a;
type AutoTrackList<'a>
= <Style as GridContainerStyle>::AutoTrackList<'a>
where
Self: 'a;
type TemplateLineNames<'a>
= <Style as GridContainerStyle>::TemplateLineNames<'a>
where
Self: 'a;
type GridTemplateAreas<'a>
= <Style as GridContainerStyle>::GridTemplateAreas<'a>
where
Self: 'a;
#[inline(always)]
fn grid_template_rows(&self) -> Option<Self::TemplateTrackList<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_rows(&**s))
}
#[inline(always)]
fn grid_template_columns(&self) -> Option<Self::TemplateTrackList<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_columns(&**s))
}
#[inline(always)]
fn grid_auto_rows(&self) -> Self::AutoTrackList<'_> {
self.extra.as_ref().map_or_else(|| [].iter().copied(), |s| GridContainerStyle::grid_auto_rows(&**s))
}
#[inline(always)]
fn grid_auto_columns(&self) -> Self::AutoTrackList<'_> {
self.extra.as_ref().map_or_else(|| [].iter().copied(), |s| GridContainerStyle::grid_auto_columns(&**s))
}
#[inline(always)]
fn grid_auto_flow(&self) -> GridAutoFlow {
self.extra.as_ref().map_or(GridAutoFlow::Row, |s| s.grid_auto_flow)
}
#[inline(always)]
fn gap(&self) -> Size<LengthPercentage> {
FlexboxContainerStyle::gap(self)
}
#[inline(always)]
fn align_content(&self) -> AlignContent {
unpack_align_content(self.align_content_u8)
}
#[inline(always)]
fn justify_content(&self) -> JustifyContent {
unpack_align_content(self.justify_content_u8)
}
#[inline(always)]
fn align_items(&self) -> AlignItems {
unpack_align_items(self.align_items_u8)
}
#[inline(always)]
fn justify_items(&self) -> AlignItems {
self.extra.as_ref().map_or(AlignItems::NORMAL, |s| s.justify_items)
}
#[inline(always)]
fn grid_template_areas(&self) -> Option<Self::GridTemplateAreas<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_areas(&**s))
}
#[inline(always)]
fn grid_template_area_row_count(&self) -> u16 {
self.extra.as_ref().map_or(0, |s| GridContainerStyle::grid_template_area_row_count(&**s))
}
#[inline(always)]
fn grid_template_area_column_count(&self) -> u16 {
self.extra.as_ref().map_or(0, |s| GridContainerStyle::grid_template_area_column_count(&**s))
}
#[inline(always)]
fn grid_template_column_names(&self) -> Option<Self::TemplateLineNames<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_column_names(&**s))
}
#[inline(always)]
fn grid_template_row_names(&self) -> Option<Self::TemplateLineNames<'_>> {
self.extra.as_ref().and_then(|s| GridContainerStyle::grid_template_row_names(&**s))
}
}
impl GridItemStyle for CompactStyle {
#[inline(always)]
fn grid_row(&self) -> Line<GridPlacement<Self::CustomIdent>> {
OofItemStyle::grid_row(self)
}
#[inline(always)]
fn grid_column(&self) -> Line<GridPlacement<Self::CustomIdent>> {
OofItemStyle::grid_column(self)
}
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
#[inline(always)]
fn justify_self(&self) -> Option<AlignSelf> {
self.extra.as_ref().and_then(|s| s.justify_self)
}
}
impl BlockContainerStyle for CompactStyle {
#[inline(always)]
fn text_align(&self) -> TextAlign {
self.extra.as_ref().map_or(TextAlign::Auto, |s| s.text_align)
}
#[inline(always)]
fn align_content(&self) -> AlignContent {
unpack_align_content(self.align_content_u8)
}
#[inline(always)]
fn justify_items(&self) -> AlignItems {
self.extra.as_ref().map_or(AlignItems::NORMAL, |s| s.justify_items)
}
}
impl BlockItemStyle for CompactStyle {
#[inline(always)]
fn is_table(&self) -> bool {
self.extra.as_ref().is_some_and(|s| s.item_is_table)
}
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> {
unpack_align_self(self.align_self_u8)
}
#[inline(always)]
fn justify_self(&self) -> Option<AlignSelf> {
self.extra.as_ref().and_then(|s| s.justify_self)
}
}
+917
View File
@@ -0,0 +1,917 @@
#![forbid(unsafe_code)]
use crate::prelude::*;
use crate::{
BaselineLayoutStore, BaselineTaffyTree, BoxLayout, CompactCache, CompactStyle, LayoutStore, SlotId,
baseline_storage_stats,
};
use core::mem::size_of;
use taffy::geometry::{Line, Point, Rect, Size};
use taffy::style::{AvailableSpace, CoreStyle, FlexboxContainerStyle, FlexboxItemStyle, Overflow};
use taffy::tree::{Baselines, CollapsibleMarginSet, LayoutInput, LayoutOutput, RequestedAxis, RunMode, SizingMode};
#[test]
fn compact_types_stay_within_size_budgets() {
assert_eq!(size_of::<CompactStyle>(), 64);
assert_eq!(size_of::<CompactCache>(), 96);
assert_eq!(size_of::<BoxLayout>(), 32);
}
#[test]
fn compact_style_round_trips_all_length_variants() {
let hot_dims = [
Dimension::auto(),
Dimension::ZERO,
Dimension::length(42.5),
Dimension::percent(0.375),
Dimension::max_content(),
];
for &w in &hot_dims {
for &h in &hot_dims {
let s = Style {
display: Display::Flex,
position: Position::Relative,
flex_direction: FlexDirection::ColumnReverse,
flex_wrap: FlexWrap::Wrap,
overflow: Point { x: Overflow::Hidden, y: Overflow::Scroll },
size: Size { width: w, height: h },
min_size: Size { width: length(10.0), height: percent(0.25) },
max_size: Size { width: auto(), height: length(500.0) },
padding: Rect {
left: length(4.0),
right: percent(0.125),
top: length(8.0),
bottom: length(12.0),
},
gap: Size { width: length(6.0), height: percent(0.25) },
flex_basis: Dimension::ZERO,
flex_grow: 1.5,
flex_shrink: 0.25,
align_items: AlignItems::CENTER,
align_self: Some(AlignSelf::FLEX_END),
justify_content: JustifyContent::SPACE_BETWEEN,
align_content: AlignContent::STRETCH,
..Style::DEFAULT
};
let compact = CompactStyle::from_style(s.clone());
assert_eq!(compact.heap_bytes(), 0, "hot Rune style should stay 100% inline in 64 bytes");
assert!(compact == s);
assert_eq!(compact.to_style(), s);
}
}
let all_dims = [
Dimension::auto(),
Dimension::ZERO,
Dimension::length(42.5),
Dimension::percent(0.375),
Dimension::min_content(),
Dimension::max_content(),
Dimension::fit_content_px(120.0),
Dimension::fit_content_percent(0.8),
];
for &w in &all_dims {
for &h in &all_dims {
let s = Style {
display: Display::Flex,
position: Position::Relative,
flex_direction: FlexDirection::ColumnReverse,
flex_wrap: FlexWrap::Wrap,
overflow: Point { x: Overflow::Hidden, y: Overflow::Scroll },
size: Size { width: w, height: h },
min_size: Size { width: length(10.0), height: percent(0.25) },
max_size: Size { width: auto(), height: length(500.0) },
padding: Rect {
left: length(4.0),
right: percent(0.1),
top: length(8.0),
bottom: length(12.0),
},
gap: Size { width: length(6.0), height: percent(0.05) },
flex_basis: w,
flex_grow: 1.5,
flex_shrink: 0.25,
aspect_ratio: Some(1.75),
align_items: AlignItems::CENTER,
align_self: Some(AlignSelf::FLEX_END),
justify_content: JustifyContent::SPACE_BETWEEN,
align_content: AlignContent::STRETCH,
..Style::DEFAULT
};
let compact = CompactStyle::from_style(s.clone());
assert!(compact == s);
assert_eq!(compact.to_style(), s);
assert_eq!(CoreStyle::size(&compact), s.size);
assert_eq!(CoreStyle::min_size(&compact), s.min_size);
assert_eq!(CoreStyle::max_size(&compact), s.max_size);
assert_eq!(CoreStyle::padding(&compact), s.padding);
assert_eq!(FlexboxContainerStyle::gap(&compact), s.gap);
assert_eq!(FlexboxItemStyle::flex_basis(&compact), s.flex_basis);
}
}
}
#[test]
fn compact_cache_preserves_second_chance_and_overflow_semantics() {
let make_input = |w: f32| LayoutInput {
run_mode: RunMode::ComputeSize,
sizing_mode: SizingMode::InherentSize,
axis: RequestedAxis::Both,
known_dimensions: Size { width: Some(w), height: None },
known_dimensions_are_definite: Size { width: true, height: true },
parent_size: Size::NONE,
available_space: Size { width: AvailableSpace::MaxContent, height: AvailableSpace::MaxContent },
vertical_margins_are_collapsible: Line::FALSE,
};
let make_out = |w: f32| LayoutOutput::from_outer_size(Size { width: w, height: w * 2.0 });
let mut cache = CompactCache::new();
cache.store(&make_input(0.0), make_out(0.0));
cache.store(&make_input(1.0), make_out(1.0));
assert_eq!(cache.heap_bytes(), 0);
for w in 2..9 {
cache.store(&make_input(w as f32), make_out(w as f32));
}
assert!(cache.heap_bytes() > 0);
cache.store(&make_input(9.0), make_out(9.0));
assert_eq!(cache.get(&make_input(1.0)), Some(make_out(1.0)));
cache.store(&make_input(10.0), make_out(10.0));
assert_eq!(cache.get(&make_input(1.0)), Some(make_out(1.0)));
assert_eq!(cache.get(&make_input(2.0)), None);
let mut collapse = make_out(99.0);
collapse.top_margin = CollapsibleMarginSet::from_margin(8.0);
cache.store(&make_input(99.0), collapse);
assert_eq!(cache.get(&make_input(99.0)), None);
}
#[test]
fn compact_style_setters_match_taffy_style() {
for dir in [
FlexDirection::Row,
FlexDirection::Column,
FlexDirection::RowReverse,
FlexDirection::ColumnReverse,
] {
let mut cs = CompactStyle::rune_base(dir);
let mut ts = Style {
display: Display::Flex,
flex_direction: dir,
flex_shrink: 0.0,
position: Position::Relative,
..Style::DEFAULT
};
assert_eq!(cs.to_style(), ts);
assert_eq!(cs, CompactStyle::from_style(ts.clone()));
cs.set_width(percent(1.0));
ts.size.width = percent(1.0);
cs.set_height(length(48.5));
ts.size.height = length(48.5);
cs.set_min_width(length(0.0));
ts.min_size.width = length(0.0);
cs.set_max_height(length(240.0));
ts.max_size.height = length(240.0);
cs.set_padding_all(12.0);
ts.padding = Rect { left: length(12.0), right: length(12.0), top: length(12.0), bottom: length(12.0) };
cs.set_pad_left(6.0);
ts.padding.left = length(6.0);
cs.set_gap(8.0, 4.0);
ts.gap = Size { width: length(8.0), height: length(4.0) };
cs.set_grow(1.5);
ts.flex_grow = 1.5;
ts.flex_shrink = 1.0;
ts.flex_basis = length(0.0);
cs.set_flex_wrap(FlexWrap::Wrap);
ts.flex_wrap = FlexWrap::Wrap;
cs.set_overflow(Overflow::Hidden, Overflow::Scroll);
ts.overflow = Point { x: Overflow::Hidden, y: Overflow::Scroll };
cs.set_align_items(AlignItems::CENTER);
ts.align_items = AlignItems::CENTER;
cs.set_align_self(Some(AlignSelf::STRETCH));
ts.align_self = Some(AlignSelf::STRETCH);
cs.set_justify_content(JustifyContent::SPACE_BETWEEN);
ts.justify_content = JustifyContent::SPACE_BETWEEN;
assert_eq!(cs.heap_bytes(), 0, "hot setters should stay inline");
assert_eq!(cs.to_style(), ts);
assert_eq!(cs, CompactStyle::from_style(ts.clone()));
cs.set_aspect_ratio(Some(1.75));
ts.aspect_ratio = Some(1.75);
assert_eq!(cs.to_style(), ts);
cs.set_aspect_ratio(None);
ts.aspect_ratio = None;
assert_eq!(cs.heap_bytes(), 0, "clearing last cold field drops extra Box");
assert_eq!(cs.to_style(), ts);
}
for pos in [Position::Static, Position::Relative, Position::Absolute] {
let s = Style { position: pos, ..Style::DEFAULT };
let c = CompactStyle::from_style(s.clone());
assert_eq!(c.position(), pos);
assert_eq!(c.to_style(), s);
}
}
#[test]
fn a_taken_box_placement_keeps_the_overflow_on_the_wrapper() {
for cold in [false, true] {
let mut cs = CompactStyle::rune_base(FlexDirection::Column);
cs.set_overflow(Overflow::Hidden, Overflow::Scroll);
if cold {
cs.set_aspect_ratio(Some(2.0));
}
let outer = cs.take_box_placement();
assert_eq!(outer.overflow(), Point { x: Overflow::Hidden, y: Overflow::Scroll }, "cold {cold}");
assert_eq!(cs.overflow(), Point { x: Overflow::Hidden, y: Overflow::Scroll }, "cold {cold}");
}
}
#[derive(Clone)]
struct SpecNode {
key: u64,
style: Style,
leaf: Option<(u64, f32, f32, f32)>, // (measure_hash, intrinsic_w, line_h, baseline)
children: Vec<SpecNode>,
}
struct CommitEntry {
key: u64,
parent: Option<usize>,
comp_slot: SlotId,
base_slot: SlotId,
leaf: Option<(f32, f32, f32)>,
}
fn sync_pair(
spec: &SpecNode,
parent: Option<usize>,
comp: &mut LayoutStore,
base: &mut BaselineLayoutStore,
out: &mut Vec<CommitEntry>,
) -> (SlotId, bool, SlotId) {
let me = out.len();
out.push(CommitEntry {
key: spec.key,
parent,
comp_slot: SlotId(0),
base_slot: SlotId(0),
leaf: spec.leaf.map(|(_, w, h, b)| (w, h, b)),
});
let c_mark = comp.begin_children();
let b_mark = base.begin_children();
let mut kids_dirty = false;
let mut c_kids = Vec::with_capacity(spec.children.len());
let mut b_kids = Vec::with_capacity(spec.children.len());
for child in &spec.children {
let (cs, cd, bs) = sync_pair(child, Some(me), comp, base, out);
kids_dirty |= cd;
c_kids.push(cs);
b_kids.push(bs);
}
for cs in c_kids {
comp.push_child(cs);
}
for bs in b_kids {
base.push_child(bs);
}
let measure = spec.leaf.map(|(h, ..)| h);
let cs_style = CompactStyle::from_style(spec.style.clone());
let (c_slot, dirty) = comp.sync_node(spec.key, me as u32, cs_style.clone(), measure, false, c_mark, kids_dirty);
let (b_slot, _) = base.sync_node(spec.key, me as u32, cs_style, measure, false, b_mark, kids_dirty);
out[me].comp_slot = c_slot;
out[me].base_slot = b_slot;
(c_slot, dirty, b_slot)
}
fn commit_and_assert_parity(
root: &SpecNode,
room: Size<AvailableSpace>,
comp: &mut LayoutStore,
base: &mut BaselineLayoutStore,
) -> (Vec<CommitEntry>, Vec<u64>, Vec<u64>) {
comp.begin_commit();
base.begin_commit();
let mut entries = Vec::new();
let (mut c_root, _, mut b_root) = sync_pair(root, None, comp, base, &mut entries);
comp.end_commit(&mut c_root, |me, slot| entries[me as usize].comp_slot = slot);
base.end_commit(&mut b_root, |me, slot| entries[me as usize].base_slot = slot);
assert_eq!(comp.live_count(), entries.len());
assert_eq!(base.live_count(), entries.len());
let eval_leaf = |inputs: LayoutInput, ctx: Option<usize>, style: &CompactStyle, log: &mut Vec<u64>| {
let mut baselines = Baselines::NONE;
let mut out = taffy::compute_leaf_layout(inputs, style, |_, _| 0.0, |known, avail| {
let Some(i) = ctx else { return Size::ZERO };
log.push(entries[i].key);
let (full_w, line_h, baseline) = entries[i].leaf.expect("ctx must point to measured leaf");
let max_w = known.width.or(match avail.width {
AvailableSpace::Definite(w) => Some(w),
AvailableSpace::MinContent => Some((full_w * 0.25).max(20.0)),
AvailableSpace::MaxContent => None,
});
let (w, lines) = match max_w {
Some(limit) if full_w > limit && limit > 0.0 => (limit, (full_w / limit).ceil().max(1.0)),
_ => (full_w, 1.0),
};
if baseline > 0.0 {
baselines = Baselines { first: Some(baseline), last: Some((lines - 1.0) * line_h + baseline) };
}
Size {
width: known.width.unwrap_or(w),
height: known.height.unwrap_or(lines * line_h),
}
});
out.baselines = baselines;
out
};
let mut c_log = Vec::new();
let mut b_log = Vec::new();
comp.compute_layout(c_root, room, |inputs, ctx, style| eval_leaf(inputs, ctx, style, &mut c_log));
base.compute_layout(b_root, room, |inputs, ctx, style| eval_leaf(inputs, ctx, style, &mut b_log));
for (i, e) in entries.iter().enumerate() {
assert_eq!(
comp.box_layout(e.comp_slot),
base.box_layout(e.base_slot),
"BoxLayout mismatch at entry {i} (key={})",
e.key
);
}
(entries, c_log, b_log)
}
#[test]
fn differential_flex_grid_oof_scroll_text_baselines_reorder_and_removal() {
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
let text_style = Style {
flex_shrink: 1.0,
min_size: Size { width: length(0.0), height: auto() },
max_size: Size { width: length(180.0), height: length(100.0) },
..Style::DEFAULT
};
let build_scene = |reordered: bool, scaled: bool, removed: bool| {
let t1 = SpecNode {
key: 11,
style: text_style.clone(),
leaf: Some(if scaled { (2, 310.0, 20.0, 15.5) } else { (1, 240.0, 18.0, 14.0) }),
children: vec![],
};
let t2 = SpecNode {
key: 12,
style: text_style.clone(),
leaf: Some((3, 95.5, 22.0, 17.0)),
children: vec![],
};
let flex_row = SpecNode {
key: 10,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
flex_wrap: FlexWrap::Wrap,
align_items: AlignItems::BASELINE,
gap: Size { width: length(8.25), height: length(4.5) },
padding: Rect { left: length(10.5), right: length(10.5), top: length(6.25), bottom: length(6.25) },
..Style::DEFAULT
},
leaf: None,
children: if reordered { vec![t2, t1] } else { vec![t1, t2] },
};
let mut grid_kids = vec![SpecNode {
key: 21,
style: Style {
grid_column: Line { start: line(1), end: span(2) },
grid_row: Line { start: line(1), end: span(1) },
size: Size { width: auto(), height: length(28.5) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
}];
if !removed {
grid_kids.push(SpecNode {
key: 22,
style: Style {
grid_column: Line { start: line(3), end: span(1) },
grid_row: Line { start: line(1), end: span(1) },
aspect_ratio: Some(1.5),
..Style::DEFAULT
},
leaf: None,
children: vec![],
});
}
let grid = SpecNode {
key: 20,
style: Style {
display: Display::Grid,
grid_template_columns: vec![fr(1.0), fr(2.0), minmax(length(40.0), fr(1.0))],
gap: Size { width: length(6.0), height: length(6.0) },
size: Size { width: percent(1.0), height: auto() },
..Style::DEFAULT
},
leaf: None,
children: grid_kids,
};
let scroll = SpecNode {
key: 30,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
position: Position::Relative,
overflow: Point { x: Overflow::Hidden, y: Overflow::Scroll },
flex_grow: 1.0,
flex_shrink: 1.0,
flex_basis: length(0.0),
min_size: Size { width: length(0.0), height: length(0.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: 31,
style: Style { size: Size { width: percent(1.0), height: length(420.0) }, flex_shrink: 0.0, ..Style::DEFAULT },
leaf: None,
children: vec![],
},
SpecNode {
key: 32,
style: Style {
position: Position::Absolute,
inset: Rect { left: length(12.25), top: length(8.75), right: auto(), bottom: auto() },
size: Size { width: length(64.0), height: length(24.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
},
],
};
SpecNode {
key: 1,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
position: Position::Relative,
size: Size { width: length(360.0), height: length(240.0) },
gap: Size { width: length(0.0), height: length(8.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![flex_row, grid, scroll],
}
};
let room = Size {
width: AvailableSpace::Definite(360.0),
height: AvailableSpace::Definite(240.0),
};
let (_, c1, b1) = commit_and_assert_parity(&build_scene(false, false, false), room, &mut comp, &mut base);
assert_eq!(c1, b1);
let (_, c2, b2) = commit_and_assert_parity(&build_scene(true, true, true), room, &mut comp, &mut base);
assert_eq!(c2, b2);
}
#[test]
fn large_to_small_swap_shrinks_retained_memory_and_matches_baseline() {
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
let make_list = |rows: usize| {
let mut children = Vec::with_capacity(rows);
for i in 0..rows {
let base_key = 100 + (i as u64) * 10;
children.push(SpecNode {
key: base_key,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
size: Size { width: percent(1.0), height: length(32.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: base_key + 1,
style: Style { size: Size { width: length(120.0), height: length(18.0) }, ..Style::DEFAULT },
leaf: Some((i as u64 + 1, 120.0, 18.0, 14.0)),
children: vec![],
},
SpecNode {
key: base_key + 2,
style: Style { size: Size { width: length(20.0), height: length(20.0) }, ..Style::DEFAULT },
leaf: None,
children: vec![],
},
],
});
}
SpecNode {
key: 1,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
size: Size { width: length(1000.0), height: length(900.0) },
..Style::DEFAULT
},
leaf: None,
children,
}
};
let room = Size {
width: AvailableSpace::Definite(1000.0),
height: AvailableSpace::Definite(900.0),
};
commit_and_assert_parity(&make_list(500), room, &mut comp, &mut base);
let b_stats_500 = base.storage_stats();
let c_stats_500 = comp.storage_stats();
assert!(
c_stats_500.total_retained_bytes * 2 < b_stats_500.total_retained_bytes,
"expected >50% reduction at 500 rows: compact={} vs baseline={}",
c_stats_500.total_retained_bytes,
b_stats_500.total_retained_bytes
);
commit_and_assert_parity(&make_list(10), room, &mut comp, &mut base);
let b_stats_10 = base.storage_stats();
let c_stats_10 = comp.storage_stats();
assert!(
c_stats_10.slot_capacity <= 64,
"LayoutStore slot capacity should shrink after 500->10 swap, got {}",
c_stats_10.slot_capacity
);
assert!(
c_stats_10.total_retained_bytes * 10 < b_stats_10.total_retained_bytes,
"expected >90% reduction after 500->10 swap: compact={} vs baseline={}",
c_stats_10.total_retained_bytes,
b_stats_10.total_retained_bytes
);
}
#[test]
fn differential_hoisted_oof_aspect_fit_anchored_fit_and_cache_hits() {
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
let scene = SpecNode {
key: 1,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
position: Position::Relative,
size: Size { width: length(400.0), height: length(300.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: 10,
style: Style {
display: Display::Flex,
position: Position::Static,
padding: Rect { left: length(7.25), right: length(7.25), top: length(5.5), bottom: length(5.5) },
..Style::DEFAULT
},
leaf: None,
children: vec![SpecNode {
key: 11,
style: Style {
position: Position::Absolute,
inset: Rect { left: auto(), right: length(14.5), top: length(9.25), bottom: auto() },
size: Size { width: length(88.0), height: length(36.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
}],
},
SpecNode {
key: 20,
style: Style {
flex_grow: 1.0,
size: Size { width: percent(1.0), height: auto() },
..Style::DEFAULT
},
leaf: None,
children: vec![],
},
SpecNode {
key: 30,
style: Style {
position: Position::Absolute,
inset: Rect { left: length(0.0), top: length(0.0), right: auto(), bottom: auto() },
size: Size { width: length(160.0), height: auto() },
..Style::DEFAULT
},
leaf: None,
children: vec![SpecNode {
key: 31,
style: Style { size: Size { width: percent(1.0), height: auto() }, ..Style::DEFAULT },
leaf: Some((99, 160.0, 320.0, 0.0)),
children: vec![],
}],
},
],
};
let room = Size {
width: AvailableSpace::Definite(400.0),
height: AvailableSpace::Definite(300.0),
};
let (_, c_cold, b_cold) = commit_and_assert_parity(&scene, room, &mut comp, &mut base);
assert!(!c_cold.is_empty());
assert_eq!(c_cold, b_cold, "measure call count mismatch on cold pass");
// Warm commit with zero changes hits root cache (0 leaf measurements).
let (entries, c_warm, b_warm) = commit_and_assert_parity(&scene, room, &mut comp, &mut base);
assert!(c_warm.is_empty());
assert!(b_warm.is_empty());
// Pass 2 intra-commit refit: clamp `aspect_fit` (key 20) to 16:9 and `anchored_fit` (key 30) max_size.height.
let aspect_idx = entries.iter().position(|e| e.key == 20).unwrap();
let ov_idx = entries.iter().position(|e| e.key == 30).unwrap();
let room_sz = comp.box_layout(entries[aspect_idx].comp_slot).size();
let fit_w = room_sz.width.min(room_sz.height * (16.0 / 9.0));
let fit_h = fit_w / (16.0 / 9.0);
let fitted = CompactStyle::from_style(Style {
size: Size { width: length(fit_w), height: length(fit_h) },
flex_shrink: 0.0,
..Style::DEFAULT
});
comp.set_style_and_mark_ancestors(
entries[aspect_idx].comp_slot,
fitted.clone(),
core::iter::successors(entries[aspect_idx].parent, |&p| entries[p].parent).map(|p| entries[p].comp_slot),
);
base.set_style_and_mark_ancestors(
entries[aspect_idx].base_slot,
fitted,
core::iter::successors(entries[aspect_idx].parent, |&p| entries[p].parent).map(|p| entries[p].base_slot),
);
let mut ov_style = comp.style(entries[ov_idx].comp_slot).clone();
ov_style.set_max_height(length(180.0));
comp.set_style_and_mark_ancestors(
entries[ov_idx].comp_slot,
ov_style.clone(),
core::iter::successors(entries[ov_idx].parent, |&p| entries[p].parent).map(|p| entries[p].comp_slot),
);
base.set_style_and_mark_ancestors(
entries[ov_idx].base_slot,
ov_style,
core::iter::successors(entries[ov_idx].parent, |&p| entries[p].parent).map(|p| entries[p].base_slot),
);
let mut c_pass2 = 0usize;
let mut b_pass2 = 0usize;
comp.compute_layout(entries[0].comp_slot, room, |inputs, _ctx, style| {
taffy::compute_leaf_layout(inputs, style, |_, _| 0.0, |known, _| {
c_pass2 += 1;
Size { width: known.width.unwrap_or(160.0), height: known.height.unwrap_or(320.0) }
})
});
base.compute_layout(entries[0].base_slot, room, |inputs, _ctx, style| {
taffy::compute_leaf_layout(inputs, style, |_, _| 0.0, |known, _| {
b_pass2 += 1;
Size { width: known.width.unwrap_or(160.0), height: known.height.unwrap_or(320.0) }
})
});
assert_eq!(c_pass2, b_pass2, "measure call count mismatch after aspect_fit + anchored_fit refit");
for (i, e) in entries.iter().enumerate() {
assert_eq!(comp.box_layout(e.comp_slot), base.box_layout(e.base_slot), "refit mismatch at {i}");
}
}
#[test]
fn layout_store_carries_cache_across_commits_and_matches_upstream_bit_for_bit() {
let make_row = |id_base: u64, text_w: f32, hash: u64| SpecNode {
key: id_base,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Row,
flex_shrink: 0.0,
position: Position::Relative,
size: Size { width: percent(1.0), height: auto() },
padding: Rect { left: length(8.0), right: length(8.0), top: length(4.0), bottom: length(4.0) },
gap: Size { width: length(6.0), height: length(0.0) },
align_items: AlignItems::CENTER,
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: id_base + 1,
style: Style { size: Size { width: length(16.0), height: length(16.0) }, flex_shrink: 0.0, ..Style::DEFAULT },
leaf: None,
children: vec![],
},
SpecNode {
key: id_base + 2,
style: Style {
flex_grow: 1.0,
flex_shrink: 1.0,
flex_basis: length(0.0),
min_size: Size { width: length(0.0), height: auto() },
..Style::DEFAULT
},
leaf: Some((hash, text_w, 16.0, 0.0)),
children: vec![],
},
],
};
let make_tree = |rows: Vec<SpecNode>, vp_w: f32| {
let grid_header = SpecNode {
key: 10,
style: Style {
display: Display::Grid,
position: Position::Relative,
size: Size { width: percent(1.0), height: auto() },
gap: Size { width: length(8.0), height: length(4.0) },
grid_template_columns: vec![fr(1.0), fr(2.0)],
..Style::DEFAULT
},
leaf: None,
children: vec![
SpecNode {
key: 11,
style: Style { size: Size { width: auto(), height: length(24.0) }, ..Style::DEFAULT },
leaf: None,
children: vec![],
},
SpecNode {
key: 12,
style: Style { size: Size { width: auto(), height: length(24.0) }, ..Style::DEFAULT },
leaf: Some((999, 180.0, 18.0, 0.0)),
children: vec![],
},
SpecNode {
key: 13,
style: Style {
position: Position::Absolute,
inset: Rect { left: auto(), top: length(2.0), right: length(4.0), bottom: auto() },
size: Size { width: length(20.0), height: length(12.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
},
],
};
let static_oof = SpecNode {
key: 20,
style: Style { position: Position::Static, size: Size { width: percent(1.0), height: length(10.0) }, ..Style::DEFAULT },
leaf: None,
children: vec![SpecNode {
key: 21,
style: Style {
position: Position::Absolute,
inset: Rect { left: length(12.0), top: auto(), right: length(12.0), bottom: length(6.0) },
size: Size { width: auto(), height: length(18.0) },
..Style::DEFAULT
},
leaf: None,
children: vec![],
}],
};
let hidden = SpecNode {
key: 30,
style: Style { display: Display::None, size: Size { width: length(90.0), height: length(90.0) }, ..Style::DEFAULT },
leaf: None,
children: vec![make_row(31, 100.0, 31)],
};
let mut children = vec![grid_header, static_oof, hidden];
children.extend(rows);
SpecNode {
key: 1,
style: Style {
display: Display::Flex,
flex_direction: FlexDirection::Column,
position: Position::Relative,
size: Size { width: length(vp_w), height: length(500.0) },
padding: Rect { left: length(10.0), right: length(10.0), top: length(8.0), bottom: length(8.0) },
gap: Size { width: length(0.0), height: length(4.0) },
..Style::DEFAULT
},
leaf: None,
children,
}
};
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
let room = |vp_w: f32| Size {
width: AvailableSpace::Definite(vp_w),
height: AvailableSpace::Definite(500.0),
};
let rows_1: Vec<SpecNode> = (0..8).map(|i| make_row(100 + i * 10, 220.0 + (i as f32) * 35.0, 1000 + i)).collect();
// Commit 1 (Cold): measures leaves and matches BaselineLayoutStore bit-for-bit.
let (entries_1, keys_1, _) = commit_and_assert_parity(&make_tree(rows_1.clone(), 360.0), room(360.0), &mut comp, &mut base);
assert!(keys_1.len() >= 9);
let mut raw_base = BaselineTaffyTree::<usize>::new();
let raw_leaf = raw_base.new_leaf(Style::DEFAULT).unwrap();
let base_bytes = baseline_storage_stats(&raw_base, Some(raw_leaf), entries_1.len()).total_retained_bytes;
assert!(comp.storage_stats().total_retained_bytes * 2 < base_bytes);
// Commit 2 (Warm identical): hits root cache — 0 leaf measurements!
let (_, keys_2, _) = commit_and_assert_parity(&make_tree(rows_1.clone(), 360.0), room(360.0), &mut comp, &mut base);
assert!(keys_2.is_empty(), "warm commit with no changes must invoke measure 0 times");
// Commit 3 (Insert row 90 at front — shifts every existing row's `me` index by +3!):
let mut rows_3 = vec![make_row(90, 310.0, 9999)];
rows_3.extend(rows_1);
let (_, keys_3, _) = commit_and_assert_parity(&make_tree(rows_3.clone(), 360.0), room(360.0), &mut comp, &mut base);
assert!(!keys_3.is_empty());
assert!(keys_3.iter().all(|&k| k == 92), "only newly inserted row leaf (key=92) may measure; got {keys_3:?}");
// Commit 4 (Narrow viewport width from 360 -> 280 after index shift):
let (_, keys_4, _) = commit_and_assert_parity(&make_tree(rows_3.clone(), 280.0), room(280.0), &mut comp, &mut base);
assert!(keys_4.len() >= 9, "narrowed viewport must re-measure shifted leaves");
// Commit 5 (Remove 3 rows, reorder remaining rows, insert 2 new rows recycling freed slots, mutate 1 leaf hash):
let mut rows_5 = vec![
rows_3[5].clone(),
make_row(500, 410.0, 5001),
rows_3[2].clone(),
make_row(510, 145.0, 5002),
rows_3[0].clone(),
];
rows_5[2].children[1].leaf = Some((77777, 480.0, 16.0, 0.0));
let (_, keys_5, _) = commit_and_assert_parity(&make_tree(rows_5, 280.0), room(280.0), &mut comp, &mut base);
assert!(keys_5.contains(&502) && keys_5.contains(&512) && keys_5.contains(&112));
assert!(!keys_5.contains(&92) && !keys_5.contains(&142), "unchanged reordered rows must hit cache");
}
#[test]
fn memo_reuse_and_retry_mutation_guard_match_baseline() {
let mut comp = LayoutStore::new();
let mut base = BaselineLayoutStore::new();
// Commit 1 (applied): create slot for key 10 with width 120.
comp.begin_commit();
base.begin_commit();
let mut s1 = CompactStyle::rune_base(FlexDirection::Row);
s1.set_width(length(120.0));
s1.set_height(length(40.0));
let m_c = comp.begin_children();
let (slot_c, _) = comp.sync_node(10, 0, s1.clone(), None, false, m_c, false);
comp.finish_flatten();
comp.compact_if_sparse(|_, _| {});
let m_b = base.begin_children();
let (slot_b, _) = base.sync_node(10, 0, s1.clone(), None, false, m_b, false);
base.finish_flatten();
base.compact_if_sparse(|_, _| {});
// Commit 2, Pass 1 (discarded before apply): key 10 temporarily mutates to width 300.
comp.begin_commit();
base.begin_commit();
assert!(comp.can_reuse(10, slot_c));
assert!(base.can_reuse(10, slot_b));
let mut s_tmp = CompactStyle::rune_base(FlexDirection::Row);
s_tmp.set_width(length(300.0));
s_tmp.set_height(length(40.0));
let m_c = comp.begin_children();
comp.sync_node(10, 0, s_tmp.clone(), None, false, m_c, false);
comp.finish_flatten();
let m_b = base.begin_children();
base.sync_node(10, 0, s_tmp, None, false, m_b, false);
base.finish_flatten();
// Commit 2, Pass 2 (retry without apply): `can_reuse` must reject `slot` because Pass 1 mutated it!
comp.begin_commit();
base.begin_commit();
assert!(!comp.can_reuse(10, slot_c), "mutated slot must not be reused across intra-commit retry");
assert!(!base.can_reuse(10, slot_b), "baseline store must match retry mutation guard");
// Normal flatten restores `s1` and applies.
let m_c = comp.begin_children();
comp.sync_node(10, 0, s1.clone(), None, false, m_c, false);
comp.finish_flatten();
comp.compact_if_sparse(|_, _| {});
let m_b = base.begin_children();
base.sync_node(10, 0, s1, None, false, m_b, false);
base.finish_flatten();
base.compact_if_sparse(|_, _| {});
// Commit 3: clean slot is reusable again and can rekey cleanly to key 20.
comp.begin_commit();
base.begin_commit();
assert!(comp.can_reuse(10, slot_c));
assert!(base.can_reuse(10, slot_b));
comp.rekey_and_reuse_batch(core::iter::once((10, 20, slot_c, 3)));
base.rekey_and_reuse_batch(core::iter::once((10, 20, slot_b, 3)));
assert_eq!(comp.mounted_node_index(20), Some(3));
assert_eq!(base.mounted_node_index(20), Some(3));
assert_eq!(comp.mounted_node_index(10), None);
assert_eq!(base.mounted_node_index(10), None);
}
+402
View File
@@ -0,0 +1,402 @@
//! Low-level Taffy 0.15 solver trait implementations over [`LayoutStore`].
#![forbid(unsafe_code)]
use taffy::compute::{
compute_block_layout, compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_hidden_layout,
compute_oof_layout,
};
use taffy::geometry::{Point, Rect, Size};
use taffy::style::{
AlignSelf, BoxGenerationMode, BoxSizing, Contain, CoreStyle, Dimension, Direction, Display, ExpandedDimension,
ExpandedLengthPercentageAuto, FlexboxItemStyle, LengthPercentage, LengthPercentageAuto, Overflow, Position, Style,
};
use taffy::tree::{
DetailedLayoutInfo, Layout, LayoutBlockContainer, LayoutContainingBlock, LayoutFlexboxContainer,
LayoutGridContainer, LayoutInput, LayoutOutput, LayoutPartialTree, NodeId, RunMode, TraversePartialTree,
TraverseTree,
};
use taffy::{BlockContext, CacheTree, DetailedGridInfo};
use crate::store::{BoxLayout, LayoutStore, RetainedSlot, SlotChildIter};
use crate::style::CompactStyle;
const NONE_DETAIL: DetailedLayoutInfo = DetailedLayoutInfo::None;
#[inline(always)]
fn round_dim(d: Dimension) -> Dimension {
match d.expand() {
ExpandedDimension::Length(h) => Dimension::length((h + 0.5).floor()),
_ => d,
}
}
#[inline(always)]
fn round_lpa(d: LengthPercentageAuto) -> LengthPercentageAuto {
match d.expand() {
ExpandedLengthPercentageAuto::Length(h) => LengthPercentageAuto::length((h + 0.5).floor()),
_ => d,
}
}
#[derive(Clone, Copy)]
pub(crate) struct FlexChildStyle<'a> {
style: &'a CompactStyle,
round_height: bool,
}
impl CoreStyle for FlexChildStyle<'_> {
type CustomIdent = <CompactStyle as CoreStyle>::CustomIdent;
#[inline(always)]
fn box_generation_mode(&self) -> BoxGenerationMode { self.style.box_generation_mode() }
#[inline(always)]
fn is_block(&self) -> bool { self.style.is_block() }
#[inline(always)]
fn is_compressible_replaced(&self) -> bool { self.style.is_compressible_replaced() }
#[inline(always)]
fn is_replaced(&self) -> bool { self.style.is_replaced() }
#[inline(always)]
fn box_sizing(&self) -> BoxSizing { self.style.box_sizing() }
#[inline(always)]
fn direction(&self) -> Direction { self.style.direction() }
#[inline(always)]
fn overflow(&self) -> Point<Overflow> { self.style.overflow() }
#[inline(always)]
fn scrollbar_width(&self) -> f32 { self.style.scrollbar_width() }
#[inline(always)]
fn position(&self) -> Position { self.style.position() }
#[inline(always)]
fn inset(&self) -> Rect<LengthPercentageAuto> { self.style.inset() }
#[inline(always)]
fn size(&self) -> Size<Dimension> {
let mut s = self.style.size();
if self.round_height {
s.height = round_dim(s.height);
}
s
}
#[inline(always)]
fn min_size(&self) -> Size<LengthPercentageAuto> {
let mut s = self.style.min_size();
if self.round_height {
s.height = round_lpa(s.height);
}
s
}
#[inline(always)]
fn max_size(&self) -> Size<LengthPercentageAuto> {
let mut s = self.style.max_size();
if self.round_height {
s.height = round_lpa(s.height);
}
s
}
#[inline(always)]
fn aspect_ratio(&self) -> Option<f32> { self.style.aspect_ratio() }
#[inline(always)]
fn margin(&self) -> Rect<LengthPercentageAuto> { self.style.margin() }
#[inline(always)]
fn padding(&self) -> Rect<LengthPercentage> { self.style.padding() }
#[inline(always)]
fn border(&self) -> Rect<LengthPercentage> { self.style.border() }
#[inline(always)]
fn contain(&self) -> Contain { self.style.contain() }
}
impl FlexboxItemStyle for FlexChildStyle<'_> {
#[inline(always)]
fn flex_basis(&self) -> Dimension {
let b = self.style.flex_basis();
if self.round_height { round_dim(b) } else { b }
}
#[inline(always)]
fn flex_grow(&self) -> f32 { self.style.flex_grow() }
#[inline(always)]
fn flex_shrink(&self) -> f32 { self.style.flex_shrink() }
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> { self.style.align_self() }
}
pub(crate) struct LayoutStoreView<'s, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
pub(crate) store: &'s mut LayoutStore,
pub(crate) measure_leaf: F,
pub(crate) in_whole_rows_col: bool,
}
impl<F> LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
#[inline(always)]
fn slot(&self, node_id: NodeId) -> &RetainedSlot {
&self.store.slots[u64::from(node_id) as usize]
}
#[inline(always)]
fn slot_mut(&mut self, node_id: NodeId) -> &mut RetainedSlot {
&mut self.store.slots[u64::from(node_id) as usize]
}
#[inline(always)]
fn compute_child_layout_inner(
&mut self,
node_id: NodeId,
inputs: LayoutInput,
block_ctx: Option<&mut BlockContext<'_>>,
) -> LayoutOutput {
let round_for_parent = core::mem::replace(&mut self.in_whole_rows_col, false);
if inputs.run_mode == RunMode::PerformHiddenLayout {
self.slot_mut(node_id).box_layout = BoxLayout::ZERO;
let out = compute_hidden_layout(self, node_id);
self.in_whole_rows_col = round_for_parent;
return out;
}
let mut out = compute_cached_layout(self, node_id, inputs, |view, node_id, inputs| {
let idx = u64::from(node_id) as usize;
let s = &view.store.slots[idx];
let (display_mode, has_children, whole_col) =
(s.style.display(), s.child_len() != 0, s.style.whole_rows_column());
match (display_mode, has_children) {
(Display::None, _) => compute_hidden_layout(view, node_id),
(Display::Block | Display::FlowRoot | Display::Flex | Display::Grid, true) => {
crate::stack::maybe_grow(|| {
let mut output = match display_mode {
Display::Block => compute_block_layout(view, node_id, inputs, block_ctx),
Display::FlowRoot => compute_block_layout(view, node_id, inputs, None),
Display::Flex => {
view.in_whole_rows_col = whole_col;
let r = compute_flexbox_layout(view, node_id, inputs);
view.in_whole_rows_col = false;
r
}
Display::Grid => compute_grid_layout(view, node_id, inputs),
Display::None => unreachable!(),
};
if inputs.run_mode == RunMode::PerformLayout {
compute_oof_layout(view, node_id, &mut output);
}
output
})
}
(_, false) => {
let s = &view.store.slots[idx];
let ctx = s.has_context().then(|| view.store.node_idx[idx] as usize);
(view.measure_leaf)(inputs, ctx, &s.style)
}
}
});
self.in_whole_rows_col = round_for_parent;
if round_for_parent && (inputs.run_mode == RunMode::ComputeSize || inputs.known_dimensions.height.is_none_or(|h| h == h.floor())) {
out.size.height = (out.size.height + 0.5).floor();
}
out
}
}
impl<F> TraversePartialTree for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type ChildIter<'a>
= SlotChildIter<'a>
where
Self: 'a;
#[inline(always)]
fn child_ids(&self, parent_node_id: NodeId) -> Self::ChildIter<'_> {
let s = self.slot(parent_node_id);
let start = s.child_start as usize;
let end = start + s.child_len() as usize;
SlotChildIter(self.store.curr_children[start..end].iter())
}
#[inline(always)]
fn child_count(&self, parent_node_id: NodeId) -> usize {
self.slot(parent_node_id).child_len() as usize
}
#[inline(always)]
fn get_child_id(&self, parent_node_id: NodeId, child_index: usize) -> NodeId {
let s = self.slot(parent_node_id);
debug_assert!(child_index < s.child_len() as usize);
let child_slot = self.store.curr_children[s.child_start as usize + child_index];
NodeId::new(child_slot as u64)
}
}
impl<F> TraverseTree for LayoutStoreView<'_, F> where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput
{
}
impl<F> LayoutPartialTree for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type CoreContainerStyle<'a>
= &'a CompactStyle
where
Self: 'a;
type CustomIdent = <Style as CoreStyle>::CustomIdent;
#[inline(always)]
fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
self.slot_mut(node_id).box_layout = BoxLayout::from_taffy(layout);
}
#[inline(always)]
fn resolve_calc_value(&self, _val: *const (), _basis: f32) -> f32 {
0.0
}
#[inline(always)]
fn compute_child_layout(&mut self, node_id: NodeId, inputs: LayoutInput) -> LayoutOutput {
self.compute_child_layout_inner(node_id, inputs, None)
}
}
impl<F> LayoutContainingBlock for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type OofItemStyle<'a>
= &'a CompactStyle
where
Self: 'a;
#[inline(always)]
fn get_oof_item_style(&self, node_id: NodeId) -> Self::OofItemStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn clear_hoisted_children(&mut self, _node_id: NodeId) {}
#[inline(always)]
fn add_hoisted_children(&mut self, _node_id: NodeId, _hoisted: &[NodeId]) {}
#[inline(always)]
fn get_detailed_layout_info(&self, node_id: NodeId) -> &DetailedLayoutInfo {
self.slot(node_id).grid_info.as_deref().unwrap_or(&NONE_DETAIL)
}
}
impl<F> CacheTree for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
#[inline(always)]
fn cache_get(&mut self, node_id: NodeId, input: &LayoutInput) -> Option<LayoutOutput> {
self.slot_mut(node_id).cache.get(input)
}
#[inline(always)]
fn cache_store(&mut self, node_id: NodeId, input: &LayoutInput, layout_output: LayoutOutput) {
self.slot_mut(node_id).cache.store(input, layout_output);
}
#[inline(always)]
fn cache_clear(&mut self, node_id: NodeId) {
self.slot_mut(node_id).cache.clear();
}
}
impl<F> LayoutBlockContainer for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type BlockContainerStyle<'a>
= &'a CompactStyle
where
Self: 'a;
type BlockItemStyle<'a>
= &'a CompactStyle
where
Self: 'a;
#[inline(always)]
fn get_block_container_style(&self, node_id: NodeId) -> Self::BlockContainerStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn get_block_child_style(&self, child_node_id: NodeId) -> Self::BlockItemStyle<'_> {
&self.slot(child_node_id).style
}
#[inline(always)]
fn compute_block_child_layout(
&mut self,
node_id: NodeId,
inputs: LayoutInput,
block_ctx: Option<&mut BlockContext<'_>>,
) -> LayoutOutput {
self.compute_child_layout_inner(node_id, inputs, block_ctx)
}
}
impl<F> LayoutFlexboxContainer for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type FlexboxContainerStyle<'a>
= &'a CompactStyle
where
Self: 'a;
type FlexboxItemStyle<'a>
= FlexChildStyle<'a>
where
Self: 'a;
#[inline(always)]
fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
let style = &self.slot(child_node_id).style;
let round_height = self.in_whole_rows_col && !style.position().is_out_of_flow() && style.display() != Display::None;
FlexChildStyle { style, round_height }
}
}
impl<F> LayoutGridContainer for LayoutStoreView<'_, F>
where
F: FnMut(LayoutInput, Option<usize>, &CompactStyle) -> LayoutOutput,
{
type GridContainerStyle<'a>
= &'a CompactStyle
where
Self: 'a;
type GridItemStyle<'a>
= &'a CompactStyle
where
Self: 'a;
#[inline(always)]
fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
&self.slot(node_id).style
}
#[inline(always)]
fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
&self.slot(child_node_id).style
}
#[inline(always)]
fn set_detailed_grid_info(&mut self, node_id: NodeId, detailed_grid_info: DetailedGridInfo) {
self.slot_mut(node_id).grid_info = Some(Box::new(DetailedLayoutInfo::Grid(Box::new(detailed_grid_info))));
}
}