1
//! Compact layout property cache — three-tier numeric encoding
2
//!
3
//! Replaces BTreeMap-based CSS property lookups with cache-friendly arrays.
4
//!
5
//! - **Tier 1**: `Vec<u64>` — ALL 21 enum properties bitpacked (8 B/node)
6
//! - **Tier 2 hot**: `Vec<CompactNodeProps>` — layout-critical numeric dimensions (68 B/node)
7
//! - **Tier 2 cold**: `Vec<CompactNodePropsCold>` — paint-only properties (28 B/node)
8
//! - **Tier 2b**: `Vec<CompactTextProps>` — text/IFC properties (24 B/node)
9
//!
10
//! Non-compact properties (background, box-shadow, transform, etc.) are
11
//! resolved via the slow cascade path in `CssPropertyCache::get_property_slow()`.
12

            
13
// The `*_from_u8` decoders below intentionally give an explicit arm for the byte
14
// that maps to each enum's default (e.g. `0 => Block`) even though the `_`
15
// catch-all returns the same default — this keeps the decode table a 1:1 mirror
16
// of the `*_to_u8` encoders. clippy::match_same_arms flags those explicit arms as
17
// duplicates of `_`; merging them would drop the encoding documentation, so allow
18
// it for this codec module (false positive for the intent here).
19
#![allow(clippy::match_same_arms)]
20

            
21
use alloc::{boxed::Box, vec::Vec};
22

            
23
use crate::{
24
    css::CssPropertyValue,
25
    props::{
26
        basic::{
27
            color::ColorU,
28
            font::{StyleFontStyle, StyleFontWeight},
29
            length::{FloatValue, SizeMetric},
30
            pixel::PixelValue,
31
        },
32
        layout::{
33
            dimensions::{
34
                LayoutBoxSizing, LayoutHeight, LayoutMaxHeight, LayoutMaxWidth, LayoutMinHeight,
35
                LayoutMinWidth, LayoutWidth,
36
            },
37
            display::{LayoutDisplay, LayoutFloat},
38
            flex::{
39
                LayoutAlignContent, LayoutAlignItems, LayoutAlignSelf, LayoutFlexDirection,
40
                LayoutFlexWrap, LayoutJustifyContent,
41
            },
42
            grid::{LayoutGridAutoFlow, LayoutJustifyItems, LayoutJustifySelf},
43
            overflow::LayoutOverflow,
44
            position::LayoutPosition,
45
            table::StyleBorderCollapse,
46
            wrapping::{LayoutClear, LayoutWritingMode},
47
        },
48
        property::{CssProperty, CssPropertyType},
49
        style::{
50
            border::BorderStyle, effects::StyleCursor, StyleDirection, StyleTextAlign,
51
            StyleVerticalAlign, StyleVisibility, StyleWhiteSpace,
52
        },
53
    },
54
};
55

            
56
// =============================================================================
57
// Sentinel Constants
58
// =============================================================================
59

            
60
/// u16 sentinel values (for resolved-px ×10 and flex ×100)
61
pub const U16_SENTINEL: u16 = 0xFFFF;
62
/// Any u16 value >= this threshold is a sentinel, not a real value
63
pub const U16_SENTINEL_THRESHOLD: u16 = 0xFFF9;
64

            
65
/// i16 sentinel values (for signed resolved-px ×10)
66
pub const I16_SENTINEL: i16 = 0x7FFF; // 32767
67
pub const I16_AUTO: i16 = 0x7FFE; // 32766
68
pub const I16_INHERIT: i16 = 0x7FFD; // 32765
69
pub const I16_INITIAL: i16 = 0x7FFC; // 32764
70
/// Any i16 value >= this threshold is a sentinel
71
pub const I16_SENTINEL_THRESHOLD: i16 = 0x7FFC; // 32764
72

            
73
/// u32 sentinel values (for dimension properties with unit info)
74
pub const U32_SENTINEL: u32 = 0xFFFF_FFFF;
75
pub const U32_AUTO: u32 = 0xFFFF_FFFE;
76
pub const U32_NONE: u32 = 0xFFFF_FFFD;
77
pub const U32_INHERIT: u32 = 0xFFFF_FFFC;
78
pub const U32_INITIAL: u32 = 0xFFFF_FFFB;
79
pub const U32_MIN_CONTENT: u32 = 0xFFFF_FFFA;
80
pub const U32_MAX_CONTENT: u32 = 0xFFFF_FFF9;
81
/// Any u32 value >= this threshold is a sentinel
82
pub const U32_SENTINEL_THRESHOLD: u32 = 0xFFFF_FFF9;
83

            
84
// =============================================================================
85
// Tier 1: u64 bitfield — ALL enum properties
86
// =============================================================================
87
//
88
// Bit layout (52 bits used, 12 spare):
89
//   [4:0]    display          5 bits  (22 variants)
90
//   [7:5]    position         3 bits  (5 variants)
91
//   [9:8]    float            2 bits  (3 variants)
92
//   [12:10]  overflow_x       3 bits  (5 variants)
93
//   [15:13]  overflow_y       3 bits  (5 variants)
94
//   [16]     box_sizing       1 bit   (2 variants)
95
//   [18:17]  flex_direction   2 bits  (4 variants)
96
//   [20:19]  flex_wrap        2 bits  (3 variants)
97
//   [23:21]  justify_content  3 bits  (8 variants)
98
//   [26:24]  align_items      3 bits  (5 variants)
99
//   [29:27]  align_content    3 bits  (6 variants)
100
//   [31:30]  writing_mode     2 bits  (3 variants)
101
//   [33:32]  clear            2 bits  (4 variants)
102
//   [37:34]  font_weight      4 bits  (11 variants)
103
//   [39:38]  font_style       2 bits  (3 variants)
104
//   [42:40]  text_align       3 bits  (6 variants)
105
//   [44:43]  visibility       2 bits  (3 variants)
106
//   [47:45]  white_space      3 bits  (6 variants)
107
//   [48]     direction        1 bit   (2 variants)
108
//   [51:49]  vertical_align   3 bits  (8 variants)
109
//   [52]     border_collapse  1 bit   (2 variants)
110
//   [63:53]  (spare / sentinel flags)
111

            
112
// Bit offsets within u64
113
pub const DISPLAY_SHIFT: u32 = 0;
114
pub const POSITION_SHIFT: u32 = 5;
115
pub const FLOAT_SHIFT: u32 = 8;
116
pub const OVERFLOW_X_SHIFT: u32 = 10;
117
pub const OVERFLOW_Y_SHIFT: u32 = 13;
118
pub const BOX_SIZING_SHIFT: u32 = 16;
119
pub const FLEX_DIRECTION_SHIFT: u32 = 17;
120
pub const FLEX_WRAP_SHIFT: u32 = 19;
121
pub const JUSTIFY_CONTENT_SHIFT: u32 = 21;
122
pub const ALIGN_ITEMS_SHIFT: u32 = 24;
123
pub const ALIGN_CONTENT_SHIFT: u32 = 27;
124
pub const WRITING_MODE_SHIFT: u32 = 30;
125
pub const CLEAR_SHIFT: u32 = 32;
126
pub const FONT_WEIGHT_SHIFT: u32 = 34;
127
pub const FONT_STYLE_SHIFT: u32 = 38;
128
pub const TEXT_ALIGN_SHIFT: u32 = 40;
129
pub const VISIBILITY_SHIFT: u32 = 43;
130
pub const WHITE_SPACE_SHIFT: u32 = 45;
131
pub const DIRECTION_SHIFT: u32 = 48;
132
pub const VERTICAL_ALIGN_SHIFT: u32 = 49;
133
pub const BORDER_COLLAPSE_SHIFT: u32 = 52;
134
// `cursor` does NOT live in this word. It was given bit 53 for 5 bits, on
135
// the belief that everything above `BORDER_COLLAPSE` (52) was free - but
136
// `ALIGN_SELF` (53), `JUSTIFY_SELF` (56), `GRID_AUTO_FLOW` (59) and
137
// `JUSTIFY_ITEMS` (61) are declared in the SECOND block below and have held
138
// 53..=62 since April. Writing a cursor therefore overwrote `align-self`,
139
// so `cursor: pointer` on a flex item silently changed its alignment - and
140
// because cursor is inheritable, every descendant was mis-aligned too.
141
//
142
// The word is full: bits 0..=62 are allocated and 63 is
143
// `TIER1_POPULATED_BIT`. `cursor` lives in `CompactNodePropsCold::cursor`,
144
// which costs nothing because that struct had padding to spare.
145
// `tier1_bit_ranges_do_not_overlap` now fails on any future collision.
146

            
147
// Bit masks
148
pub const DISPLAY_MASK: u64 = 0x1F; // 5 bits
149
pub const POSITION_MASK: u64 = 0x07; // 3 bits
150
pub const FLOAT_MASK: u64 = 0x03; // 2 bits
151
pub const OVERFLOW_MASK: u64 = 0x07; // 3 bits
152
pub const BOX_SIZING_MASK: u64 = 0x01; // 1 bit
153
pub const FLEX_DIR_MASK: u64 = 0x03; // 2 bits
154
pub const FLEX_WRAP_MASK: u64 = 0x03; // 2 bits
155
pub const JUSTIFY_MASK: u64 = 0x07; // 3 bits
156
pub const ALIGN_MASK: u64 = 0x07; // 3 bits
157
pub const WRITING_MODE_MASK: u64 = 0x03; // 2 bits
158
pub const CLEAR_MASK: u64 = 0x03; // 2 bits
159
pub const FONT_WEIGHT_MASK: u64 = 0x0F; // 4 bits
160
pub const FONT_STYLE_MASK: u64 = 0x03; // 2 bits
161
pub const TEXT_ALIGN_MASK: u64 = 0x07; // 3 bits
162
pub const VISIBILITY_MASK: u64 = 0x03; // 2 bits
163
pub const WHITE_SPACE_MASK: u64 = 0x07; // 3 bits
164
pub const DIRECTION_MASK: u64 = 0x01; // 1 bit
165
pub const VERTICAL_ALIGN_MASK: u64 = 0x07; // 3 bits
166
pub const BORDER_COLLAPSE_MASK: u64 = 0x01; // 1 bit
167
/// The range of `cursor` CODES (30 variants). This is NOT a tier-1 bit
168
/// slot - see the note above the mask block.
169
pub const CURSOR_CODE_MAX: u8 = 0x1F;
170

            
171
pub const ALIGN_SELF_SHIFT: u32 = 53;
172
pub const JUSTIFY_SELF_SHIFT: u32 = 56;
173
pub const GRID_AUTO_FLOW_SHIFT: u32 = 59;
174
pub const JUSTIFY_ITEMS_SHIFT: u32 = 61;
175
pub const ALIGN_SELF_MASK: u64 = 0x07; // 3 bits
176
pub const JUSTIFY_SELF_MASK: u64 = 0x07; // 3 bits
177
pub const GRID_AUTO_FLOW_MASK: u64 = 0x03; // 2 bits (row/col × dense)
178
pub const JUSTIFY_ITEMS_MASK: u64 = 0x03; // 2 bits (start/center/end/stretch)
179

            
180
/// Special value stored in the spare bits [63:51] to indicate this node has
181
/// NO tier-1 data (i.e., all defaults).
182
///
183
/// 0 is a valid all-defaults encoding,
184
/// so we use bit 63 as a "tier1 populated" flag. If bit 63 is 0 and all other
185
/// bits are 0, it means "all defaults" (`Display::Block`, `Position::Static`, etc.).
186
/// We set bit 63 = 1 to mark that the node HAS been populated.
187
pub const TIER1_POPULATED_BIT: u64 = 1 << 63;
188

            
189
// =============================================================================
190
// Safe from_u8 conversion functions (no transmute!)
191
// =============================================================================
192

            
193
/// Decode display from u8. **0 = Block** (most common HTML default).
194
/// Value 31 (0x1F) = sentinel: look up in slow path for uncommon values.
195
/// Returns default (Block) on invalid input.
196
#[inline]
197
#[must_use]
198
8778461
pub const fn layout_display_from_u8(v: u8) -> LayoutDisplay {
199
8778461
    match v {
200
3312557
        0 => LayoutDisplay::Block, // default when bits are 0
201
2276014
        1 => LayoutDisplay::Inline,
202
625917
        2 => LayoutDisplay::InlineBlock,
203
2471327
        3 => LayoutDisplay::Flex,
204
2362
        4 => LayoutDisplay::None,
205
4497
        5 => LayoutDisplay::InlineFlex,
206
7281
        6 => LayoutDisplay::Table,
207
609
        7 => LayoutDisplay::InlineTable,
208
333
        8 => LayoutDisplay::TableRowGroup,
209
561
        9 => LayoutDisplay::TableHeaderGroup,
210
154
        10 => LayoutDisplay::TableFooterGroup,
211
8577
        11 => LayoutDisplay::TableRow,
212
153
        12 => LayoutDisplay::TableColumnGroup,
213
261
        13 => LayoutDisplay::TableColumn,
214
29145
        14 => LayoutDisplay::TableCell,
215
165
        15 => LayoutDisplay::TableCaption,
216
441
        16 => LayoutDisplay::FlowRoot,
217
33885
        17 => LayoutDisplay::ListItem,
218
129
        18 => LayoutDisplay::RunIn,
219
129
        19 => LayoutDisplay::Marker,
220
1605
        20 => LayoutDisplay::Grid,
221
634
        21 => LayoutDisplay::InlineGrid,
222
336
        22 => LayoutDisplay::Contents,
223
1389
        _ => LayoutDisplay::Block, // fallback + sentinel (31)
224
    }
225
8778461
}
226

            
227
/// Encode display to u8. **0 = Block** (most common HTML default).
228
#[inline]
229
#[must_use]
230
2030643
pub const fn layout_display_to_u8(v: LayoutDisplay) -> u8 {
231
2030643
    match v {
232
948437
        LayoutDisplay::Block => 0, // 0 = default when bits unset
233
508613
        LayoutDisplay::Inline => 1,
234
92906
        LayoutDisplay::InlineBlock => 2,
235
292747
        LayoutDisplay::Flex => 3,
236
5378
        LayoutDisplay::None => 4,
237
704
        LayoutDisplay::InlineFlex => 5,
238
1107
        LayoutDisplay::Table => 6,
239
80
        LayoutDisplay::InlineTable => 7,
240
93
        LayoutDisplay::TableRowGroup => 8,
241
119
        LayoutDisplay::TableHeaderGroup => 9,
242
15
        LayoutDisplay::TableFooterGroup => 10,
243
1406
        LayoutDisplay::TableRow => 11,
244
15
        LayoutDisplay::TableColumnGroup => 12,
245
41
        LayoutDisplay::TableColumn => 13,
246
2589
        LayoutDisplay::TableCell => 14,
247
41
        LayoutDisplay::TableCaption => 15,
248
67
        LayoutDisplay::FlowRoot => 16,
249
4396
        LayoutDisplay::ListItem => 17,
250
2
        LayoutDisplay::RunIn => 18,
251
2
        LayoutDisplay::Marker => 19,
252
171758
        LayoutDisplay::Grid => 20,
253
80
        LayoutDisplay::InlineGrid => 21,
254
47
        LayoutDisplay::Contents => 22,
255
    }
256
2030643
}
257

            
258
#[inline]
259
#[must_use]
260
4287468
pub const fn layout_position_from_u8(v: u8) -> LayoutPosition {
261
4287468
    match v {
262
4191389
        0 => LayoutPosition::Static,
263
34294
        1 => LayoutPosition::Relative,
264
58582
        2 => LayoutPosition::Absolute,
265
657
        3 => LayoutPosition::Fixed,
266
756
        4 => LayoutPosition::Sticky,
267
1790
        _ => LayoutPosition::Static,
268
    }
269
4287468
}
270

            
271
#[inline]
272
#[must_use]
273
37617
pub const fn layout_position_to_u8(v: LayoutPosition) -> u8 {
274
37617
    match v {
275
458
        LayoutPosition::Static => 0,
276
20277
        LayoutPosition::Relative => 1,
277
16508
        LayoutPosition::Absolute => 2,
278
119
        LayoutPosition::Fixed => 3,
279
255
        LayoutPosition::Sticky => 4,
280
    }
281
37617
}
282

            
283
/// Decode float from u8. **0 = None** (CSS initial value).
284
#[inline]
285
#[must_use]
286
1750259
pub const fn layout_float_from_u8(v: u8) -> LayoutFloat {
287
1750259
    match v {
288
1744284
        0 => LayoutFloat::None, // default when bits unset
289
2959
        1 => LayoutFloat::Left,
290
1737
        2 => LayoutFloat::Right,
291
1279
        _ => LayoutFloat::None,
292
    }
293
1750259
}
294

            
295
/// Encode float to u8. **0 = None** (CSS initial value).
296
#[inline]
297
#[must_use]
298
924
pub const fn layout_float_to_u8(v: LayoutFloat) -> u8 {
299
924
    match v {
300
419
        LayoutFloat::None => 0,
301
354
        LayoutFloat::Left => 1,
302
151
        LayoutFloat::Right => 2,
303
    }
304
924
}
305

            
306
/// Decode overflow from u8. **0 = Visible** (CSS initial value).
307
#[inline]
308
#[must_use]
309
7879841
pub const fn layout_overflow_from_u8(v: u8) -> LayoutOverflow {
310
7879841
    match v {
311
7695464
        0 => LayoutOverflow::Visible, // default when bits unset
312
122123
        1 => LayoutOverflow::Hidden,
313
22834
        2 => LayoutOverflow::Scroll,
314
35000
        3 => LayoutOverflow::Auto,
315
1058
        4 => LayoutOverflow::Clip,
316
3362
        _ => LayoutOverflow::Visible,
317
    }
318
7879841
}
319

            
320
/// Encode overflow to u8. **0 = Visible** (CSS initial value).
321
#[inline]
322
#[must_use]
323
60359
pub const fn layout_overflow_to_u8(v: LayoutOverflow) -> u8 {
324
60359
    match v {
325
2525
        LayoutOverflow::Visible => 0, // 0 = default when bits unset
326
43685
        LayoutOverflow::Hidden => 1,
327
4098
        LayoutOverflow::Scroll => 2,
328
10025
        LayoutOverflow::Auto => 3,
329
26
        LayoutOverflow::Clip => 4,
330
    }
331
60359
}
332

            
333
#[inline]
334
#[must_use]
335
521531
pub const fn layout_box_sizing_from_u8(v: u8) -> LayoutBoxSizing {
336
521531
    match v {
337
396983
        0 => LayoutBoxSizing::ContentBox,
338
124294
        1 => LayoutBoxSizing::BorderBox,
339
254
        _ => LayoutBoxSizing::ContentBox,
340
    }
341
521531
}
342

            
343
#[inline]
344
#[must_use]
345
154660
pub const fn layout_box_sizing_to_u8(v: LayoutBoxSizing) -> u8 {
346
154660
    match v {
347
458
        LayoutBoxSizing::ContentBox => 0,
348
154202
        LayoutBoxSizing::BorderBox => 1,
349
    }
350
154660
}
351

            
352
#[inline]
353
#[must_use]
354
239543
pub const fn layout_flex_direction_from_u8(v: u8) -> LayoutFlexDirection {
355
239543
    match v {
356
188412
        0 => LayoutFlexDirection::Row,
357
1044
        1 => LayoutFlexDirection::RowReverse,
358
48813
        2 => LayoutFlexDirection::Column,
359
1022
        3 => LayoutFlexDirection::ColumnReverse,
360
252
        _ => LayoutFlexDirection::Row,
361
    }
362
239543
}
363

            
364
#[inline]
365
#[must_use]
366
295091
pub const fn layout_flex_direction_to_u8(v: LayoutFlexDirection) -> u8 {
367
295091
    match v {
368
202842
        LayoutFlexDirection::Row => 0,
369
2
        LayoutFlexDirection::RowReverse => 1,
370
92239
        LayoutFlexDirection::Column => 2,
371
8
        LayoutFlexDirection::ColumnReverse => 3,
372
    }
373
295091
}
374

            
375
/// 0 = `NoWrap` (CSS initial value for flex-wrap)
376
#[inline]
377
#[must_use]
378
162791
pub const fn layout_flex_wrap_from_u8(v: u8) -> LayoutFlexWrap {
379
162791
    match v {
380
159380
        0 => LayoutFlexWrap::NoWrap, // CSS initial
381
1045
        1 => LayoutFlexWrap::Wrap,
382
1006
        2 => LayoutFlexWrap::WrapReverse,
383
1360
        _ => LayoutFlexWrap::NoWrap,
384
    }
385
162791
}
386

            
387
#[inline]
388
#[must_use]
389
3902
pub const fn layout_flex_wrap_to_u8(v: LayoutFlexWrap) -> u8 {
390
3902
    match v {
391
406
        LayoutFlexWrap::NoWrap => 0,
392
3488
        LayoutFlexWrap::Wrap => 1,
393
8
        LayoutFlexWrap::WrapReverse => 2,
394
    }
395
3902
}
396

            
397
#[inline]
398
#[must_use]
399
162827
pub const fn layout_justify_content_from_u8(v: u8) -> LayoutJustifyContent {
400
162827
    match v {
401
146661
        0 => LayoutJustifyContent::FlexStart,
402
523
        1 => LayoutJustifyContent::FlexEnd,
403
486
        2 => LayoutJustifyContent::Start,
404
490
        3 => LayoutJustifyContent::End,
405
12759
        4 => LayoutJustifyContent::Center,
406
581
        5 => LayoutJustifyContent::SpaceBetween,
407
571
        6 => LayoutJustifyContent::SpaceAround,
408
508
        7 => LayoutJustifyContent::SpaceEvenly,
409
248
        _ => LayoutJustifyContent::FlexStart,
410
    }
411
162827
}
412

            
413
#[inline]
414
#[must_use]
415
85623
pub const fn layout_justify_content_to_u8(v: LayoutJustifyContent) -> u8 {
416
85623
    match v {
417
26
        LayoutJustifyContent::FlexStart => 0,
418
2
        LayoutJustifyContent::FlexEnd => 1,
419
382
        LayoutJustifyContent::Start => 2,
420
2
        LayoutJustifyContent::End => 3,
421
84990
        LayoutJustifyContent::Center => 4,
422
211
        LayoutJustifyContent::SpaceBetween => 5,
423
2
        LayoutJustifyContent::SpaceAround => 6,
424
8
        LayoutJustifyContent::SpaceEvenly => 7,
425
    }
426
85623
}
427

            
428
#[inline]
429
#[must_use]
430
162791
pub const fn layout_align_items_from_u8(v: u8) -> LayoutAlignItems {
431
162791
    match v {
432
99143
        0 => LayoutAlignItems::Stretch,
433
49534
        1 => LayoutAlignItems::Center,
434
11322
        2 => LayoutAlignItems::Start,
435
499
        3 => LayoutAlignItems::End,
436
483
        4 => LayoutAlignItems::Baseline,
437
1810
        _ => LayoutAlignItems::Stretch,
438
    }
439
162791
}
440

            
441
#[inline]
442
#[must_use]
443
232192
pub const fn layout_align_items_to_u8(v: LayoutAlignItems) -> u8 {
444
232192
    match v {
445
757
        LayoutAlignItems::Stretch => 0,
446
206671
        LayoutAlignItems::Center => 1,
447
24741
        LayoutAlignItems::Start => 2,
448
15
        LayoutAlignItems::End => 3,
449
8
        LayoutAlignItems::Baseline => 4,
450
    }
451
232192
}
452

            
453
#[inline]
454
#[must_use]
455
10155
pub const fn layout_align_self_to_u8(v: LayoutAlignSelf) -> u8 {
456
10155
    match v {
457
3
        LayoutAlignSelf::Auto => 0,
458
145
        LayoutAlignSelf::Stretch => 1,
459
5007
        LayoutAlignSelf::Center => 2,
460
4968
        LayoutAlignSelf::Start => 3,
461
28
        LayoutAlignSelf::End => 4,
462
4
        LayoutAlignSelf::Baseline => 5,
463
    }
464
10155
}
465

            
466
#[inline]
467
#[must_use]
468
158694
pub const fn layout_align_self_from_u8(v: u8) -> LayoutAlignSelf {
469
158694
    match v {
470
157598
        0 => LayoutAlignSelf::Auto,
471
13
        1 => LayoutAlignSelf::Stretch,
472
637
        2 => LayoutAlignSelf::Center,
473
181
        3 => LayoutAlignSelf::Start,
474
13
        4 => LayoutAlignSelf::End,
475
2
        5 => LayoutAlignSelf::Baseline,
476
250
        _ => LayoutAlignSelf::Auto,
477
    }
478
158694
}
479

            
480
#[inline]
481
#[must_use]
482
13
pub const fn layout_justify_self_to_u8(v: LayoutJustifySelf) -> u8 {
483
13
    match v {
484
3
        LayoutJustifySelf::Auto => 0,
485
2
        LayoutJustifySelf::Start => 1,
486
2
        LayoutJustifySelf::End => 2,
487
2
        LayoutJustifySelf::Center => 3,
488
4
        LayoutJustifySelf::Stretch => 4,
489
    }
490
13
}
491

            
492
#[inline]
493
#[must_use]
494
158694
pub const fn layout_justify_self_from_u8(v: u8) -> LayoutJustifySelf {
495
158694
    match v {
496
158438
        0 => LayoutJustifySelf::Auto,
497
1
        1 => LayoutJustifySelf::Start,
498
1
        2 => LayoutJustifySelf::End,
499
1
        3 => LayoutJustifySelf::Center,
500
2
        4 => LayoutJustifySelf::Stretch,
501
251
        _ => LayoutJustifySelf::Auto,
502
    }
503
158694
}
504

            
505
// Tier1 uses 0 as the "unset" sentinel for every enum. For justify-items
506
// the CSS default is `normal` which behaves as `stretch` on grid items,
507
// so 0 must decode to Stretch (not Start). Getting this wrong leaves
508
// every unset grid container reporting justify-items: Start, which
509
// forces taffy to content-size items instead of stretching them across
510
// their column tracks — exactly the calc.c regression.
511
#[inline]
512
#[must_use]
513
12
pub const fn layout_justify_items_to_u8(v: LayoutJustifyItems) -> u8 {
514
12
    match v {
515
4
        LayoutJustifyItems::Stretch => 0,
516
2
        LayoutJustifyItems::Start => 1,
517
2
        LayoutJustifyItems::End => 2,
518
4
        LayoutJustifyItems::Center => 3,
519
    }
520
12
}
521

            
522
#[inline]
523
#[must_use]
524
158695
pub const fn layout_justify_items_from_u8(v: u8) -> LayoutJustifyItems {
525
158695
    match v {
526
158439
        0 => LayoutJustifyItems::Stretch,
527
1
        1 => LayoutJustifyItems::Start,
528
1
        2 => LayoutJustifyItems::End,
529
2
        3 => LayoutJustifyItems::Center,
530
252
        _ => LayoutJustifyItems::Stretch,
531
    }
532
158695
}
533

            
534
#[inline]
535
#[must_use]
536
11
pub const fn layout_grid_auto_flow_to_u8(v: LayoutGridAutoFlow) -> u8 {
537
11
    match v {
538
3
        LayoutGridAutoFlow::Row => 0,
539
2
        LayoutGridAutoFlow::Column => 1,
540
2
        LayoutGridAutoFlow::RowDense => 2,
541
4
        LayoutGridAutoFlow::ColumnDense => 3,
542
    }
543
11
}
544

            
545
#[inline]
546
#[must_use]
547
294
pub const fn layout_grid_auto_flow_from_u8(v: u8) -> LayoutGridAutoFlow {
548
294
    match v {
549
38
        0 => LayoutGridAutoFlow::Row,
550
1
        1 => LayoutGridAutoFlow::Column,
551
1
        2 => LayoutGridAutoFlow::RowDense,
552
2
        3 => LayoutGridAutoFlow::ColumnDense,
553
252
        _ => LayoutGridAutoFlow::Row,
554
    }
555
294
}
556

            
557
#[inline]
558
#[must_use]
559
162791
pub const fn layout_align_content_from_u8(v: u8) -> LayoutAlignContent {
560
162791
    match v {
561
158949
        0 => LayoutAlignContent::Stretch,
562
496
        1 => LayoutAlignContent::Center,
563
493
        2 => LayoutAlignContent::Start,
564
533
        3 => LayoutAlignContent::End,
565
483
        4 => LayoutAlignContent::SpaceBetween,
566
532
        5 => LayoutAlignContent::SpaceAround,
567
1305
        _ => LayoutAlignContent::Stretch,
568
    }
569
162791
}
570

            
571
#[inline]
572
#[must_use]
573
423
pub const fn layout_align_content_to_u8(v: LayoutAlignContent) -> u8 {
574
423
    match v {
575
406
        LayoutAlignContent::Stretch => 0,
576
2
        LayoutAlignContent::Center => 1,
577
2
        LayoutAlignContent::Start => 2,
578
3
        LayoutAlignContent::End => 3,
579
2
        LayoutAlignContent::SpaceBetween => 4,
580
8
        LayoutAlignContent::SpaceAround => 5,
581
    }
582
423
}
583

            
584
#[inline]
585
#[must_use]
586
1317707
pub const fn layout_writing_mode_from_u8(v: u8) -> LayoutWritingMode {
587
1317707
    match v {
588
1314016
        0 => LayoutWritingMode::HorizontalTb,
589
1397
        1 => LayoutWritingMode::VerticalRl,
590
1024
        2 => LayoutWritingMode::VerticalLr,
591
1270
        _ => LayoutWritingMode::HorizontalTb,
592
    }
593
1317707
}
594

            
595
#[inline]
596
#[must_use]
597
534
pub const fn layout_writing_mode_to_u8(v: LayoutWritingMode) -> u8 {
598
534
    match v {
599
406
        LayoutWritingMode::HorizontalTb => 0,
600
94
        LayoutWritingMode::VerticalRl => 1,
601
34
        LayoutWritingMode::VerticalLr => 2,
602
    }
603
534
}
604

            
605
#[inline]
606
#[must_use]
607
66671
pub const fn layout_clear_from_u8(v: u8) -> LayoutClear {
608
66671
    match v {
609
63267
        0 => LayoutClear::None,
610
1070
        1 => LayoutClear::Left,
611
1011
        2 => LayoutClear::Right,
612
1071
        3 => LayoutClear::Both,
613
252
        _ => LayoutClear::None,
614
    }
615
66671
}
616

            
617
#[inline]
618
#[must_use]
619
510
pub const fn layout_clear_to_u8(v: LayoutClear) -> u8 {
620
510
    match v {
621
406
        LayoutClear::None => 0,
622
54
        LayoutClear::Left => 1,
623
15
        LayoutClear::Right => 2,
624
35
        LayoutClear::Both => 3,
625
    }
626
510
}
627

            
628
#[inline]
629
/// 0 = Normal/400 (CSS initial value for font-weight)
630
#[must_use]
631
228971
pub const fn style_font_weight_from_u8(v: u8) -> StyleFontWeight {
632
228971
    match v {
633
224072
        0 => StyleFontWeight::Normal, // CSS initial (400)
634
261
        1 => StyleFontWeight::W100,
635
273
        2 => StyleFontWeight::W200,
636
251
        3 => StyleFontWeight::W300,
637
245
        4 => StyleFontWeight::W500,
638
250
        5 => StyleFontWeight::W600,
639
1051
        6 => StyleFontWeight::Bold, // 700
640
253
        7 => StyleFontWeight::W800,
641
245
        8 => StyleFontWeight::W900,
642
267
        9 => StyleFontWeight::Lighter,
643
289
        10 => StyleFontWeight::Bolder,
644
1514
        _ => StyleFontWeight::Normal,
645
    }
646
228971
}
647

            
648
#[inline]
649
/// 0 = Normal/400 (CSS initial value for font-weight)
650
#[must_use]
651
2570
pub const fn style_font_weight_to_u8(v: StyleFontWeight) -> u8 {
652
2570
    match v {
653
406
        StyleFontWeight::Normal => 0, // CSS initial (400)
654
2
        StyleFontWeight::W100 => 1,
655
2
        StyleFontWeight::W200 => 2,
656
2
        StyleFontWeight::W300 => 3,
657
2
        StyleFontWeight::W500 => 4,
658
2
        StyleFontWeight::W600 => 5,
659
2114
        StyleFontWeight::Bold => 6, // 700
660
2
        StyleFontWeight::W800 => 7,
661
2
        StyleFontWeight::W900 => 8,
662
2
        StyleFontWeight::Lighter => 9,
663
34
        StyleFontWeight::Bolder => 10,
664
    }
665
2570
}
666

            
667
#[inline]
668
#[must_use]
669
228971
pub const fn style_font_style_from_u8(v: u8) -> StyleFontStyle {
670
228971
    match v {
671
225542
        0 => StyleFontStyle::Normal,
672
1131
        1 => StyleFontStyle::Italic,
673
1011
        2 => StyleFontStyle::Oblique,
674
1287
        _ => StyleFontStyle::Normal,
675
    }
676
228971
}
677

            
678
#[inline]
679
#[must_use]
680
443
pub const fn style_font_style_to_u8(v: StyleFontStyle) -> u8 {
681
443
    match v {
682
406
        StyleFontStyle::Normal => 0,
683
29
        StyleFontStyle::Italic => 1,
684
8
        StyleFontStyle::Oblique => 2,
685
    }
686
443
}
687

            
688
#[inline]
689
#[must_use]
690
1079663
pub const fn style_text_align_from_u8(v: u8) -> StyleTextAlign {
691
    // Code 0 must decode to the CSS-initial value so an un-written tier1 field (all
692
    // zero) yields `start`, not physical `left` — otherwise direction:rtl never
693
    // right-aligns (start→right needs the value to actually be `start`). `left`
694
    // therefore takes code 4 (swapped with `start`).
695
1079663
    match v {
696
953943
        0 => StyleTextAlign::Start,
697
119370
        1 => StyleTextAlign::Center,
698
552
        2 => StyleTextAlign::Right,
699
899
        3 => StyleTextAlign::Justify,
700
3129
        4 => StyleTextAlign::Left,
701
529
        5 => StyleTextAlign::End,
702
1241
        _ => StyleTextAlign::Start,
703
    }
704
1079663
}
705

            
706
#[inline]
707
#[must_use]
708
100419
pub const fn style_text_align_to_u8(v: StyleTextAlign) -> u8 {
709
    // `start` encodes to 0 (the CSS-initial / zero-baseline code); `left` takes 4.
710
100419
    match v {
711
404
        StyleTextAlign::Start => 0,
712
93525
        StyleTextAlign::Center => 1,
713
171
        StyleTextAlign::Right => 2,
714
15
        StyleTextAlign::Justify => 3,
715
6296
        StyleTextAlign::Left => 4,
716
8
        StyleTextAlign::End => 5,
717
    }
718
100419
}
719

            
720
#[inline]
721
#[must_use]
722
2926907
pub const fn style_visibility_from_u8(v: u8) -> StyleVisibility {
723
2926907
    match v {
724
2923578
        0 => StyleVisibility::Visible,
725
1000
        1 => StyleVisibility::Hidden,
726
1070
        2 => StyleVisibility::Collapse,
727
1259
        _ => StyleVisibility::Visible,
728
    }
729
2926907
}
730

            
731
#[inline]
732
#[must_use]
733
437
pub const fn style_visibility_to_u8(v: StyleVisibility) -> u8 {
734
437
    match v {
735
406
        StyleVisibility::Visible => 0,
736
23
        StyleVisibility::Hidden => 1,
737
8
        StyleVisibility::Collapse => 2,
738
    }
739
437
}
740

            
741
#[inline]
742
#[must_use]
743
884039
pub const fn style_white_space_from_u8(v: u8) -> StyleWhiteSpace {
744
884039
    match v {
745
708199
        0 => StyleWhiteSpace::Normal,
746
4049
        1 => StyleWhiteSpace::Pre,
747
125230
        2 => StyleWhiteSpace::Nowrap,
748
44134
        3 => StyleWhiteSpace::PreWrap,
749
635
        4 => StyleWhiteSpace::PreLine,
750
503
        5 => StyleWhiteSpace::BreakSpaces,
751
1289
        _ => StyleWhiteSpace::Normal,
752
    }
753
884039
}
754

            
755
#[inline]
756
#[must_use]
757
45845
pub const fn style_white_space_to_u8(v: StyleWhiteSpace) -> u8 {
758
45845
    match v {
759
523
        StyleWhiteSpace::Normal => 0,
760
3838
        StyleWhiteSpace::Pre => 1,
761
24962
        StyleWhiteSpace::Nowrap => 2,
762
16434
        StyleWhiteSpace::PreWrap => 3,
763
67
        StyleWhiteSpace::PreLine => 4,
764
21
        StyleWhiteSpace::BreakSpaces => 5,
765
    }
766
45845
}
767

            
768
#[inline]
769
#[must_use]
770
859055
pub const fn style_direction_from_u8(v: u8) -> StyleDirection {
771
859055
    match v {
772
856588
        0 => StyleDirection::Ltr,
773
2213
        1 => StyleDirection::Rtl,
774
254
        _ => StyleDirection::Ltr,
775
    }
776
859055
}
777

            
778
#[inline]
779
#[must_use]
780
454
pub const fn style_direction_to_u8(v: StyleDirection) -> u8 {
781
454
    match v {
782
406
        StyleDirection::Ltr => 0,
783
48
        StyleDirection::Rtl => 1,
784
    }
785
454
}
786

            
787
#[inline]
788
#[must_use]
789
4397
pub const fn style_vertical_align_from_u8(v: u8) -> StyleVerticalAlign {
790
4397
    match v {
791
545
        0 => StyleVerticalAlign::Baseline,
792
490
        1 => StyleVerticalAlign::Top,
793
497
        2 => StyleVerticalAlign::Middle,
794
535
        3 => StyleVerticalAlign::Bottom,
795
538
        4 => StyleVerticalAlign::Sub,
796
504
        5 => StyleVerticalAlign::Superscript,
797
530
        6 => StyleVerticalAlign::TextTop,
798
510
        7 => StyleVerticalAlign::TextBottom,
799
248
        _ => StyleVerticalAlign::Baseline,
800
    }
801
4397
}
802

            
803
#[inline]
804
#[must_use]
805
4014
pub const fn style_vertical_align_to_u8(v: StyleVerticalAlign) -> u8 {
806
4014
    match v {
807
405
        StyleVerticalAlign::Baseline => 0,
808
2
        StyleVerticalAlign::Top => 1,
809
3552
        StyleVerticalAlign::Middle => 2,
810
2
        StyleVerticalAlign::Bottom => 3,
811
15
        StyleVerticalAlign::Sub => 4,
812
15
        StyleVerticalAlign::Superscript => 5,
813
2
        StyleVerticalAlign::TextTop => 6,
814
8
        StyleVerticalAlign::TextBottom => 7,
815
        // Percentage/Length cannot be stored in the 3-bit compact cache field;
816
        // fall back to 0 (Baseline). Callers must use the slow cascade path
817
        // for vertical-align values with length/percentage units.
818
13
        StyleVerticalAlign::Percentage(_) | StyleVerticalAlign::Length(_) => 0,
819
    }
820
4014
}
821

            
822
/// `StyleCursor` <-> 5-bit code. `Default` (the CSS initial value) is 0 so an
823
/// unset node decodes to it for free, and an out-of-range code falls back to it
824
/// rather than panicking.
825
#[inline]
826
#[must_use]
827
759632
pub const fn cursor_to_u8(v: StyleCursor) -> u8 {
828
759632
    match v {
829
71540
        StyleCursor::Default => 0,
830
1
        StyleCursor::Alias => 1,
831
1
        StyleCursor::AllScroll => 2,
832
1
        StyleCursor::Cell => 3,
833
755
        StyleCursor::ColResize => 4,
834
1
        StyleCursor::ContextMenu => 5,
835
1
        StyleCursor::Copy => 6,
836
807
        StyleCursor::Crosshair => 7,
837
1
        StyleCursor::EResize => 8,
838
1
        StyleCursor::EwResize => 9,
839
482
        StyleCursor::Grab => 10,
840
1
        StyleCursor::Grabbing => 11,
841
1
        StyleCursor::Help => 12,
842
1
        StyleCursor::Move => 13,
843
1
        StyleCursor::NResize => 14,
844
1
        StyleCursor::NsResize => 15,
845
1
        StyleCursor::NeswResize => 16,
846
1
        StyleCursor::NwseResize => 17,
847
176533
        StyleCursor::Pointer => 18,
848
1
        StyleCursor::Progress => 19,
849
53
        StyleCursor::RowResize => 20,
850
1
        StyleCursor::SResize => 21,
851
1
        StyleCursor::SeResize => 22,
852
509439
        StyleCursor::Text => 23,
853
1
        StyleCursor::Unset => 24,
854
1
        StyleCursor::VerticalText => 25,
855
1
        StyleCursor::WResize => 26,
856
1
        StyleCursor::Wait => 27,
857
1
        StyleCursor::ZoomIn => 28,
858
1
        StyleCursor::ZoomOut => 29,
859
    }
860
759632
}
861

            
862
#[inline]
863
#[must_use]
864
60
pub const fn cursor_from_u8(v: u8) -> StyleCursor {
865
60
    match v {
866
2
        1 => StyleCursor::Alias,
867
2
        2 => StyleCursor::AllScroll,
868
2
        3 => StyleCursor::Cell,
869
2
        4 => StyleCursor::ColResize,
870
2
        5 => StyleCursor::ContextMenu,
871
2
        6 => StyleCursor::Copy,
872
2
        7 => StyleCursor::Crosshair,
873
2
        8 => StyleCursor::EResize,
874
2
        9 => StyleCursor::EwResize,
875
2
        10 => StyleCursor::Grab,
876
2
        11 => StyleCursor::Grabbing,
877
2
        12 => StyleCursor::Help,
878
2
        13 => StyleCursor::Move,
879
2
        14 => StyleCursor::NResize,
880
2
        15 => StyleCursor::NsResize,
881
2
        16 => StyleCursor::NeswResize,
882
2
        17 => StyleCursor::NwseResize,
883
2
        18 => StyleCursor::Pointer,
884
2
        19 => StyleCursor::Progress,
885
2
        20 => StyleCursor::RowResize,
886
2
        21 => StyleCursor::SResize,
887
2
        22 => StyleCursor::SeResize,
888
2
        23 => StyleCursor::Text,
889
2
        24 => StyleCursor::Unset,
890
2
        25 => StyleCursor::VerticalText,
891
2
        26 => StyleCursor::WResize,
892
2
        27 => StyleCursor::Wait,
893
2
        28 => StyleCursor::ZoomIn,
894
2
        29 => StyleCursor::ZoomOut,
895
2
        _ => StyleCursor::Default,
896
    }
897
60
}
898

            
899
#[inline]
900
#[must_use]
901
6444
pub const fn border_collapse_from_u8(v: u8) -> StyleBorderCollapse {
902
6444
    match v {
903
3905
        0 => StyleBorderCollapse::Separate,
904
2285
        1 => StyleBorderCollapse::Collapse,
905
254
        _ => StyleBorderCollapse::Separate,
906
    }
907
6444
}
908

            
909
#[inline]
910
#[must_use]
911
559
pub const fn border_collapse_to_u8(v: StyleBorderCollapse) -> u8 {
912
559
    match v {
913
405
        StyleBorderCollapse::Separate => 0,
914
154
        StyleBorderCollapse::Collapse => 1,
915
    }
916
559
}
917

            
918
#[inline]
919
#[must_use]
920
7834849
pub const fn border_style_from_u8(v: u8) -> BorderStyle {
921
7834849
    match v {
922
7185129
        0 => BorderStyle::None,
923
490092
        1 => BorderStyle::Solid,
924
12336
        2 => BorderStyle::Double,
925
12336
        3 => BorderStyle::Dotted,
926
12336
        4 => BorderStyle::Dashed,
927
12244
        5 => BorderStyle::Hidden,
928
12192
        6 => BorderStyle::Groove,
929
12193
        7 => BorderStyle::Ridge,
930
24384
        8 => BorderStyle::Inset,
931
12194
        9 => BorderStyle::Outset,
932
49413
        _ => BorderStyle::None,
933
    }
934
7834849
}
935

            
936
#[inline]
937
#[must_use]
938
709842
pub const fn border_style_to_u8(v: BorderStyle) -> u8 {
939
709842
    match v {
940
5527
        BorderStyle::None => 0,
941
645953
        BorderStyle::Solid => 1,
942
4093
        BorderStyle::Double => 2,
943
4053
        BorderStyle::Dotted => 3,
944
4053
        BorderStyle::Dashed => 4,
945
4053
        BorderStyle::Hidden => 5,
946
4001
        BorderStyle::Groove => 6,
947
4001
        BorderStyle::Ridge => 7,
948
30105
        BorderStyle::Inset => 8,
949
4003
        BorderStyle::Outset => 9,
950
    }
951
709842
}
952

            
953
/// Encode 4 border styles into a u16: [3:0]=top, [7:4]=right, [11:8]=bottom, [15:12]=left
954
#[inline]
955
#[must_use]
956
10382
pub const fn encode_border_styles_packed(
957
10382
    top: BorderStyle,
958
10382
    right: BorderStyle,
959
10382
    bottom: BorderStyle,
960
10382
    left: BorderStyle,
961
10382
) -> u16 {
962
10382
    (border_style_to_u8(top) as u16)
963
10382
        | ((border_style_to_u8(right) as u16) << 4)
964
10382
        | ((border_style_to_u8(bottom) as u16) << 8)
965
10382
        | ((border_style_to_u8(left) as u16) << 12)
966
10382
}
967

            
968
/// Decode border-top-style from packed u16
969
#[inline]
970
#[must_use]
971
1991420
pub const fn decode_border_top_style(packed: u16) -> BorderStyle {
972
1991420
    border_style_from_u8((packed & 0x0F) as u8)
973
1991420
}
974

            
975
/// Decode border-right-style from packed u16
976
#[inline]
977
#[must_use]
978
1925882
pub const fn decode_border_right_style(packed: u16) -> BorderStyle {
979
1925882
    border_style_from_u8(((packed >> 4) & 0x0F) as u8)
980
1925882
}
981

            
982
/// Decode border-bottom-style from packed u16
983
#[inline]
984
#[must_use]
985
1925882
pub const fn decode_border_bottom_style(packed: u16) -> BorderStyle {
986
1925882
    border_style_from_u8(((packed >> 8) & 0x0F) as u8)
987
1925882
}
988

            
989
/// Decode border-left-style from packed u16
990
#[inline]
991
#[must_use]
992
1991419
pub const fn decode_border_left_style(packed: u16) -> BorderStyle {
993
1991419
    border_style_from_u8(((packed >> 12) & 0x0F) as u8)
994
1991419
}
995

            
996
/// Encode a `ColorU` as u32 (0xRRGGBBAA). Returns 0 for sentinel/unset.
997
#[inline]
998
#[must_use]
999
728809
pub const fn encode_color_u32(c: &ColorU) -> u32 {
728809
    ((c.r as u32) << 24) | ((c.g as u32) << 16) | ((c.b as u32) << 8) | (c.a as u32)
728809
}
/// Decode a u32 back to `ColorU`. Returns `None` if sentinel (`0x00000000`).
///
/// **Limitation:** `rgba(0,0,0,0)` (fully transparent black) also encodes as
/// `0x00000000` and will be decoded as `None` (unset). This is acceptable
/// because fully transparent black is visually indistinguishable from unset.
#[inline]
#[must_use]
633
pub const fn decode_color_u32(v: u32) -> Option<ColorU> {
633
    if v == 0 {
5
        return None;
628
    }
628
    Some(ColorU {
628
        r: ((v >> 24) & 0xFF) as u8,
628
        g: ((v >> 16) & 0xFF) as u8,
628
        b: ((v >> 8) & 0xFF) as u8,
628
        a: (v & 0xFF) as u8,
628
    })
633
}
// =============================================================================
// Tier 1: Encode / Decode
// =============================================================================
/// Pack all 21 enum properties into a single u64.
#[inline]
#[must_use]
409
pub const fn encode_tier1(
409
    display: LayoutDisplay,
409
    position: LayoutPosition,
409
    float: LayoutFloat,
409
    overflow_x: LayoutOverflow,
409
    overflow_y: LayoutOverflow,
409
    box_sizing: LayoutBoxSizing,
409
    flex_direction: LayoutFlexDirection,
409
    flex_wrap: LayoutFlexWrap,
409
    justify_content: LayoutJustifyContent,
409
    align_items: LayoutAlignItems,
409
    align_content: LayoutAlignContent,
409
    writing_mode: LayoutWritingMode,
409
    clear: LayoutClear,
409
    font_weight: StyleFontWeight,
409
    font_style: StyleFontStyle,
409
    text_align: StyleTextAlign,
409
    visibility: StyleVisibility,
409
    white_space: StyleWhiteSpace,
409
    direction: StyleDirection,
409
    vertical_align: StyleVerticalAlign,
409
    border_collapse: StyleBorderCollapse,
409
) -> u64 {
409
    let mut v: u64 = TIER1_POPULATED_BIT;
409
    v |= (layout_display_to_u8(display) as u64) << DISPLAY_SHIFT;
409
    v |= (layout_position_to_u8(position) as u64) << POSITION_SHIFT;
409
    v |= (layout_float_to_u8(float) as u64) << FLOAT_SHIFT;
409
    v |= (layout_overflow_to_u8(overflow_x) as u64) << OVERFLOW_X_SHIFT;
409
    v |= (layout_overflow_to_u8(overflow_y) as u64) << OVERFLOW_Y_SHIFT;
409
    v |= (layout_box_sizing_to_u8(box_sizing) as u64) << BOX_SIZING_SHIFT;
409
    v |= (layout_flex_direction_to_u8(flex_direction) as u64) << FLEX_DIRECTION_SHIFT;
409
    v |= (layout_flex_wrap_to_u8(flex_wrap) as u64) << FLEX_WRAP_SHIFT;
409
    v |= (layout_justify_content_to_u8(justify_content) as u64) << JUSTIFY_CONTENT_SHIFT;
409
    v |= (layout_align_items_to_u8(align_items) as u64) << ALIGN_ITEMS_SHIFT;
409
    v |= (layout_align_content_to_u8(align_content) as u64) << ALIGN_CONTENT_SHIFT;
409
    v |= (layout_writing_mode_to_u8(writing_mode) as u64) << WRITING_MODE_SHIFT;
409
    v |= (layout_clear_to_u8(clear) as u64) << CLEAR_SHIFT;
409
    v |= (style_font_weight_to_u8(font_weight) as u64) << FONT_WEIGHT_SHIFT;
409
    v |= (style_font_style_to_u8(font_style) as u64) << FONT_STYLE_SHIFT;
409
    v |= (style_text_align_to_u8(text_align) as u64) << TEXT_ALIGN_SHIFT;
409
    v |= (style_visibility_to_u8(visibility) as u64) << VISIBILITY_SHIFT;
409
    v |= (style_white_space_to_u8(white_space) as u64) << WHITE_SPACE_SHIFT;
409
    v |= (style_direction_to_u8(direction) as u64) << DIRECTION_SHIFT;
409
    v |= (style_vertical_align_to_u8(vertical_align) as u64) << VERTICAL_ALIGN_SHIFT;
409
    v |= (border_collapse_to_u8(border_collapse) as u64) << BORDER_COLLAPSE_SHIFT;
409
    v
409
}
// Decode individual enum properties from a Tier 1 u64.
// Each function is `#[inline]` for zero-cost extraction.
#[inline]
#[must_use]
8778202
pub const fn decode_display(t1: u64) -> LayoutDisplay {
8778202
    layout_display_from_u8(((t1 >> DISPLAY_SHIFT) & DISPLAY_MASK) as u8)
8778202
}
#[inline]
#[must_use]
4287211
pub const fn decode_position(t1: u64) -> LayoutPosition {
4287211
    layout_position_from_u8(((t1 >> POSITION_SHIFT) & POSITION_MASK) as u8)
4287211
}
#[inline]
#[must_use]
1750002
pub const fn decode_float(t1: u64) -> LayoutFloat {
1750002
    layout_float_from_u8(((t1 >> FLOAT_SHIFT) & FLOAT_MASK) as u8)
1750002
}
#[inline]
#[must_use]
4079454
pub const fn decode_overflow_x(t1: u64) -> LayoutOverflow {
4079454
    layout_overflow_from_u8(((t1 >> OVERFLOW_X_SHIFT) & OVERFLOW_MASK) as u8)
4079454
}
#[inline]
#[must_use]
3800130
pub const fn decode_overflow_y(t1: u64) -> LayoutOverflow {
3800130
    layout_overflow_from_u8(((t1 >> OVERFLOW_Y_SHIFT) & OVERFLOW_MASK) as u8)
3800130
}
#[inline]
#[must_use]
521274
pub const fn decode_box_sizing(t1: u64) -> LayoutBoxSizing {
521274
    layout_box_sizing_from_u8(((t1 >> BOX_SIZING_SHIFT) & BOX_SIZING_MASK) as u8)
521274
}
#[inline]
#[must_use]
239286
pub const fn decode_flex_direction(t1: u64) -> LayoutFlexDirection {
239286
    layout_flex_direction_from_u8(((t1 >> FLEX_DIRECTION_SHIFT) & FLEX_DIR_MASK) as u8)
239286
}
#[inline]
#[must_use]
162534
pub const fn decode_flex_wrap(t1: u64) -> LayoutFlexWrap {
162534
    layout_flex_wrap_from_u8(((t1 >> FLEX_WRAP_SHIFT) & FLEX_WRAP_MASK) as u8)
162534
}
#[inline]
#[must_use]
4134
pub const fn decode_justify_content(t1: u64) -> LayoutJustifyContent {
4134
    layout_justify_content_from_u8(((t1 >> JUSTIFY_CONTENT_SHIFT) & JUSTIFY_MASK) as u8)
4134
}
#[inline]
#[must_use]
162534
pub const fn decode_align_items(t1: u64) -> LayoutAlignItems {
162534
    layout_align_items_from_u8(((t1 >> ALIGN_ITEMS_SHIFT) & ALIGN_MASK) as u8)
162534
}
#[inline]
#[must_use]
162534
pub const fn decode_align_content(t1: u64) -> LayoutAlignContent {
162534
    layout_align_content_from_u8(((t1 >> ALIGN_CONTENT_SHIFT) & ALIGN_MASK) as u8)
162534
}
#[inline]
#[must_use]
1317450
pub const fn decode_writing_mode(t1: u64) -> LayoutWritingMode {
1317450
    layout_writing_mode_from_u8(((t1 >> WRITING_MODE_SHIFT) & WRITING_MODE_MASK) as u8)
1317450
}
#[inline]
#[must_use]
66414
pub const fn decode_clear(t1: u64) -> LayoutClear {
66414
    layout_clear_from_u8(((t1 >> CLEAR_SHIFT) & CLEAR_MASK) as u8)
66414
}
#[inline]
#[must_use]
228714
pub const fn decode_font_weight(t1: u64) -> StyleFontWeight {
228714
    style_font_weight_from_u8(((t1 >> FONT_WEIGHT_SHIFT) & FONT_WEIGHT_MASK) as u8)
228714
}
#[inline]
#[must_use]
228714
pub const fn decode_font_style(t1: u64) -> StyleFontStyle {
228714
    style_font_style_from_u8(((t1 >> FONT_STYLE_SHIFT) & FONT_STYLE_MASK) as u8)
228714
}
#[inline]
#[must_use]
1079406
pub const fn decode_text_align(t1: u64) -> StyleTextAlign {
1079406
    style_text_align_from_u8(((t1 >> TEXT_ALIGN_SHIFT) & TEXT_ALIGN_MASK) as u8)
1079406
}
#[inline]
#[must_use]
2926650
pub const fn decode_visibility(t1: u64) -> StyleVisibility {
2926650
    style_visibility_from_u8(((t1 >> VISIBILITY_SHIFT) & VISIBILITY_MASK) as u8)
2926650
}
#[inline]
#[must_use]
883782
pub const fn decode_white_space(t1: u64) -> StyleWhiteSpace {
883782
    style_white_space_from_u8(((t1 >> WHITE_SPACE_SHIFT) & WHITE_SPACE_MASK) as u8)
883782
}
#[inline]
#[must_use]
858798
pub const fn decode_direction(t1: u64) -> StyleDirection {
858798
    style_direction_from_u8(((t1 >> DIRECTION_SHIFT) & DIRECTION_MASK) as u8)
858798
}
#[inline]
#[must_use]
4135
pub const fn decode_vertical_align(t1: u64) -> StyleVerticalAlign {
4135
    style_vertical_align_from_u8(((t1 >> VERTICAL_ALIGN_SHIFT) & VERTICAL_ALIGN_MASK) as u8)
4135
}
#[inline]
#[must_use]
6187
pub const fn decode_border_collapse(t1: u64) -> StyleBorderCollapse {
6187
    border_collapse_from_u8(((t1 >> BORDER_COLLAPSE_SHIFT) & BORDER_COLLAPSE_MASK) as u8)
6187
}
/// Returns true if the tier1 u64 was actually populated by `encode_tier1`.
#[inline]
#[cfg(test)]
#[must_use]
4102
pub const fn tier1_is_populated(t1: u64) -> bool {
4102
    (t1 & TIER1_POPULATED_BIT) != 0
4102
}
// =============================================================================
// Tier 2: CompactNodeProps — numeric dimensions (64 bytes/node)
// =============================================================================
/// u32 encoding for dimension properties (width, height, min-*, max-*, flex-basis, font-size).
///
/// Layout: `[3:0] SizeMetric (4 bits) | [31:4] signed fixed-point ×1000 (28 bits)`
///
/// This matches `FloatValue`'s internal representation (isize × 1000).
/// Range: ±134,217.727 at 0.001 precision (28-bit signed = ±2^27 = ±134,217,728 / 1000).
///
/// Sentinel values use the top of the u32 range (0xFFFFFFF9..0xFFFFFFFF).
///
/// Encode a `PixelValue` into u32 with `SizeMetric`. Returns `U32_SENTINEL` if out of range.
#[inline]
#[must_use]
915976
pub fn encode_pixel_value_u32(pv: &PixelValue) -> u32 {
915976
    let metric = u32::from(size_metric_to_u8(pv.metric));
915976
    let raw = pv.number.number; // already × 1000 (FloatValue internal repr)
                                // 28-bit signed range: -134_217_728 ..= +134_217_727
915976
    if !(-134_217_728..=134_217_727).contains(&raw) {
458
        return U32_SENTINEL; // overflow → tier 3
915518
    }
    // Pack: low 4 bits = metric, upper 28 bits = value (as unsigned offset)
    // raw is range-checked to 28 bits above; reinterpret its low 32 bits for packing.
915518
    let value_bits = i32::try_from(raw).unwrap_or(0).cast_unsigned() << 4;
915518
    let packed = value_bits | metric;
    // A legitimate small NEGATIVE value with a high metric nibble (e.g. -1 in
    // vh/vmin/vmax packs to 0xFFFF_FFF9/FA/FB) lands in the reserved sentinel band
    // [U32_SENTINEL_THRESHOLD, U32_SENTINEL] and decode would misread it as an unset
    // sentinel. Escape to tier 3 so the real value is stored losslessly instead.
915518
    if packed >= U32_SENTINEL_THRESHOLD {
66
        return U32_SENTINEL;
915452
    }
915452
    packed
915976
}
/// Decode a u32 back to `PixelValue`. Returns None for sentinel values.
#[inline]
#[must_use]
1583321
pub const fn decode_pixel_value_u32(encoded: u32) -> Option<PixelValue> {
1583321
    if encoded >= U32_SENTINEL_THRESHOLD {
178
        return None; // sentinel
1583143
    }
1583143
    let metric = size_metric_from_u8((encoded & 0xF) as u8);
    // Cast to i32 FIRST, then arithmetic right-shift to preserve sign bit
1583143
    let value_bits = encoded.cast_signed() >> 4;
1583143
    let raw = value_bits as isize; // × 1000
1583143
    Some(PixelValue {
1583143
        metric,
1583143
        number: FloatValue { number: raw },
1583143
    })
1583321
}
/// Encode an i16 resolved px value (×10). Returns `I16_SENTINEL` if out of range.
/// Range: -3276.8 ..= +3276.3 px at 0.1px precision.
#[inline]
#[must_use]
3204043
pub fn encode_resolved_px_i16(px: f32) -> i16 {
3204043
    let scaled = crate::cast::f32_to_i32((px * 10.0).round());
3204043
    if scaled < -32768 || scaled > i32::from(I16_SENTINEL_THRESHOLD) - 1 {
370
        return I16_SENTINEL; // overflow or too large → tier 3
3203673
    }
3203673
    i16::try_from(scaled).unwrap_or(I16_SENTINEL)
3204043
}
/// Decode an i16 back to resolved px. Returns None for sentinel values.
#[inline]
#[must_use]
371688
pub fn decode_resolved_px_i16(v: i16) -> Option<f32> {
371688
    if v >= I16_SENTINEL_THRESHOLD {
96479
        return None;
275209
    }
275209
    Some(f32::from(v) / 10.0)
371688
}
/// Encode a u16 flex value (×100). Returns `U16_SENTINEL` if out of range.
/// Range: 0.00 ..= 655.27 at 0.01 precision.
#[inline]
#[must_use]
855659
pub fn encode_flex_u16(value: f32) -> u16 {
855659
    let scaled = crate::cast::f32_to_i32((value * 100.0).round());
855659
    if scaled < 0 || scaled >= i32::from(U16_SENTINEL_THRESHOLD) {
49
        return U16_SENTINEL;
855610
    }
855610
    u16::try_from(scaled).unwrap_or(U16_SENTINEL)
855659
}
/// Decode a u16 flex value back to f32. Returns None for sentinel values.
#[inline]
#[must_use]
382345
pub fn decode_flex_u16(v: u16) -> Option<f32> {
382345
    if v >= U16_SENTINEL_THRESHOLD {
7
        return None;
382338
    }
382338
    Some(f32::from(v) / 100.0)
382345
}
/// `SizeMetric` → u8 (4 bits, 12 variants)
#[inline]
#[must_use]
915988
pub const fn size_metric_to_u8(m: SizeMetric) -> u8 {
915988
    match m {
853948
        SizeMetric::Px => 0,
54
        SizeMetric::Pt => 1,
2421
        SizeMetric::Em => 2,
74
        SizeMetric::Rem => 3,
14
        SizeMetric::In => 4,
14
        SizeMetric::Cm => 5,
14
        SizeMetric::Mm => 6,
58953
        SizeMetric::Percent => 7,
391
        SizeMetric::Vw => 8,
35
        SizeMetric::Vh => 9,
35
        SizeMetric::Vmin => 10,
35
        SizeMetric::Vmax => 11,
    }
915988
}
/// u8 → `SizeMetric`
#[inline]
#[must_use]
1583387
pub const fn size_metric_from_u8(v: u8) -> SizeMetric {
1583387
    match v {
1548405
        0 => SizeMetric::Px,
47
        1 => SizeMetric::Pt,
516
        2 => SizeMetric::Em,
67
        3 => SizeMetric::Rem,
7
        4 => SizeMetric::In,
7
        5 => SizeMetric::Cm,
7
        6 => SizeMetric::Mm,
34005
        7 => SizeMetric::Percent,
60
        8 => SizeMetric::Vw,
6
        9 => SizeMetric::Vh,
6
        10 => SizeMetric::Vmin,
6
        11 => SizeMetric::Vmax,
248
        _ => SizeMetric::Px,
    }
1583387
}
/// Layout-hot compact numeric properties for a single node (68 bytes).
/// Only fields accessed during the constraint-solving loop.
/// All dimensions use MSB-sentinel encoding.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct CompactNodeProps {
    // --- Dimensions needing unit (u32 MSB-sentinel) ---
    pub width: u32,
    pub height: u32,
    pub min_width: u32,
    pub max_width: u32,
    pub min_height: u32,
    pub max_height: u32,
    pub flex_basis: u32,
    pub font_size: u32,
    // --- Resolved px values (i16 MSB-sentinel, ×10) ---
    pub padding_top: i16,
    pub padding_right: i16,
    pub padding_bottom: i16,
    pub padding_left: i16,
    pub margin_top: i16,
    pub margin_right: i16,
    pub margin_bottom: i16,
    pub margin_left: i16,
    pub border_top_width: i16,
    pub border_right_width: i16,
    pub border_bottom_width: i16,
    pub border_left_width: i16,
    pub top: i16,
    pub right: i16,
    pub bottom: i16,
    pub left: i16,
    // --- Flex (u16 MSB-sentinel, ×100) ---
    pub flex_grow: u16,
    pub flex_shrink: u16,
    // --- Gap (i16 px×10, 0 = default) ---
    pub row_gap: i16,
    pub column_gap: i16,
}
/// Paint-cold compact properties for a single node.
/// Only accessed during display list generation, table layout, or text shaping.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct CompactNodePropsCold {
    // --- Border colors (u32 RGBA as 0xRRGGBBAA, 0 = unset sentinel) ---
    pub border_top_color: u32,
    pub border_right_color: u32,
    pub border_bottom_color: u32,
    pub border_left_color: u32,
    // --- Border radii (i16 px × 10, I16_SENTINEL = unset/default = 0) ---
    pub border_top_left_radius: i16,
    pub border_top_right_radius: i16,
    pub border_bottom_left_radius: i16,
    pub border_bottom_right_radius: i16,
    // --- Other ---
    pub z_index: i16, // range ±32764, sentinel = 0x7FFF
    /// Border styles packed: [3:0]=top, [7:4]=right, [11:8]=bottom, [15:12]=left
    pub border_styles_packed: u16,
    pub border_spacing_h: i16,
    pub border_spacing_v: i16,
    pub tab_size: i16,
    /// Grid column start (`I16_AUTO` = auto, positive = line number, negative = span)
    pub grid_col_start: i16,
    /// Grid column end
    pub grid_col_end: i16,
    /// Grid row start
    pub grid_row_start: i16,
    /// Grid row end
    pub grid_row_end: i16,
    // --- GPU / hot paint props ---
    /// Opacity × 254 (0 = fully transparent, 254 = opaque). 255 = unset/default (= 1.0).
    pub opacity: u8,
    /// Resolved `cursor`, as a `cursor_to_u8` code (0 = `Default`).
    ///
    /// It is INHERITABLE per spec and is resolved on every mouse move, so it
    /// wants a flat per-node read - but the tier-1 word has no free bits (see
    /// the note by the bit masks), and taking bit 53 silently overwrote
    /// `align-self`. This byte fits in padding this struct already had, so the
    /// read stays one index and the struct does not grow.
    pub cursor: u8,
    /// Bitflags for properties that are usually unset. Lets the getter
    /// short-circuit without a cascade walk when the value is the default.
    ///
    /// bit 0: `has_transform`                (slow-walk only when set)
    /// bit 1: `has_transform_origin`
    /// bit 2: `has_box_shadow`
    /// bit 3: `has_text_decoration`          (slow-walk only when set)
    /// bits 4-5: `scrollbar_gutter` (0 = auto default, 1 = stable, 2 = both-edges, 3 = mirror)
    /// bit 6: `has_background`                (slow-walk only when set; ≈ negative fast path)
    /// bit 7: `has_clip_path`                 (slow-walk only when set)
    pub hot_flags: u8,
    /// Second byte of flags for rarely-set properties.
    ///
    /// bit 0: `has_any_scrollbar_css`
    ///        OR of all -azul-scrollbar-* / scrollbar-color / scrollbar-width props.
    ///        When clear, `get_scrollbar_style` can skip 8 cascade walks and use
    ///        the UA-default result.
    /// bit 1: `has_counter`      (counter-reset OR counter-increment)
    /// bit 2: `has_break`        (break-before OR break-after)
    /// bit 3: `has_text_orientation`
    /// bit 4: `has_text_shadow`
    /// bit 5: `has_backdrop_filter`
    /// bit 6: `has_filter`
    /// bit 7: `has_mix_blend_mode`
    pub extra_flags: u8,
}
pub const OPACITY_SENTINEL: u8 = 255;
pub const HOT_FLAG_HAS_TRANSFORM: u8 = 1 << 0;
pub const HOT_FLAG_HAS_TRANSFORM_ORIGIN: u8 = 1 << 1;
pub const HOT_FLAG_HAS_BOX_SHADOW: u8 = 1 << 2;
pub const HOT_FLAG_HAS_TEXT_DECORATION: u8 = 1 << 3;
pub const HOT_FLAG_SCROLLBAR_GUTTER_SHIFT: u8 = 4;
pub const HOT_FLAG_SCROLLBAR_GUTTER_MASK: u8 = 0b0011_0000;
pub const HOT_FLAG_HAS_BACKGROUND: u8 = 1 << 6;
pub const HOT_FLAG_HAS_CLIP_PATH: u8 = 1 << 7;
pub const EXTRA_FLAG_HAS_SCROLLBAR_CSS: u8 = 1 << 0;
pub const EXTRA_FLAG_HAS_COUNTER: u8 = 1 << 1;
pub const EXTRA_FLAG_HAS_BREAK: u8 = 1 << 2;
pub const EXTRA_FLAG_HAS_TEXT_ORIENTATION: u8 = 1 << 3;
pub const EXTRA_FLAG_HAS_TEXT_SHADOW: u8 = 1 << 4;
pub const EXTRA_FLAG_HAS_BACKDROP_FILTER: u8 = 1 << 5;
pub const EXTRA_FLAG_HAS_FILTER: u8 = 1 << 6;
pub const EXTRA_FLAG_HAS_MIX_BLEND_MODE: u8 = 1 << 7;
// ---- DOM-level rare text prop flags (stored on CompactLayoutCache) ----
// Each bit = "some node in this DOM declared this property".
// When clear, cascade walks for that prop anywhere in the DOM
// necessarily return None → callers can skip the walk and use
// the default value. Eliminates ~N × IFC-count walks per layout
// in typical pages where these props are never declared.
pub const DOM_HAS_SHAPE_INSIDE: u32 = 1 << 0;
pub const DOM_HAS_SHAPE_OUTSIDE: u32 = 1 << 1;
pub const DOM_HAS_TEXT_JUSTIFY: u32 = 1 << 2;
pub const DOM_HAS_TEXT_INDENT: u32 = 1 << 3;
pub const DOM_HAS_COLUMN_COUNT: u32 = 1 << 4;
pub const DOM_HAS_COLUMN_GAP: u32 = 1 << 5;
pub const DOM_HAS_INITIAL_LETTER: u32 = 1 << 6;
pub const DOM_HAS_INITIAL_LETTER_ALIGN: u32 = 1 << 7;
pub const DOM_HAS_LINE_CLAMP: u32 = 1 << 8;
pub const DOM_HAS_HANGING_PUNCTUATION: u32 = 1 << 9;
pub const DOM_HAS_TEXT_COMBINE_UPRIGHT: u32 = 1 << 10;
pub const DOM_HAS_EXCLUSION_MARGIN: u32 = 1 << 11;
pub const DOM_HAS_HYPHENATION_LANGUAGE: u32 = 1 << 12;
pub const DOM_HAS_UNICODE_BIDI: u32 = 1 << 13;
pub const DOM_HAS_TEXT_BOX_TRIM: u32 = 1 << 14;
pub const DOM_HAS_HYPHENS: u32 = 1 << 15;
pub const DOM_HAS_WORD_BREAK: u32 = 1 << 16;
pub const DOM_HAS_OVERFLOW_WRAP: u32 = 1 << 17;
pub const DOM_HAS_LINE_BREAK: u32 = 1 << 18;
pub const DOM_HAS_TEXT_ALIGN_LAST: u32 = 1 << 19;
pub const DOM_HAS_LINE_HEIGHT: u32 = 1 << 20;
pub const DOM_HAS_COLUMN_WIDTH: u32 = 1 << 21;
pub const DOM_HAS_SHAPE_MARGIN: u32 = 1 << 22;
pub const SCROLLBAR_GUTTER_AUTO: u8 = 0;
pub const SCROLLBAR_GUTTER_STABLE: u8 = 1;
pub const SCROLLBAR_GUTTER_BOTH_EDGES: u8 = 2;
pub const SCROLLBAR_GUTTER_MIRROR: u8 = 3;
impl Default for CompactNodeProps {
134695
    fn default() -> Self {
134695
        Self {
134695
            // All dimensions default to Auto
134695
            width: U32_AUTO,
134695
            height: U32_AUTO,
134695
            min_width: U32_AUTO,
134695
            max_width: U32_NONE,
134695
            min_height: U32_AUTO,
134695
            max_height: U32_NONE,
134695
            flex_basis: U32_AUTO,
134695
            font_size: U32_INITIAL,
134695
            // All resolved px default to 0
134695
            padding_top: 0,
134695
            padding_right: 0,
134695
            padding_bottom: 0,
134695
            padding_left: 0,
134695
            margin_top: 0,
134695
            margin_right: 0,
134695
            margin_bottom: 0,
134695
            margin_left: 0,
134695
            border_top_width: 0,
134695
            border_right_width: 0,
134695
            border_bottom_width: 0,
134695
            border_left_width: 0,
134695
            top: I16_AUTO,
134695
            right: I16_AUTO,
134695
            bottom: I16_AUTO,
134695
            left: I16_AUTO,
134695
            // Flex defaults
134695
            flex_grow: 0,
134695
            flex_shrink: encode_flex_u16(1.0), // CSS default: flex-shrink: 1
134695

            
134695
            // Gap defaults
134695
            row_gap: 0,
134695
            column_gap: 0,
134695
        }
134695
    }
}
impl Default for CompactNodePropsCold {
134473
    fn default() -> Self {
134473
        Self {
134473
            // Border colors default to 0 (sentinel/unset)
134473
            border_top_color: 0,
134473
            border_right_color: 0,
134473
            border_bottom_color: 0,
134473
            border_left_color: 0,
134473
            // Border radii: I16_SENTINEL means "no rounded corner" (skip slow walk)
134473
            border_top_left_radius: I16_SENTINEL,
134473
            border_top_right_radius: I16_SENTINEL,
134473
            border_bottom_left_radius: I16_SENTINEL,
134473
            border_bottom_right_radius: I16_SENTINEL,
134473
            // Other
134473
            z_index: I16_AUTO,
134473
            border_styles_packed: 0, // all BorderStyle::None
134473
            border_spacing_h: 0,
134473
            border_spacing_v: 0,
134473
            tab_size: I16_SENTINEL, // default is 8em, needs resolution → sentinel
134473
            grid_col_start: I16_AUTO,
134473
            grid_col_end: I16_AUTO,
134473
            grid_row_start: I16_AUTO,
134473
            grid_row_end: I16_AUTO,
134473
            opacity: OPACITY_SENTINEL,
134473
            // 0 is `StyleCursor::Default`, so a zeroed node needs no fixup.
134473
            cursor: 0,
134473
            hot_flags: 0,
134473
            extra_flags: 0,
134473
        }
134473
    }
}
// =============================================================================
// Tier 2b: CompactTextProps — IFC/text properties (24 bytes/node)
// =============================================================================
/// Compact text/IFC properties for a single node (24 bytes).
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct CompactTextProps {
    pub text_color: u32,       // RGBA as 0xRRGGBBAA (0 = transparent/unset)
    pub font_family_hash: u64, // FxHash of font-family list (0 = sentinel/unset)
    /// Split scale by SIGN (parser convention: negative normalized =
    /// absolute px): negative = -px x 10 (line-height: 40px -> -400),
    /// positive = unitless multiple x 1000 (1.2 / 120% -> 1200).
    /// `I16_SENTINEL` = unset ("normal").
    pub line_height: i16,
    pub letter_spacing: i16, // px × 10
    pub word_spacing: i16,   // px × 10
    pub text_indent: i16,    // px × 10
}
impl Default for CompactTextProps {
134443
    fn default() -> Self {
134443
        Self {
134443
            text_color: 0,
134443
            font_family_hash: 0,
134443
            line_height: I16_SENTINEL, // "normal" → sentinel
134443
            letter_spacing: 0,
134443
            word_spacing: 0,
134443
            text_indent: 0,
134443
        }
134443
    }
}
// =============================================================================
// Tier 3: Overflow map — rare/complex properties
// =============================================================================
// Overflow properties that couldn't fit in Tier 1/2 encoding.
// Contains the original `CssProperty` values for properties that:
// - Have `calc()` expressions
// - Exceed the numeric range of compact encoding
// - Are rare CSS properties (grid, transforms, etc.)
// =============================================================================
// CompactLayoutCache — the top-level container
// =============================================================================
/// Three-tier compact layout property cache.
///
/// Allocated once per restyle, indexed by node index (same as `NodeId`).
/// Provides O(1) array-indexed access to all layout properties.
///
/// Non-compact properties (background, box-shadow, transform, etc.) are
/// resolved via the slow cascade path in `CssPropertyCache::get_property_slow()`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompactLayoutCache {
    /// Whether ANY layout-relevant pixel value in this document uses a
    /// viewport-relative unit (vw/vh/vmin/vmax), detected while the build
    /// loop extracts those very values (text tier + box dimensions — the set
    /// that feeds inline collection and measurement).
    ///
    /// Consumers use it to SKIP viewport-based cache invalidation for the
    /// overwhelmingly common document that never mentions a viewport unit:
    /// solver3's inline-collection fingerprint folded `ctx.viewport_size`
    /// into EVERY IFC's key "because vw/vh", so every resize invalidated
    /// every collection (552 re-collections ≈ 19.6 ms per resize on big.md)
    /// to protect a feature the document did not use. False negatives are
    /// impossible for the covered set (the flag is set from the same values
    /// the cache encodes); a property OUTSIDE the covered set cannot reach
    /// inline collection, which is the only consumer.
    pub uses_viewport_units: bool,
    /// Tier 1: ALL enum properties bitpacked into u64 per node (8 B/node)
    pub tier1_enums: Vec<u64>,
    /// Tier 2 hot: Layout-critical numeric dimensions per node (68 B/node)
    pub tier2_dims: Vec<CompactNodeProps>,
    /// Tier 2 cold: Paint-only properties per node (28 B/node)
    pub tier2_cold: Vec<CompactNodePropsCold>,
    /// Tier 2b: Text/IFC properties per node (24 B/node)
    pub tier2b_text: Vec<CompactTextProps>,
    /// Indices of nodes whose `font_family_hash` changed since the last frame.
    ///
    /// Enables **per-node** font dirty tracking instead of the global all-or-nothing
    /// `font_stacks_hash` XOR approach. When this list is non-empty, only the
    /// font chains for these specific nodes need to be re-resolved, avoiding O(N)
    /// re-resolution when a single node's `font-family` changes.
    ///
    /// Populated during `build_compact_cache()` by comparing each node's
    /// `font_family_hash` against `prev_font_hashes`.
    pub font_dirty_nodes: Vec<usize>,
    /// Previous frame's per-node `font_family_hash` values.
    ///
    /// Stored after each compact cache build so that the next build can detect
    /// which specific nodes' font-family changed (rather than relying on a
    /// collision-prone global XOR hash).
    pub prev_font_hashes: Vec<u64>,
    /// Reverse map: `font_family_hash` (u64) → actual `StyleFontFamilyVec`.
    ///
    /// Populated during `build_compact_cache()` as a byproduct of hash computation.
    /// Consumers use this to look up font family names from the compact cache hash
    /// without going through `get_property_slow()` (which fails for inherited values
    /// on text nodes).
    pub font_hash_to_families:
        alloc::collections::BTreeMap<u64, crate::props::basic::font::StyleFontFamilyVec>,
    /// True when any node's inline style carries a NON-pseudo dynamic
    /// condition (viewport/@media, theme, OS, container...). The window uses
    /// this to decide whether a `DynamicSelectorContext` change (a resize
    /// crossing a breakpoint, a theme flip) requires rebuilding this cache:
    /// for the overwhelmingly common condition-free DOM the answer is a
    /// single bool read.
    pub has_dynamic_conditions: bool,
    /// Bitfield tracking which rare text props are declared *anywhere* in the DOM.
    /// Built once during `build_compact_cache_with_inheritance`. When a bit is
    /// clear, callers (e.g. `translate_to_text3_constraints`) can skip the
    /// cascade walk for that property — its slow path would always return
    /// `None` and fall back to the default. See `DOM_HAS_*` constants.
    pub dom_declared_flags: u32,
    /// Viewport WIDTH thresholds harvested from every inline conditional
    /// property in the DOM — where a `ViewportWidth` condition can flip.
    /// Stored as `f32::to_bits` (this struct derives `Eq`); sorted +
    /// deduped. Together with the author stylesheet's
    /// `Css::viewport_breakpoints`, these replace the old hardcoded
    /// breakpoint guess list in the engine's resize decision (a widget
    /// breakpoint like the ribbon's 720px was invisible to that list, so
    /// shrinking onto the mobile layout never regenerated).
    pub inline_viewport_w: Vec<u32>,
    /// Viewport HEIGHT thresholds, same contract as `inline_viewport_w`.
    pub inline_viewport_h: Vec<u32>,
}
impl CompactLayoutCache {
    /// Create an empty cache (no nodes).
    #[must_use]
3
    pub const fn empty() -> Self {
3
        Self {
3
            uses_viewport_units: false,
3
            tier1_enums: Vec::new(),
3
            tier2_dims: Vec::new(),
3
            tier2_cold: Vec::new(),
3
            tier2b_text: Vec::new(),
3
            font_dirty_nodes: Vec::new(),
3
            prev_font_hashes: Vec::new(),
3
            font_hash_to_families: alloc::collections::BTreeMap::new(),
3
            dom_declared_flags: 0,
3
            has_dynamic_conditions: false,
3
            inline_viewport_w: Vec::new(),
3
            inline_viewport_h: Vec::new(),
3
        }
3
    }
    /// Create a cache pre-allocated for `node_count` nodes, filled with defaults.
    #[must_use]
66817
    pub fn with_capacity(node_count: usize) -> Self {
66817
        Self {
66817
            uses_viewport_units: false,
66817
            tier1_enums: vec![0u64; node_count],
66817
            tier2_dims: vec![CompactNodeProps::default(); node_count],
66817
            tier2_cold: vec![CompactNodePropsCold::default(); node_count],
66817
            tier2b_text: vec![CompactTextProps::default(); node_count],
66817
            font_dirty_nodes: Vec::new(),
66817
            prev_font_hashes: vec![0u64; node_count],
66817
            font_hash_to_families: alloc::collections::BTreeMap::new(),
66817
            dom_declared_flags: 0,
66817
            has_dynamic_conditions: false,
66817
            inline_viewport_w: Vec::new(),
66817
            inline_viewport_h: Vec::new(),
66817
        }
66817
    }
    /// Number of nodes in this cache.
    #[inline]
    #[must_use]
17
    pub const fn node_count(&self) -> usize {
17
        self.tier1_enums.len()
17
    }
    // -- Tier 1 getters (enum properties) --
    #[inline]
    #[must_use]
8774071
    pub fn get_display(&self, node_idx: usize) -> LayoutDisplay {
8774071
        decode_display(self.tier1_enums[node_idx])
8774071
    }
    #[inline]
    #[must_use]
4283079
    pub fn get_position(&self, node_idx: usize) -> LayoutPosition {
4283079
        decode_position(self.tier1_enums[node_idx])
4283079
    }
    #[inline]
    #[must_use]
1745871
    pub fn get_float(&self, node_idx: usize) -> LayoutFloat {
1745871
        decode_float(self.tier1_enums[node_idx])
1745871
    }
    #[inline]
    #[must_use]
4075323
    pub fn get_overflow_x(&self, node_idx: usize) -> LayoutOverflow {
4075323
        decode_overflow_x(self.tier1_enums[node_idx])
4075323
    }
    #[inline]
    #[must_use]
3795999
    pub fn get_overflow_y(&self, node_idx: usize) -> LayoutOverflow {
3795999
        decode_overflow_y(self.tier1_enums[node_idx])
3795999
    }
    #[inline]
    #[must_use]
517143
    pub fn get_box_sizing(&self, node_idx: usize) -> LayoutBoxSizing {
517143
        decode_box_sizing(self.tier1_enums[node_idx])
517143
    }
    #[inline]
    #[must_use]
235155
    pub fn get_flex_direction(&self, node_idx: usize) -> LayoutFlexDirection {
235155
        decode_flex_direction(self.tier1_enums[node_idx])
235155
    }
    #[inline]
    #[must_use]
158403
    pub fn get_flex_wrap(&self, node_idx: usize) -> LayoutFlexWrap {
158403
        decode_flex_wrap(self.tier1_enums[node_idx])
158403
    }
    #[inline]
    #[must_use]
3
    pub fn get_justify_content(&self, node_idx: usize) -> LayoutJustifyContent {
3
        decode_justify_content(self.tier1_enums[node_idx])
3
    }
    #[inline]
    #[must_use]
158403
    pub fn get_align_items(&self, node_idx: usize) -> LayoutAlignItems {
158403
        decode_align_items(self.tier1_enums[node_idx])
158403
    }
    #[inline]
    #[must_use]
158403
    pub fn get_align_content(&self, node_idx: usize) -> LayoutAlignContent {
158403
        decode_align_content(self.tier1_enums[node_idx])
158403
    }
    #[inline]
    #[must_use]
1313319
    pub fn get_writing_mode(&self, node_idx: usize) -> LayoutWritingMode {
1313319
        decode_writing_mode(self.tier1_enums[node_idx])
1313319
    }
    #[inline]
    #[must_use]
62283
    pub fn get_clear(&self, node_idx: usize) -> LayoutClear {
62283
        decode_clear(self.tier1_enums[node_idx])
62283
    }
    #[inline]
    #[must_use]
224583
    pub fn get_font_weight(&self, node_idx: usize) -> StyleFontWeight {
224583
        decode_font_weight(self.tier1_enums[node_idx])
224583
    }
    #[inline]
    #[must_use]
224583
    pub fn get_font_style(&self, node_idx: usize) -> StyleFontStyle {
224583
        decode_font_style(self.tier1_enums[node_idx])
224583
    }
    #[inline]
    #[must_use]
1075275
    pub fn get_text_align(&self, node_idx: usize) -> StyleTextAlign {
1075275
        decode_text_align(self.tier1_enums[node_idx])
1075275
    }
    #[inline]
    #[must_use]
2922519
    pub fn get_visibility(&self, node_idx: usize) -> StyleVisibility {
2922519
        decode_visibility(self.tier1_enums[node_idx])
2922519
    }
    #[inline]
    #[must_use]
879651
    pub fn get_white_space(&self, node_idx: usize) -> StyleWhiteSpace {
879651
        decode_white_space(self.tier1_enums[node_idx])
879651
    }
    #[inline]
    #[must_use]
854667
    pub fn get_direction(&self, node_idx: usize) -> StyleDirection {
854667
        decode_direction(self.tier1_enums[node_idx])
854667
    }
    #[inline]
    #[must_use]
3
    pub fn get_vertical_align(&self, node_idx: usize) -> StyleVerticalAlign {
3
        decode_vertical_align(self.tier1_enums[node_idx])
3
    }
    #[inline]
    #[must_use]
2055
    pub fn get_border_collapse(&self, node_idx: usize) -> StyleBorderCollapse {
2055
        decode_border_collapse(self.tier1_enums[node_idx])
2055
    }
    /// The resolved `cursor` for a node — one byte read.
    #[inline]
    #[must_use]
    pub fn get_cursor(&self, node_idx: usize) -> StyleCursor {
        cursor_from_u8(self.tier2_cold[node_idx].cursor)
    }
    // -- Tier 2 getters (numeric dimensions) --
    /// Get width as encoded u32 (use `decode_pixel_value_u32` or check sentinel).
    #[inline]
    #[must_use]
1257235
    pub fn get_width_raw(&self, node_idx: usize) -> u32 {
1257235
        self.tier2_dims[node_idx].width
1257235
    }
    #[inline]
    #[must_use]
1331799
    pub fn get_height_raw(&self, node_idx: usize) -> u32 {
1331799
        self.tier2_dims[node_idx].height
1331799
    }
    #[inline]
    #[must_use]
809043
    pub fn get_min_width_raw(&self, node_idx: usize) -> u32 {
809043
        self.tier2_dims[node_idx].min_width
809043
    }
    #[inline]
    #[must_use]
534171
    pub fn get_max_width_raw(&self, node_idx: usize) -> u32 {
534171
        self.tier2_dims[node_idx].max_width
534171
    }
    #[inline]
    #[must_use]
808935
    pub fn get_min_height_raw(&self, node_idx: usize) -> u32 {
808935
        self.tier2_dims[node_idx].min_height
808935
    }
    #[inline]
    #[must_use]
534063
    pub fn get_max_height_raw(&self, node_idx: usize) -> u32 {
534063
        self.tier2_dims[node_idx].max_height
534063
    }
    #[inline]
    #[must_use]
102042
    pub fn get_font_size_raw(&self, node_idx: usize) -> u32 {
102042
        self.tier2_dims[node_idx].font_size
102042
    }
    #[inline]
    #[must_use]
158403
    pub fn get_flex_basis_raw(&self, node_idx: usize) -> u32 {
158403
        self.tier2_dims[node_idx].flex_basis
158403
    }
    /// Get padding-top as resolved px. Returns None if sentinel (needs slow path).
    #[inline]
    #[must_use]
5
    pub fn get_padding_top(&self, node_idx: usize) -> Option<f32> {
5
        decode_resolved_px_i16(self.tier2_dims[node_idx].padding_top)
5
    }
    #[inline]
    #[must_use]
3
    pub fn get_padding_right(&self, node_idx: usize) -> Option<f32> {
3
        decode_resolved_px_i16(self.tier2_dims[node_idx].padding_right)
3
    }
    #[inline]
    #[must_use]
3
    pub fn get_padding_bottom(&self, node_idx: usize) -> Option<f32> {
3
        decode_resolved_px_i16(self.tier2_dims[node_idx].padding_bottom)
3
    }
    #[inline]
    #[must_use]
3
    pub fn get_padding_left(&self, node_idx: usize) -> Option<f32> {
3
        decode_resolved_px_i16(self.tier2_dims[node_idx].padding_left)
3
    }
    #[inline]
    #[must_use]
3
    pub fn get_margin_top(&self, node_idx: usize) -> Option<f32> {
3
        let v = self.tier2_dims[node_idx].margin_top;
3
        if v == I16_AUTO {
            return None;
3
        } // Auto for margin is special
3
        decode_resolved_px_i16(v)
3
    }
    #[inline]
    #[must_use]
    pub fn get_margin_right(&self, node_idx: usize) -> Option<f32> {
        let v = self.tier2_dims[node_idx].margin_right;
        if v == I16_AUTO {
            return None;
        }
        decode_resolved_px_i16(v)
    }
    #[inline]
    #[must_use]
    pub fn get_margin_bottom(&self, node_idx: usize) -> Option<f32> {
        let v = self.tier2_dims[node_idx].margin_bottom;
        if v == I16_AUTO {
            return None;
        }
        decode_resolved_px_i16(v)
    }
    #[inline]
    #[must_use]
3
    pub fn get_margin_left(&self, node_idx: usize) -> Option<f32> {
3
        let v = self.tier2_dims[node_idx].margin_left;
3
        if v == I16_AUTO {
            return None;
3
        }
3
        decode_resolved_px_i16(v)
3
    }
    /// Check if margin is Auto (important for centering logic).
    #[inline]
    #[must_use]
3
    pub fn is_margin_top_auto(&self, node_idx: usize) -> bool {
3
        self.tier2_dims[node_idx].margin_top == I16_AUTO
3
    }
    #[inline]
    #[must_use]
3
    pub fn is_margin_right_auto(&self, node_idx: usize) -> bool {
3
        self.tier2_dims[node_idx].margin_right == I16_AUTO
3
    }
    #[inline]
    #[must_use]
3
    pub fn is_margin_bottom_auto(&self, node_idx: usize) -> bool {
3
        self.tier2_dims[node_idx].margin_bottom == I16_AUTO
3
    }
    #[inline]
    #[must_use]
3
    pub fn is_margin_left_auto(&self, node_idx: usize) -> bool {
3
        self.tier2_dims[node_idx].margin_left == I16_AUTO
3
    }
    #[inline]
    #[must_use]
3
    pub fn get_border_top_width(&self, node_idx: usize) -> Option<f32> {
3
        decode_resolved_px_i16(self.tier2_dims[node_idx].border_top_width)
3
    }
    #[inline]
    #[must_use]
    pub fn get_border_right_width(&self, node_idx: usize) -> Option<f32> {
        decode_resolved_px_i16(self.tier2_dims[node_idx].border_right_width)
    }
    #[inline]
    #[must_use]
    pub fn get_border_bottom_width(&self, node_idx: usize) -> Option<f32> {
        decode_resolved_px_i16(self.tier2_dims[node_idx].border_bottom_width)
    }
    #[inline]
    #[must_use]
3
    pub fn get_border_left_width(&self, node_idx: usize) -> Option<f32> {
3
        decode_resolved_px_i16(self.tier2_dims[node_idx].border_left_width)
3
    }
    // -- Raw i16 getters for macro fast paths --
    #[inline]
    #[must_use]
553968
    pub fn get_padding_top_raw(&self, node_idx: usize) -> i16 {
553968
        self.tier2_dims[node_idx].padding_top
553968
    }
    #[inline]
    #[must_use]
553872
    pub fn get_padding_right_raw(&self, node_idx: usize) -> i16 {
553872
        self.tier2_dims[node_idx].padding_right
553872
    }
    #[inline]
    #[must_use]
553968
    pub fn get_padding_bottom_raw(&self, node_idx: usize) -> i16 {
553968
        self.tier2_dims[node_idx].padding_bottom
553968
    }
    #[inline]
    #[must_use]
553872
    pub fn get_padding_left_raw(&self, node_idx: usize) -> i16 {
553872
        self.tier2_dims[node_idx].padding_left
553872
    }
    #[inline]
    #[must_use]
452604
    pub fn get_margin_top_raw(&self, node_idx: usize) -> i16 {
452604
        self.tier2_dims[node_idx].margin_top
452604
    }
    #[inline]
    #[must_use]
452604
    pub fn get_margin_right_raw(&self, node_idx: usize) -> i16 {
452604
        self.tier2_dims[node_idx].margin_right
452604
    }
    #[inline]
    #[must_use]
452604
    pub fn get_margin_bottom_raw(&self, node_idx: usize) -> i16 {
452604
        self.tier2_dims[node_idx].margin_bottom
452604
    }
    #[inline]
    #[must_use]
452604
    pub fn get_margin_left_raw(&self, node_idx: usize) -> i16 {
452604
        self.tier2_dims[node_idx].margin_left
452604
    }
    #[inline]
    #[must_use]
2074368
    pub fn get_border_top_width_raw(&self, node_idx: usize) -> i16 {
2074368
        self.tier2_dims[node_idx].border_top_width
2074368
    }
    #[inline]
    #[must_use]
2074272
    pub fn get_border_right_width_raw(&self, node_idx: usize) -> i16 {
2074272
        self.tier2_dims[node_idx].border_right_width
2074272
    }
    #[inline]
    #[must_use]
2074368
    pub fn get_border_bottom_width_raw(&self, node_idx: usize) -> i16 {
2074368
        self.tier2_dims[node_idx].border_bottom_width
2074368
    }
    #[inline]
    #[must_use]
2074272
    pub fn get_border_left_width_raw(&self, node_idx: usize) -> i16 {
2074272
        self.tier2_dims[node_idx].border_left_width
2074272
    }
    #[inline]
    #[must_use]
168843
    pub fn get_top(&self, node_idx: usize) -> i16 {
168843
        self.tier2_dims[node_idx].top
168843
    }
    #[inline]
    #[must_use]
168843
    pub fn get_right(&self, node_idx: usize) -> i16 {
168843
        self.tier2_dims[node_idx].right
168843
    }
    #[inline]
    #[must_use]
168843
    pub fn get_bottom(&self, node_idx: usize) -> i16 {
168843
        self.tier2_dims[node_idx].bottom
168843
    }
    #[inline]
    #[must_use]
168843
    pub fn get_left(&self, node_idx: usize) -> i16 {
168843
        self.tier2_dims[node_idx].left
168843
    }
    #[inline]
    #[must_use]
158403
    pub fn get_flex_grow(&self, node_idx: usize) -> Option<f32> {
158403
        decode_flex_u16(self.tier2_dims[node_idx].flex_grow)
158403
    }
    #[inline]
    #[must_use]
158403
    pub fn get_flex_shrink(&self, node_idx: usize) -> Option<f32> {
158403
        decode_flex_u16(self.tier2_dims[node_idx].flex_shrink)
158403
    }
    #[inline]
    #[must_use]
1912889
    pub fn get_z_index(&self, node_idx: usize) -> i16 {
1912889
        self.tier2_cold[node_idx].z_index
1912889
    }
    // -- Border colors (u32 RGBA) — cold tier --
    #[inline]
    #[must_use]
1621677
    pub fn get_border_top_color_raw(&self, node_idx: usize) -> u32 {
1621677
        self.tier2_cold[node_idx].border_top_color
1621677
    }
    #[inline]
    #[must_use]
1621668
    pub fn get_border_right_color_raw(&self, node_idx: usize) -> u32 {
1621668
        self.tier2_cold[node_idx].border_right_color
1621668
    }
    #[inline]
    #[must_use]
1621668
    pub fn get_border_bottom_color_raw(&self, node_idx: usize) -> u32 {
1621668
        self.tier2_cold[node_idx].border_bottom_color
1621668
    }
    #[inline]
    #[must_use]
1621668
    pub fn get_border_left_color_raw(&self, node_idx: usize) -> u32 {
1621668
        self.tier2_cold[node_idx].border_left_color
1621668
    }
    // -- Border styles (packed u16) — cold tier --
    #[inline]
    #[must_use]
3
    pub fn get_border_styles_packed(&self, node_idx: usize) -> u16 {
3
        self.tier2_cold[node_idx].border_styles_packed
3
    }
    #[inline]
    #[must_use]
1915876
    pub fn get_border_top_style(&self, node_idx: usize) -> BorderStyle {
1915876
        decode_border_top_style(self.tier2_cold[node_idx].border_styles_packed)
1915876
    }
    #[inline]
    #[must_use]
1915875
    pub fn get_border_right_style(&self, node_idx: usize) -> BorderStyle {
1915875
        decode_border_right_style(self.tier2_cold[node_idx].border_styles_packed)
1915875
    }
    #[inline]
    #[must_use]
1915875
    pub fn get_border_bottom_style(&self, node_idx: usize) -> BorderStyle {
1915875
        decode_border_bottom_style(self.tier2_cold[node_idx].border_styles_packed)
1915875
    }
    #[inline]
    #[must_use]
1915875
    pub fn get_border_left_style(&self, node_idx: usize) -> BorderStyle {
1915875
        decode_border_left_style(self.tier2_cold[node_idx].border_styles_packed)
1915875
    }
    // -- Border spacing — cold tier --
    #[inline]
    #[must_use]
483
    pub fn get_border_spacing_h_raw(&self, node_idx: usize) -> i16 {
483
        self.tier2_cold[node_idx].border_spacing_h
483
    }
    #[inline]
    #[must_use]
483
    pub fn get_border_spacing_v_raw(&self, node_idx: usize) -> i16 {
483
        self.tier2_cold[node_idx].border_spacing_v
483
    }
    // -- Tab size — cold tier --
    #[inline]
    #[must_use]
102039
    pub fn get_tab_size_raw(&self, node_idx: usize) -> i16 {
102039
        self.tier2_cold[node_idx].tab_size
102039
    }
    // -- Border radii — cold tier (i16 px × 10, I16_SENTINEL = unset = 0) --
    #[inline]
    #[must_use]
3050247
    pub fn get_border_top_left_radius_raw(&self, node_idx: usize) -> i16 {
3050247
        self.tier2_cold[node_idx].border_top_left_radius
3050247
    }
    #[inline]
    #[must_use]
3050244
    pub fn get_border_top_right_radius_raw(&self, node_idx: usize) -> i16 {
3050244
        self.tier2_cold[node_idx].border_top_right_radius
3050244
    }
    #[inline]
    #[must_use]
3050244
    pub fn get_border_bottom_left_radius_raw(&self, node_idx: usize) -> i16 {
3050244
        self.tier2_cold[node_idx].border_bottom_left_radius
3050244
    }
    #[inline]
    #[must_use]
3050244
    pub fn get_border_bottom_right_radius_raw(&self, node_idx: usize) -> i16 {
3050244
        self.tier2_cold[node_idx].border_bottom_right_radius
3050244
    }
    // -- Opacity / transform / hot flags --
    /// Raw opacity byte. `OPACITY_SENTINEL` (255) = unset (default = 1.0).
    /// Otherwise value / 254.0 yields the opacity in [0.0, 1.0].
    #[inline]
    #[must_use]
2482585
    pub fn get_opacity_raw(&self, node_idx: usize) -> u8 {
2482585
        self.tier2_cold[node_idx].opacity
2482585
    }
    #[inline]
    #[must_use]
3
    pub fn get_hot_flags(&self, node_idx: usize) -> u8 {
3
        self.tier2_cold[node_idx].hot_flags
3
    }
    #[inline]
    #[must_use]
2456838
    pub fn has_transform(&self, node_idx: usize) -> bool {
2456838
        self.tier2_cold[node_idx].hot_flags & HOT_FLAG_HAS_TRANSFORM != 0
2456838
    }
    #[inline]
    #[must_use]
9
    pub fn has_transform_origin(&self, node_idx: usize) -> bool {
9
        self.tier2_cold[node_idx].hot_flags & HOT_FLAG_HAS_TRANSFORM_ORIGIN != 0
9
    }
    #[inline]
    #[must_use]
2207769
    pub fn has_box_shadow(&self, node_idx: usize) -> bool {
2207769
        self.tier2_cold[node_idx].hot_flags & HOT_FLAG_HAS_BOX_SHADOW != 0
2207769
    }
    #[inline]
    #[must_use]
102045
    pub fn has_text_decoration(&self, node_idx: usize) -> bool {
102045
        self.tier2_cold[node_idx].hot_flags & HOT_FLAG_HAS_TEXT_DECORATION != 0
102045
    }
    #[inline]
    #[must_use]
1733993
    pub fn has_background(&self, node_idx: usize) -> bool {
1733993
        self.tier2_cold[node_idx].hot_flags & HOT_FLAG_HAS_BACKGROUND != 0
1733993
    }
    #[inline]
    #[must_use]
977413
    pub fn has_clip_path(&self, node_idx: usize) -> bool {
977413
        self.tier2_cold[node_idx].hot_flags & HOT_FLAG_HAS_CLIP_PATH != 0
977413
    }
    #[inline]
    #[must_use]
966263
    pub fn has_scrollbar_css(&self, node_idx: usize) -> bool {
966263
        self.tier2_cold[node_idx].extra_flags & EXTRA_FLAG_HAS_SCROLLBAR_CSS != 0
966263
    }
    #[inline]
    #[must_use]
342419
    pub fn has_counter(&self, node_idx: usize) -> bool {
342419
        self.tier2_cold[node_idx].extra_flags & EXTRA_FLAG_HAS_COUNTER != 0
342419
    }
    #[inline]
    #[must_use]
1932227
    pub fn has_break(&self, node_idx: usize) -> bool {
1932227
        self.tier2_cold[node_idx].extra_flags & EXTRA_FLAG_HAS_BREAK != 0
1932227
    }
    #[inline]
    #[must_use]
791279
    pub fn has_text_orientation(&self, node_idx: usize) -> bool {
791279
        self.tier2_cold[node_idx].extra_flags & EXTRA_FLAG_HAS_TEXT_ORIENTATION != 0
791279
    }
    #[inline]
    #[must_use]
23
    pub fn has_text_shadow(&self, node_idx: usize) -> bool {
23
        self.tier2_cold[node_idx].extra_flags & EXTRA_FLAG_HAS_TEXT_SHADOW != 0
23
    }
    #[inline]
    #[must_use]
23
    pub fn has_backdrop_filter(&self, node_idx: usize) -> bool {
23
        self.tier2_cold[node_idx].extra_flags & EXTRA_FLAG_HAS_BACKDROP_FILTER != 0
23
    }
    #[inline]
    #[must_use]
23
    pub fn has_filter(&self, node_idx: usize) -> bool {
23
        self.tier2_cold[node_idx].extra_flags & EXTRA_FLAG_HAS_FILTER != 0
23
    }
    #[inline]
    #[must_use]
11
    pub fn has_mix_blend_mode(&self, node_idx: usize) -> bool {
11
        self.tier2_cold[node_idx].extra_flags & EXTRA_FLAG_HAS_MIX_BLEND_MODE != 0
11
    }
    /// DOM-level fast-path check: returns `true` if the given flag bit is set
    /// (some node in this DOM declared the corresponding property).
    #[inline]
    #[must_use]
73
    pub const fn dom_declared(&self, flag: u32) -> bool {
73
        self.dom_declared_flags & flag != 0
73
    }
    /// Scrollbar-gutter: 0 = auto (default), 1 = stable, 2 = both-edges, 3 = mirror.
    #[inline]
    #[must_use]
1456695
    pub fn get_scrollbar_gutter_bits(&self, node_idx: usize) -> u8 {
1456695
        (self.tier2_cold[node_idx].hot_flags & HOT_FLAG_SCROLLBAR_GUTTER_MASK)
1456695
            >> HOT_FLAG_SCROLLBAR_GUTTER_SHIFT
1456695
    }
    // -- Tier 2b getters (text props) --
    #[inline]
    #[must_use]
102044
    pub fn get_text_color_raw(&self, node_idx: usize) -> u32 {
102044
        self.tier2b_text[node_idx].text_color
102044
    }
    #[inline]
    #[must_use]
4
    pub fn get_font_family_hash(&self, node_idx: usize) -> u64 {
4
        self.tier2b_text[node_idx].font_family_hash
4
    }
    #[inline]
    #[must_use]
102040
    pub fn get_line_height(&self, node_idx: usize) -> Option<f32> {
102040
        decode_resolved_px_i16(self.tier2b_text[node_idx].line_height)
102040
    }
    #[inline]
    #[must_use]
102039
    pub fn get_letter_spacing(&self, node_idx: usize) -> Option<f32> {
102039
        decode_resolved_px_i16(self.tier2b_text[node_idx].letter_spacing)
102039
    }
    #[inline]
    #[must_use]
102039
    pub fn get_word_spacing(&self, node_idx: usize) -> Option<f32> {
102039
        decode_resolved_px_i16(self.tier2b_text[node_idx].word_spacing)
102039
    }
    #[inline]
    #[must_use]
3
    pub fn get_text_indent(&self, node_idx: usize) -> Option<f32> {
3
        decode_resolved_px_i16(self.tier2b_text[node_idx].text_indent)
3
    }
}
// =============================================================================
// Helper: encode a CssPropertyValue<PixelValue> into i16 resolved-px
// =============================================================================
/// Resolve a `CssPropertyValue`<PixelValue> to an i16 ×10 encoding.
///
/// Only handles `Exact(px(...))` values. Everything else → sentinel.
/// For the compact cache builder, we only pre-resolve absolute pixel values.
/// Relative units (em, %, etc.) get sentinel and fall back to the slow path.
#[inline]
#[must_use]
3383940
pub fn encode_css_pixel_as_i16(prop: &CssPropertyValue<PixelValue>) -> i16 {
3383940
    match prop {
3383639
        CssPropertyValue::Exact(pv) => {
3383639
            if pv.metric == SizeMetric::Px {
2863317
                encode_resolved_px_i16(pv.number.get())
            } else {
520322
                I16_SENTINEL // non-px units need resolution context → slow path
            }
        }
171
        CssPropertyValue::Auto => I16_AUTO,
21
        CssPropertyValue::Initial => I16_INITIAL,
21
        CssPropertyValue::Inherit => I16_INHERIT,
88
        _ => I16_SENTINEL,
    }
3383940
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
1
    fn test_tier1_roundtrip() {
1
        let t1 = encode_tier1(
1
            LayoutDisplay::Flex,
1
            LayoutPosition::Relative,
1
            LayoutFloat::Left,
1
            LayoutOverflow::Hidden,
1
            LayoutOverflow::Scroll,
1
            LayoutBoxSizing::BorderBox,
1
            LayoutFlexDirection::Column,
1
            LayoutFlexWrap::Wrap,
1
            LayoutJustifyContent::SpaceBetween,
1
            LayoutAlignItems::Center,
1
            LayoutAlignContent::End,
1
            LayoutWritingMode::VerticalRl,
1
            LayoutClear::Both,
1
            StyleFontWeight::Bold,
1
            StyleFontStyle::Italic,
1
            StyleTextAlign::Center,
1
            StyleVisibility::Hidden,
1
            StyleWhiteSpace::Pre,
1
            StyleDirection::Rtl,
1
            StyleVerticalAlign::Middle,
1
            StyleBorderCollapse::Collapse,
        );
1
        assert!(tier1_is_populated(t1));
1
        assert_eq!(decode_display(t1), LayoutDisplay::Flex);
1
        assert_eq!(decode_position(t1), LayoutPosition::Relative);
1
        assert_eq!(decode_float(t1), LayoutFloat::Left);
1
        assert_eq!(decode_overflow_x(t1), LayoutOverflow::Hidden);
1
        assert_eq!(decode_overflow_y(t1), LayoutOverflow::Scroll);
1
        assert_eq!(decode_box_sizing(t1), LayoutBoxSizing::BorderBox);
1
        assert_eq!(decode_flex_direction(t1), LayoutFlexDirection::Column);
1
        assert_eq!(decode_flex_wrap(t1), LayoutFlexWrap::Wrap);
1
        assert_eq!(
1
            decode_justify_content(t1),
            LayoutJustifyContent::SpaceBetween
        );
1
        assert_eq!(decode_align_items(t1), LayoutAlignItems::Center);
1
        assert_eq!(decode_align_content(t1), LayoutAlignContent::End);
1
        assert_eq!(decode_writing_mode(t1), LayoutWritingMode::VerticalRl);
1
        assert_eq!(decode_clear(t1), LayoutClear::Both);
1
        assert_eq!(decode_font_weight(t1), StyleFontWeight::Bold);
1
        assert_eq!(decode_font_style(t1), StyleFontStyle::Italic);
1
        assert_eq!(decode_text_align(t1), StyleTextAlign::Center);
1
        assert_eq!(decode_visibility(t1), StyleVisibility::Hidden);
1
        assert_eq!(decode_white_space(t1), StyleWhiteSpace::Pre);
1
        assert_eq!(decode_direction(t1), StyleDirection::Rtl);
1
        assert_eq!(decode_vertical_align(t1), StyleVerticalAlign::Middle);
1
        assert_eq!(decode_border_collapse(t1), StyleBorderCollapse::Collapse);
1
    }
    #[test]
1
    fn test_tier1_defaults() {
1
        let t1 = encode_tier1(
1
            LayoutDisplay::Block,
1
            LayoutPosition::Static,
1
            LayoutFloat::None,
1
            LayoutOverflow::Visible,
1
            LayoutOverflow::Visible,
1
            LayoutBoxSizing::ContentBox,
1
            LayoutFlexDirection::Row,
1
            LayoutFlexWrap::NoWrap,
1
            LayoutJustifyContent::FlexStart,
1
            LayoutAlignItems::Stretch,
1
            LayoutAlignContent::Stretch,
1
            LayoutWritingMode::HorizontalTb,
1
            LayoutClear::None,
1
            StyleFontWeight::Normal,
1
            StyleFontStyle::Normal,
1
            StyleTextAlign::Left,
1
            StyleVisibility::Visible,
1
            StyleWhiteSpace::Normal,
1
            StyleDirection::Ltr,
1
            StyleVerticalAlign::Baseline,
1
            StyleBorderCollapse::Separate,
        );
1
        assert!(tier1_is_populated(t1));
1
        assert_eq!(decode_display(t1), LayoutDisplay::Block);
1
        assert_eq!(decode_position(t1), LayoutPosition::Static);
1
    }
    #[test]
1
    fn test_pixel_value_u32_roundtrip() {
1
        let pv = PixelValue::px(123.456);
1
        let encoded = encode_pixel_value_u32(&pv);
1
        assert!(encoded < U32_SENTINEL_THRESHOLD);
1
        let decoded = decode_pixel_value_u32(encoded).unwrap();
1
        assert_eq!(decoded.metric, SizeMetric::Px);
        // Check within precision (×1000)
1
        assert!((decoded.number.get() - 123.456).abs() < 0.002);
1
    }
    #[test]
1
    fn test_pixel_value_u32_percent() {
1
        let pv = PixelValue {
1
            metric: SizeMetric::Percent,
1
            number: FloatValue::new(50.0),
1
        };
1
        let encoded = encode_pixel_value_u32(&pv);
1
        let decoded = decode_pixel_value_u32(encoded).unwrap();
1
        assert_eq!(decoded.metric, SizeMetric::Percent);
1
        assert!((decoded.number.get() - 50.0).abs() < 0.002);
1
    }
    #[test]
1
    fn test_sentinel_values() {
1
        assert_eq!(decode_pixel_value_u32(U32_SENTINEL), None);
1
        assert_eq!(decode_pixel_value_u32(U32_AUTO), None);
1
        assert_eq!(decode_pixel_value_u32(U32_MIN_CONTENT), None);
1
        assert_eq!(decode_resolved_px_i16(I16_SENTINEL), None);
1
        assert_eq!(decode_resolved_px_i16(I16_AUTO), None);
1
    }
    #[test]
1
    fn test_resolved_px_i16_roundtrip() {
1
        let px = 123.4f32;
1
        let encoded = encode_resolved_px_i16(px);
1
        let decoded = decode_resolved_px_i16(encoded).unwrap();
1
        assert!((decoded - 123.4).abs() < 0.11);
        // Negative values
1
        let px = -50.7f32;
1
        let encoded = encode_resolved_px_i16(px);
1
        let decoded = decode_resolved_px_i16(encoded).unwrap();
1
        assert!((decoded - (-50.7)).abs() < 0.11);
1
    }
    #[test]
1
    fn test_flex_u16_roundtrip() {
1
        let v = 2.5f32;
1
        let encoded = encode_flex_u16(v);
1
        let decoded = decode_flex_u16(encoded).unwrap();
1
        assert!((decoded - 2.5).abs() < 0.011);
1
    }
    #[test]
1
    fn test_compact_node_props_size() {
        // 72B hot props: 8×u32 dimensions (32B) + 16×i16 box model (32B)
        // + 2×u16 flex (4B) + 1×i16 order + align/pos tier1 bits (4B).
1
        assert_eq!(size_of::<CompactNodeProps>(), 72);
1
    }
    #[test]
1
    fn test_compact_node_props_cold_size() {
        // 48B cold props: 4×u32 border colors (16B) + 4×i16 border radii (8B)
        // + 1×i16 z_index + 1×u16 border_styles_packed + 2×i16 border_spacing
        // + 1×i16 tab_size + 4×i16 grid placement (8B) + 3×u8 (opacity,
        // hot_flags, extra_flags) = 45B, padded to 48B for u32 alignment.
1
        assert_eq!(size_of::<CompactNodePropsCold>(), 48);
1
    }
    #[test]
1
    fn test_compact_text_props_size() {
1
        assert_eq!(size_of::<CompactTextProps>(), 24);
1
    }
    // ========================================================================
    // Tier1 enum 0-sentinel contract
    //
    // Tier1 packs 21 enums into a single u64. A bit run that is all zeros
    // must decode to the CSS initial value of that property, because an
    // unpopulated tier1 field is all zeros. If any encoder shifts so that
    // `0 -> something-other-than-initial`, every node that didn't explicitly
    // set the property silently gets the wrong default — which is exactly
    // how the calc.c grid stretch regression shipped (Start encoded as 0,
    // so every grid container reported justify-items: Start instead of
    // the CSS default Stretch-for-grid, collapsing the calc button grid).
    //
    // Test invariant: decoding a u8 of 0 for every enum yields the CSS
    // initial value of that property.
    // ========================================================================
    #[test]
1
    fn test_justify_items_zero_is_stretch() {
        // CSS initial for justify-items is `normal`, which on a grid item
        // behaves as `stretch`. The tier1 bit pattern 0 must round-trip to
        // Stretch so unset grid containers don't collapse their items.
1
        assert_eq!(layout_justify_items_from_u8(0), LayoutJustifyItems::Stretch);
1
        assert_eq!(layout_justify_items_to_u8(LayoutJustifyItems::Stretch), 0);
1
    }
    #[test]
1
    fn test_tier1_enum_zero_sentinel_is_css_initial() {
1
        assert_eq!(layout_display_from_u8(0), LayoutDisplay::Block);
1
        assert_eq!(layout_position_from_u8(0), LayoutPosition::Static);
1
        assert_eq!(layout_float_from_u8(0), LayoutFloat::None);
1
        assert_eq!(layout_overflow_from_u8(0), LayoutOverflow::Visible);
1
        assert_eq!(layout_box_sizing_from_u8(0), LayoutBoxSizing::ContentBox);
1
        assert_eq!(layout_flex_direction_from_u8(0), LayoutFlexDirection::Row);
1
        assert_eq!(layout_flex_wrap_from_u8(0), LayoutFlexWrap::NoWrap);
1
        assert_eq!(
1
            layout_justify_content_from_u8(0),
            LayoutJustifyContent::FlexStart
        );
1
        assert_eq!(layout_align_items_from_u8(0), LayoutAlignItems::Stretch);
1
        assert_eq!(layout_align_content_from_u8(0), LayoutAlignContent::Stretch);
1
        assert_eq!(layout_align_self_from_u8(0), LayoutAlignSelf::Auto);
1
        assert_eq!(layout_justify_self_from_u8(0), LayoutJustifySelf::Auto);
1
        assert_eq!(layout_justify_items_from_u8(0), LayoutJustifyItems::Stretch);
1
        assert_eq!(layout_grid_auto_flow_from_u8(0), LayoutGridAutoFlow::Row);
1
        assert_eq!(
1
            layout_writing_mode_from_u8(0),
            LayoutWritingMode::HorizontalTb
        );
1
        assert_eq!(layout_clear_from_u8(0), LayoutClear::None);
1
        assert_eq!(style_font_weight_from_u8(0), StyleFontWeight::Normal);
1
        assert_eq!(style_font_style_from_u8(0), StyleFontStyle::Normal);
        // text-align initial is `start`; we collapse `start` → `left` on
        // LTR runs at encode time, so the 0 slot decodes to Left.
1
        assert_eq!(style_text_align_from_u8(0), StyleTextAlign::Start);
1
        assert_eq!(style_visibility_from_u8(0), StyleVisibility::Visible);
1
        assert_eq!(style_white_space_from_u8(0), StyleWhiteSpace::Normal);
1
        assert_eq!(style_direction_from_u8(0), StyleDirection::Ltr);
1
        assert_eq!(
1
            style_vertical_align_from_u8(0),
            StyleVerticalAlign::Baseline
        );
1
        assert_eq!(border_collapse_from_u8(0), StyleBorderCollapse::Separate);
1
    }
    #[test]
1
    fn test_tier1_enum_initial_encodes_to_zero() {
        // Mirror of the above — encoding the CSS initial value must
        // produce 0, otherwise an `all-zeros` tier1 bit run would encode
        // a non-initial value and nodes without explicit properties would
        // silently inherit the wrong default.
1
        assert_eq!(layout_display_to_u8(LayoutDisplay::Block), 0);
1
        assert_eq!(layout_position_to_u8(LayoutPosition::Static), 0);
1
        assert_eq!(layout_float_to_u8(LayoutFloat::None), 0);
1
        assert_eq!(layout_overflow_to_u8(LayoutOverflow::Visible), 0);
1
        assert_eq!(layout_box_sizing_to_u8(LayoutBoxSizing::ContentBox), 0);
1
        assert_eq!(layout_flex_direction_to_u8(LayoutFlexDirection::Row), 0);
1
        assert_eq!(layout_flex_wrap_to_u8(LayoutFlexWrap::NoWrap), 0);
1
        assert_eq!(
1
            layout_justify_content_to_u8(LayoutJustifyContent::FlexStart),
            0
        );
1
        assert_eq!(layout_align_items_to_u8(LayoutAlignItems::Stretch), 0);
1
        assert_eq!(layout_align_content_to_u8(LayoutAlignContent::Stretch), 0);
1
        assert_eq!(layout_align_self_to_u8(LayoutAlignSelf::Auto), 0);
1
        assert_eq!(layout_justify_self_to_u8(LayoutJustifySelf::Auto), 0);
1
        assert_eq!(layout_justify_items_to_u8(LayoutJustifyItems::Stretch), 0);
1
        assert_eq!(layout_grid_auto_flow_to_u8(LayoutGridAutoFlow::Row), 0);
1
        assert_eq!(
1
            layout_writing_mode_to_u8(LayoutWritingMode::HorizontalTb),
            0
        );
1
        assert_eq!(layout_clear_to_u8(LayoutClear::None), 0);
1
        assert_eq!(style_font_weight_to_u8(StyleFontWeight::Normal), 0);
1
        assert_eq!(style_font_style_to_u8(StyleFontStyle::Normal), 0);
1
        assert_eq!(style_text_align_to_u8(StyleTextAlign::Left), 4);
1
        assert_eq!(style_visibility_to_u8(StyleVisibility::Visible), 0);
1
        assert_eq!(style_white_space_to_u8(StyleWhiteSpace::Normal), 0);
1
        assert_eq!(style_direction_to_u8(StyleDirection::Ltr), 0);
1
        assert_eq!(style_vertical_align_to_u8(StyleVerticalAlign::Baseline), 0);
1
        assert_eq!(border_collapse_to_u8(StyleBorderCollapse::Separate), 0);
1
    }
    // ========================================================================
    // Exhaustive round-trip: every variant of every enum must survive
    // encode → decode unchanged. Catches any reordering that maps two
    // different variants to the same u8, or any mask-width mismatch.
    // ========================================================================
    macro_rules! roundtrip_all {
        ($name:ident, $to:ident, $from:ident, [$($variant:expr),+ $(,)?]) => {
            #[test]
24
            fn $name() {
155
                for v in [$($variant),+] {
131
                    let u = $to(v);
131
                    let decoded = $from(u);
131
                    assert_eq!(decoded, v, "{:?} != {:?} (via u8 = {})", decoded, v, u);
                }
24
            }
        };
    }
    roundtrip_all!(
        rt_display,
        layout_display_to_u8,
        layout_display_from_u8,
        [
            LayoutDisplay::Block,
            LayoutDisplay::Inline,
            LayoutDisplay::InlineBlock,
            LayoutDisplay::Flex,
            LayoutDisplay::None,
            LayoutDisplay::InlineFlex,
            LayoutDisplay::Table,
            LayoutDisplay::InlineTable,
            LayoutDisplay::TableRowGroup,
            LayoutDisplay::TableHeaderGroup,
            LayoutDisplay::TableFooterGroup,
            LayoutDisplay::TableRow,
            LayoutDisplay::TableColumnGroup,
            LayoutDisplay::TableColumn,
            LayoutDisplay::TableCell,
            LayoutDisplay::TableCaption,
            LayoutDisplay::FlowRoot,
            LayoutDisplay::ListItem,
            LayoutDisplay::RunIn,
            LayoutDisplay::Marker,
            LayoutDisplay::Grid,
            LayoutDisplay::InlineGrid,
            LayoutDisplay::Contents,
        ]
    );
    roundtrip_all!(
        rt_position,
        layout_position_to_u8,
        layout_position_from_u8,
        [
            LayoutPosition::Static,
            LayoutPosition::Relative,
            LayoutPosition::Absolute,
            LayoutPosition::Fixed,
            LayoutPosition::Sticky,
        ]
    );
    roundtrip_all!(
        rt_float,
        layout_float_to_u8,
        layout_float_from_u8,
        [LayoutFloat::None, LayoutFloat::Left, LayoutFloat::Right,]
    );
    roundtrip_all!(
        rt_overflow,
        layout_overflow_to_u8,
        layout_overflow_from_u8,
        [
            LayoutOverflow::Visible,
            LayoutOverflow::Hidden,
            LayoutOverflow::Scroll,
            LayoutOverflow::Auto,
            LayoutOverflow::Clip,
        ]
    );
    roundtrip_all!(
        rt_box_sizing,
        layout_box_sizing_to_u8,
        layout_box_sizing_from_u8,
        [LayoutBoxSizing::ContentBox, LayoutBoxSizing::BorderBox,]
    );
    roundtrip_all!(
        rt_flex_direction,
        layout_flex_direction_to_u8,
        layout_flex_direction_from_u8,
        [
            LayoutFlexDirection::Row,
            LayoutFlexDirection::RowReverse,
            LayoutFlexDirection::Column,
            LayoutFlexDirection::ColumnReverse,
        ]
    );
    roundtrip_all!(
        rt_flex_wrap,
        layout_flex_wrap_to_u8,
        layout_flex_wrap_from_u8,
        [
            LayoutFlexWrap::NoWrap,
            LayoutFlexWrap::Wrap,
            LayoutFlexWrap::WrapReverse,
        ]
    );
    roundtrip_all!(
        rt_justify_content,
        layout_justify_content_to_u8,
        layout_justify_content_from_u8,
        [
            LayoutJustifyContent::FlexStart,
            LayoutJustifyContent::FlexEnd,
            LayoutJustifyContent::Start,
            LayoutJustifyContent::End,
            LayoutJustifyContent::Center,
            LayoutJustifyContent::SpaceBetween,
            LayoutJustifyContent::SpaceAround,
            LayoutJustifyContent::SpaceEvenly,
        ]
    );
    roundtrip_all!(
        rt_align_items,
        layout_align_items_to_u8,
        layout_align_items_from_u8,
        [
            LayoutAlignItems::Stretch,
            LayoutAlignItems::Center,
            LayoutAlignItems::Start,
            LayoutAlignItems::End,
            LayoutAlignItems::Baseline,
        ]
    );
    roundtrip_all!(
        rt_align_self,
        layout_align_self_to_u8,
        layout_align_self_from_u8,
        [
            LayoutAlignSelf::Auto,
            LayoutAlignSelf::Stretch,
            LayoutAlignSelf::Center,
            LayoutAlignSelf::Start,
            LayoutAlignSelf::End,
            LayoutAlignSelf::Baseline,
        ]
    );
    roundtrip_all!(
        rt_justify_self,
        layout_justify_self_to_u8,
        layout_justify_self_from_u8,
        [
            LayoutJustifySelf::Auto,
            LayoutJustifySelf::Start,
            LayoutJustifySelf::End,
            LayoutJustifySelf::Center,
            LayoutJustifySelf::Stretch,
        ]
    );
    roundtrip_all!(
        rt_justify_items,
        layout_justify_items_to_u8,
        layout_justify_items_from_u8,
        [
            LayoutJustifyItems::Stretch,
            LayoutJustifyItems::Start,
            LayoutJustifyItems::End,
            LayoutJustifyItems::Center,
        ]
    );
    roundtrip_all!(
        rt_grid_auto_flow,
        layout_grid_auto_flow_to_u8,
        layout_grid_auto_flow_from_u8,
        [
            LayoutGridAutoFlow::Row,
            LayoutGridAutoFlow::Column,
            LayoutGridAutoFlow::RowDense,
            LayoutGridAutoFlow::ColumnDense,
        ]
    );
    roundtrip_all!(
        rt_align_content,
        layout_align_content_to_u8,
        layout_align_content_from_u8,
        [
            LayoutAlignContent::Stretch,
            LayoutAlignContent::Center,
            LayoutAlignContent::Start,
            LayoutAlignContent::End,
            LayoutAlignContent::SpaceBetween,
            LayoutAlignContent::SpaceAround,
        ]
    );
    roundtrip_all!(
        rt_writing_mode,
        layout_writing_mode_to_u8,
        layout_writing_mode_from_u8,
        [
            LayoutWritingMode::HorizontalTb,
            LayoutWritingMode::VerticalRl,
            LayoutWritingMode::VerticalLr,
        ]
    );
    roundtrip_all!(
        rt_clear,
        layout_clear_to_u8,
        layout_clear_from_u8,
        [
            LayoutClear::None,
            LayoutClear::Left,
            LayoutClear::Right,
            LayoutClear::Both,
        ]
    );
    roundtrip_all!(
        rt_font_weight,
        style_font_weight_to_u8,
        style_font_weight_from_u8,
        [
            StyleFontWeight::Normal,
            StyleFontWeight::W100,
            StyleFontWeight::W200,
            StyleFontWeight::W300,
            StyleFontWeight::W500,
            StyleFontWeight::W600,
            StyleFontWeight::Bold,
            StyleFontWeight::W800,
            StyleFontWeight::W900,
            StyleFontWeight::Lighter,
            StyleFontWeight::Bolder,
        ]
    );
    roundtrip_all!(
        rt_font_style,
        style_font_style_to_u8,
        style_font_style_from_u8,
        [
            StyleFontStyle::Normal,
            StyleFontStyle::Italic,
            StyleFontStyle::Oblique,
        ]
    );
    roundtrip_all!(
        rt_text_align,
        style_text_align_to_u8,
        style_text_align_from_u8,
        [
            StyleTextAlign::Left,
            StyleTextAlign::Center,
            StyleTextAlign::Right,
            StyleTextAlign::Justify,
            StyleTextAlign::Start,
            StyleTextAlign::End,
        ]
    );
    roundtrip_all!(
        rt_visibility,
        style_visibility_to_u8,
        style_visibility_from_u8,
        [
            StyleVisibility::Visible,
            StyleVisibility::Hidden,
            StyleVisibility::Collapse,
        ]
    );
    roundtrip_all!(
        rt_white_space,
        style_white_space_to_u8,
        style_white_space_from_u8,
        [
            StyleWhiteSpace::Normal,
            StyleWhiteSpace::Pre,
            StyleWhiteSpace::Nowrap,
            StyleWhiteSpace::PreWrap,
            StyleWhiteSpace::PreLine,
            StyleWhiteSpace::BreakSpaces,
        ]
    );
    roundtrip_all!(
        rt_direction,
        style_direction_to_u8,
        style_direction_from_u8,
        [StyleDirection::Ltr, StyleDirection::Rtl,]
    );
    roundtrip_all!(
        rt_vertical_align,
        style_vertical_align_to_u8,
        style_vertical_align_from_u8,
        [
            StyleVerticalAlign::Baseline,
            StyleVerticalAlign::Top,
            StyleVerticalAlign::Middle,
            StyleVerticalAlign::Bottom,
            StyleVerticalAlign::Sub,
            StyleVerticalAlign::Superscript,
            StyleVerticalAlign::TextTop,
            StyleVerticalAlign::TextBottom,
        ]
    );
    roundtrip_all!(
        rt_border_collapse,
        border_collapse_to_u8,
        border_collapse_from_u8,
        [StyleBorderCollapse::Separate, StyleBorderCollapse::Collapse,]
    );
    // ========================================================================
    // Bit-layout safety: every encoder must produce a u8 whose bits all
    // fit inside the mask allocated for that property in the tier1 u64.
    // If an enum grows a new variant that overflows its mask, the encoded
    // bits would leak into the next property's slot and silently corrupt
    // unrelated state.
    // ========================================================================
    #[test]
1
    fn test_encoded_u8_fits_in_tier1_mask() {
24
        fn assert_fits(name: &str, val: u8, mask: u64) {
24
            assert!(
24
                u64::from(val) & !mask == 0,
                "{name}: encoded u8 {val} overflows mask {mask:b}",
            );
24
        }
1
        assert_fits(
1
            "display",
1
            layout_display_to_u8(LayoutDisplay::Contents),
            DISPLAY_MASK,
        );
1
        assert_fits(
1
            "position",
1
            layout_position_to_u8(LayoutPosition::Sticky),
            POSITION_MASK,
        );
1
        assert_fits("float", layout_float_to_u8(LayoutFloat::Right), FLOAT_MASK);
1
        assert_fits(
1
            "overflow",
1
            layout_overflow_to_u8(LayoutOverflow::Clip),
            OVERFLOW_MASK,
        );
1
        assert_fits(
1
            "box_sizing",
1
            layout_box_sizing_to_u8(LayoutBoxSizing::BorderBox),
            BOX_SIZING_MASK,
        );
1
        assert_fits(
1
            "flex_direction",
1
            layout_flex_direction_to_u8(LayoutFlexDirection::ColumnReverse),
            FLEX_DIR_MASK,
        );
1
        assert_fits(
1
            "flex_wrap",
1
            layout_flex_wrap_to_u8(LayoutFlexWrap::WrapReverse),
            FLEX_WRAP_MASK,
        );
1
        assert_fits(
1
            "justify_content",
1
            layout_justify_content_to_u8(LayoutJustifyContent::SpaceEvenly),
            JUSTIFY_MASK,
        );
1
        assert_fits(
1
            "align_items",
1
            layout_align_items_to_u8(LayoutAlignItems::Baseline),
            ALIGN_MASK,
        );
1
        assert_fits(
1
            "align_self",
1
            layout_align_self_to_u8(LayoutAlignSelf::Baseline),
            ALIGN_SELF_MASK,
        );
1
        assert_fits(
1
            "justify_self",
1
            layout_justify_self_to_u8(LayoutJustifySelf::Stretch),
            JUSTIFY_SELF_MASK,
        );
1
        assert_fits(
1
            "justify_items",
1
            layout_justify_items_to_u8(LayoutJustifyItems::Center),
            JUSTIFY_ITEMS_MASK,
        );
1
        assert_fits(
1
            "grid_auto_flow",
1
            layout_grid_auto_flow_to_u8(LayoutGridAutoFlow::ColumnDense),
            GRID_AUTO_FLOW_MASK,
        );
1
        assert_fits(
1
            "align_content",
1
            layout_align_content_to_u8(LayoutAlignContent::SpaceAround),
            ALIGN_MASK,
        );
1
        assert_fits(
1
            "writing_mode",
1
            layout_writing_mode_to_u8(LayoutWritingMode::VerticalLr),
            WRITING_MODE_MASK,
        );
1
        assert_fits("clear", layout_clear_to_u8(LayoutClear::Both), CLEAR_MASK);
1
        assert_fits(
1
            "font_weight",
1
            style_font_weight_to_u8(StyleFontWeight::Bolder),
            FONT_WEIGHT_MASK,
        );
1
        assert_fits(
1
            "font_style",
1
            style_font_style_to_u8(StyleFontStyle::Oblique),
            FONT_STYLE_MASK,
        );
1
        assert_fits(
1
            "text_align",
1
            style_text_align_to_u8(StyleTextAlign::End),
            TEXT_ALIGN_MASK,
        );
1
        assert_fits(
1
            "visibility",
1
            style_visibility_to_u8(StyleVisibility::Collapse),
            VISIBILITY_MASK,
        );
1
        assert_fits(
1
            "white_space",
1
            style_white_space_to_u8(StyleWhiteSpace::BreakSpaces),
            WHITE_SPACE_MASK,
        );
1
        assert_fits(
1
            "direction",
1
            style_direction_to_u8(StyleDirection::Rtl),
            DIRECTION_MASK,
        );
1
        assert_fits(
1
            "vertical_align",
1
            style_vertical_align_to_u8(StyleVerticalAlign::TextBottom),
            VERTICAL_ALIGN_MASK,
        );
1
        assert_fits(
1
            "border_collapse",
1
            border_collapse_to_u8(StyleBorderCollapse::Collapse),
            BORDER_COLLAPSE_MASK,
        );
1
    }
    // ========================================================================
    // Empty tier1 decodes to all-initial — this is the core contract that
    // was violated by the pre-fix justify_items encoding. An empty u64 with
    // only TIER1_POPULATED_BIT set must decode every property to its CSS
    // initial value; this is how `build_compact_cache` can leave unspecified
    // properties at 0 and still produce the correct cascade result.
    // ========================================================================
    #[test]
1
    fn test_empty_tier1_decodes_to_initial_values() {
1
        let t1 = TIER1_POPULATED_BIT; // populated, but zero content
1
        assert!(tier1_is_populated(t1));
1
        assert_eq!(decode_display(t1), LayoutDisplay::Block);
1
        assert_eq!(decode_position(t1), LayoutPosition::Static);
1
        assert_eq!(decode_float(t1), LayoutFloat::None);
1
        assert_eq!(decode_overflow_x(t1), LayoutOverflow::Visible);
1
        assert_eq!(decode_overflow_y(t1), LayoutOverflow::Visible);
1
        assert_eq!(decode_box_sizing(t1), LayoutBoxSizing::ContentBox);
1
        assert_eq!(decode_flex_direction(t1), LayoutFlexDirection::Row);
1
        assert_eq!(decode_flex_wrap(t1), LayoutFlexWrap::NoWrap);
1
        assert_eq!(decode_justify_content(t1), LayoutJustifyContent::FlexStart);
1
        assert_eq!(decode_align_items(t1), LayoutAlignItems::Stretch);
1
        assert_eq!(decode_align_content(t1), LayoutAlignContent::Stretch);
1
        assert_eq!(decode_writing_mode(t1), LayoutWritingMode::HorizontalTb);
1
        assert_eq!(decode_clear(t1), LayoutClear::None);
1
        assert_eq!(decode_font_weight(t1), StyleFontWeight::Normal);
1
        assert_eq!(decode_font_style(t1), StyleFontStyle::Normal);
1
        assert_eq!(decode_text_align(t1), StyleTextAlign::Start);
1
        assert_eq!(decode_visibility(t1), StyleVisibility::Visible);
1
        assert_eq!(decode_white_space(t1), StyleWhiteSpace::Normal);
1
        assert_eq!(decode_direction(t1), StyleDirection::Ltr);
1
        assert_eq!(decode_vertical_align(t1), StyleVerticalAlign::Baseline);
1
        assert_eq!(decode_border_collapse(t1), StyleBorderCollapse::Separate);
1
    }
}
#[cfg(test)]
#[allow(
    clippy::float_cmp,
    clippy::unreadable_literal,
    clippy::too_many_lines,
    clippy::cast_precision_loss
)]
mod autotest_generated {
    use super::*;
    use crate::props::basic::length::PercentageValue;
    // =========================================================================
    // Shared fixtures
    // =========================================================================
    const ALL_DISPLAY: [LayoutDisplay; 23] = [
        LayoutDisplay::Block,
        LayoutDisplay::Inline,
        LayoutDisplay::InlineBlock,
        LayoutDisplay::Flex,
        LayoutDisplay::None,
        LayoutDisplay::InlineFlex,
        LayoutDisplay::Table,
        LayoutDisplay::InlineTable,
        LayoutDisplay::TableRowGroup,
        LayoutDisplay::TableHeaderGroup,
        LayoutDisplay::TableFooterGroup,
        LayoutDisplay::TableRow,
        LayoutDisplay::TableColumnGroup,
        LayoutDisplay::TableColumn,
        LayoutDisplay::TableCell,
        LayoutDisplay::TableCaption,
        LayoutDisplay::FlowRoot,
        LayoutDisplay::ListItem,
        LayoutDisplay::RunIn,
        LayoutDisplay::Marker,
        LayoutDisplay::Grid,
        LayoutDisplay::InlineGrid,
        LayoutDisplay::Contents,
    ];
    const ALL_BORDER_STYLE: [BorderStyle; 10] = [
        BorderStyle::None,
        BorderStyle::Solid,
        BorderStyle::Double,
        BorderStyle::Dotted,
        BorderStyle::Dashed,
        BorderStyle::Hidden,
        BorderStyle::Groove,
        BorderStyle::Ridge,
        BorderStyle::Inset,
        BorderStyle::Outset,
    ];
    const ALL_SIZE_METRIC: [SizeMetric; 12] = [
        SizeMetric::Px,
        SizeMetric::Pt,
        SizeMetric::Em,
        SizeMetric::Rem,
        SizeMetric::In,
        SizeMetric::Cm,
        SizeMetric::Mm,
        SizeMetric::Percent,
        SizeMetric::Vw,
        SizeMetric::Vh,
        SizeMetric::Vmin,
        SizeMetric::Vmax,
    ];
    /// Build a `PixelValue` straight from the raw fixed-point isize (×1000),
    /// bypassing the f32 constructor so boundary rows are exact.
    fn pv_raw(metric: SizeMetric, raw: isize) -> PixelValue {
        PixelValue {
            metric,
            number: FloatValue { number: raw },
        }
    }
    /// All 21 tier-1 enum properties as one struct, so a decode can be checked
    /// field-by-field against exactly what was encoded.
    #[derive(Debug, Copy, Clone, PartialEq, Eq)]
    struct T1 {
        display: LayoutDisplay,
        position: LayoutPosition,
        float: LayoutFloat,
        overflow_x: LayoutOverflow,
        overflow_y: LayoutOverflow,
        box_sizing: LayoutBoxSizing,
        flex_direction: LayoutFlexDirection,
        flex_wrap: LayoutFlexWrap,
        justify_content: LayoutJustifyContent,
        align_items: LayoutAlignItems,
        align_content: LayoutAlignContent,
        writing_mode: LayoutWritingMode,
        clear: LayoutClear,
        font_weight: StyleFontWeight,
        font_style: StyleFontStyle,
        text_align: StyleTextAlign,
        visibility: StyleVisibility,
        white_space: StyleWhiteSpace,
        direction: StyleDirection,
        vertical_align: StyleVerticalAlign,
        border_collapse: StyleBorderCollapse,
    }
    impl T1 {
        /// Every field at its CSS initial value (the u8-0 slot).
        const fn initial() -> Self {
            Self {
                display: LayoutDisplay::Block,
                position: LayoutPosition::Static,
                float: LayoutFloat::None,
                overflow_x: LayoutOverflow::Visible,
                overflow_y: LayoutOverflow::Visible,
                box_sizing: LayoutBoxSizing::ContentBox,
                flex_direction: LayoutFlexDirection::Row,
                flex_wrap: LayoutFlexWrap::NoWrap,
                justify_content: LayoutJustifyContent::FlexStart,
                align_items: LayoutAlignItems::Stretch,
                align_content: LayoutAlignContent::Stretch,
                writing_mode: LayoutWritingMode::HorizontalTb,
                clear: LayoutClear::None,
                font_weight: StyleFontWeight::Normal,
                font_style: StyleFontStyle::Normal,
                text_align: StyleTextAlign::Start,
                visibility: StyleVisibility::Visible,
                white_space: StyleWhiteSpace::Normal,
                direction: StyleDirection::Ltr,
                vertical_align: StyleVerticalAlign::Baseline,
                border_collapse: StyleBorderCollapse::Separate,
            }
        }
        /// Every field at its highest-numbered variant — the worst case for a
        /// mask that is one bit too narrow.
        const fn saturated() -> Self {
            Self {
                display: LayoutDisplay::Contents,
                position: LayoutPosition::Sticky,
                float: LayoutFloat::Right,
                overflow_x: LayoutOverflow::Clip,
                overflow_y: LayoutOverflow::Clip,
                box_sizing: LayoutBoxSizing::BorderBox,
                flex_direction: LayoutFlexDirection::ColumnReverse,
                flex_wrap: LayoutFlexWrap::WrapReverse,
                justify_content: LayoutJustifyContent::SpaceEvenly,
                align_items: LayoutAlignItems::Baseline,
                align_content: LayoutAlignContent::SpaceAround,
                writing_mode: LayoutWritingMode::VerticalLr,
                clear: LayoutClear::Both,
                font_weight: StyleFontWeight::Bolder,
                font_style: StyleFontStyle::Oblique,
                text_align: StyleTextAlign::End,
                visibility: StyleVisibility::Collapse,
                white_space: StyleWhiteSpace::BreakSpaces,
                direction: StyleDirection::Rtl,
                vertical_align: StyleVerticalAlign::TextBottom,
                border_collapse: StyleBorderCollapse::Collapse,
            }
        }
        fn encode(self) -> u64 {
            encode_tier1(
                self.display,
                self.position,
                self.float,
                self.overflow_x,
                self.overflow_y,
                self.box_sizing,
                self.flex_direction,
                self.flex_wrap,
                self.justify_content,
                self.align_items,
                self.align_content,
                self.writing_mode,
                self.clear,
                self.font_weight,
                self.font_style,
                self.text_align,
                self.visibility,
                self.white_space,
                self.direction,
                self.vertical_align,
                self.border_collapse,
            )
        }
        fn decode(t1: u64) -> Self {
            Self {
                display: decode_display(t1),
                position: decode_position(t1),
                float: decode_float(t1),
                overflow_x: decode_overflow_x(t1),
                overflow_y: decode_overflow_y(t1),
                box_sizing: decode_box_sizing(t1),
                flex_direction: decode_flex_direction(t1),
                flex_wrap: decode_flex_wrap(t1),
                justify_content: decode_justify_content(t1),
                align_items: decode_align_items(t1),
                align_content: decode_align_content(t1),
                writing_mode: decode_writing_mode(t1),
                clear: decode_clear(t1),
                font_weight: decode_font_weight(t1),
                font_style: decode_font_style(t1),
                text_align: decode_text_align(t1),
                visibility: decode_visibility(t1),
                white_space: decode_white_space(t1),
                direction: decode_direction(t1),
                vertical_align: decode_vertical_align(t1),
                border_collapse: decode_border_collapse(t1),
            }
        }
    }
    // =========================================================================
    // u8 decoders — every byte outside the variant range must fall back to the
    // CSS initial value (the u8-0 slot), never panic, never alias a real variant
    // =========================================================================
    /// `first_invalid` = the first u8 that has no variant. Every byte from there
    /// to `u8::MAX` must decode to `initial`.
    fn assert_u8_fallback<T: PartialEq + core::fmt::Debug + Copy>(
        name: &str,
        decode: fn(u8) -> T,
        first_invalid: u8,
        initial: T,
    ) {
        for v in first_invalid..=u8::MAX {
            assert_eq!(
                decode(v),
                initial,
                "{name}: out-of-range byte {v} must fall back to the CSS initial value",
            );
        }
    }
    #[test]
    fn out_of_range_u8_falls_back_to_css_initial_for_every_enum() {
        assert_u8_fallback("display", layout_display_from_u8, 23, LayoutDisplay::Block);
        assert_u8_fallback(
            "position",
            layout_position_from_u8,
            5,
            LayoutPosition::Static,
        );
        assert_u8_fallback("float", layout_float_from_u8, 3, LayoutFloat::None);
        assert_u8_fallback(
            "overflow",
            layout_overflow_from_u8,
            5,
            LayoutOverflow::Visible,
        );
        assert_u8_fallback(
            "box_sizing",
            layout_box_sizing_from_u8,
            2,
            LayoutBoxSizing::ContentBox,
        );
        assert_u8_fallback(
            "flex_direction",
            layout_flex_direction_from_u8,
            4,
            LayoutFlexDirection::Row,
        );
        assert_u8_fallback(
            "flex_wrap",
            layout_flex_wrap_from_u8,
            3,
            LayoutFlexWrap::NoWrap,
        );
        assert_u8_fallback(
            "justify_content",
            layout_justify_content_from_u8,
            8,
            LayoutJustifyContent::FlexStart,
        );
        assert_u8_fallback(
            "align_items",
            layout_align_items_from_u8,
            5,
            LayoutAlignItems::Stretch,
        );
        assert_u8_fallback(
            "align_self",
            layout_align_self_from_u8,
            6,
            LayoutAlignSelf::Auto,
        );
        assert_u8_fallback(
            "justify_self",
            layout_justify_self_from_u8,
            5,
            LayoutJustifySelf::Auto,
        );
        assert_u8_fallback(
            "justify_items",
            layout_justify_items_from_u8,
            4,
            LayoutJustifyItems::Stretch,
        );
        assert_u8_fallback(
            "grid_auto_flow",
            layout_grid_auto_flow_from_u8,
            4,
            LayoutGridAutoFlow::Row,
        );
        assert_u8_fallback(
            "align_content",
            layout_align_content_from_u8,
            6,
            LayoutAlignContent::Stretch,
        );
        assert_u8_fallback(
            "writing_mode",
            layout_writing_mode_from_u8,
            3,
            LayoutWritingMode::HorizontalTb,
        );
        assert_u8_fallback("clear", layout_clear_from_u8, 4, LayoutClear::None);
        assert_u8_fallback(
            "font_weight",
            style_font_weight_from_u8,
            11,
            StyleFontWeight::Normal,
        );
        assert_u8_fallback(
            "font_style",
            style_font_style_from_u8,
            3,
            StyleFontStyle::Normal,
        );
        assert_u8_fallback(
            "text_align",
            style_text_align_from_u8,
            6,
            StyleTextAlign::Start,
        );
        assert_u8_fallback(
            "visibility",
            style_visibility_from_u8,
            3,
            StyleVisibility::Visible,
        );
        assert_u8_fallback(
            "white_space",
            style_white_space_from_u8,
            6,
            StyleWhiteSpace::Normal,
        );
        assert_u8_fallback("direction", style_direction_from_u8, 2, StyleDirection::Ltr);
        assert_u8_fallback(
            "vertical_align",
            style_vertical_align_from_u8,
            8,
            StyleVerticalAlign::Baseline,
        );
        assert_u8_fallback(
            "border_collapse",
            border_collapse_from_u8,
            2,
            StyleBorderCollapse::Separate,
        );
        assert_u8_fallback("border_style", border_style_from_u8, 10, BorderStyle::None);
        assert_u8_fallback("size_metric", size_metric_from_u8, 12, SizeMetric::Px);
    }
    #[test]
    fn display_documented_sentinel_31_decodes_to_block() {
        // The module doc promises 0x1F is the "look it up in the slow path"
        // sentinel and that decoding it yields the default rather than a
        // garbage variant. 31 is also DISPLAY_MASK, so a saturated tier1 u64
        // lands exactly here.
        assert_eq!(layout_display_from_u8(31), LayoutDisplay::Block);
        assert_eq!(layout_display_from_u8(u8::MAX), LayoutDisplay::Block);
    }
    #[test]
    fn every_variant_of_every_enum_fits_its_tier1_mask() {
        // The existing suite checks only the highest variant per enum. If a new
        // variant is inserted in the middle with a hand-written u8 above the
        // mask width, that check still passes while the encoding silently
        // corrupts the neighbouring bit run. Check the whole variant set.
        fn fits(name: &str, val: u8, mask: u64) {
            assert!(
                u64::from(val) & !mask == 0,
                "{name}: encoded u8 {val} does not fit mask {mask:#b}",
            );
        }
        for v in ALL_DISPLAY {
            fits("display", layout_display_to_u8(v), DISPLAY_MASK);
        }
        for v in [
            LayoutPosition::Static,
            LayoutPosition::Relative,
            LayoutPosition::Absolute,
            LayoutPosition::Fixed,
            LayoutPosition::Sticky,
        ] {
            fits("position", layout_position_to_u8(v), POSITION_MASK);
        }
        for v in [LayoutFloat::None, LayoutFloat::Left, LayoutFloat::Right] {
            fits("float", layout_float_to_u8(v), FLOAT_MASK);
        }
        for v in [
            LayoutOverflow::Visible,
            LayoutOverflow::Hidden,
            LayoutOverflow::Scroll,
            LayoutOverflow::Auto,
            LayoutOverflow::Clip,
        ] {
            fits("overflow", layout_overflow_to_u8(v), OVERFLOW_MASK);
        }
        for v in [LayoutBoxSizing::ContentBox, LayoutBoxSizing::BorderBox] {
            fits("box_sizing", layout_box_sizing_to_u8(v), BOX_SIZING_MASK);
        }
        for v in [
            LayoutFlexDirection::Row,
            LayoutFlexDirection::RowReverse,
            LayoutFlexDirection::Column,
            LayoutFlexDirection::ColumnReverse,
        ] {
            fits(
                "flex_direction",
                layout_flex_direction_to_u8(v),
                FLEX_DIR_MASK,
            );
        }
        for v in [
            LayoutFlexWrap::NoWrap,
            LayoutFlexWrap::Wrap,
            LayoutFlexWrap::WrapReverse,
        ] {
            fits("flex_wrap", layout_flex_wrap_to_u8(v), FLEX_WRAP_MASK);
        }
        for v in [
            LayoutJustifyContent::FlexStart,
            LayoutJustifyContent::FlexEnd,
            LayoutJustifyContent::Start,
            LayoutJustifyContent::End,
            LayoutJustifyContent::Center,
            LayoutJustifyContent::SpaceBetween,
            LayoutJustifyContent::SpaceAround,
            LayoutJustifyContent::SpaceEvenly,
        ] {
            fits(
                "justify_content",
                layout_justify_content_to_u8(v),
                JUSTIFY_MASK,
            );
        }
        for v in [
            LayoutAlignItems::Stretch,
            LayoutAlignItems::Center,
            LayoutAlignItems::Start,
            LayoutAlignItems::End,
            LayoutAlignItems::Baseline,
        ] {
            fits("align_items", layout_align_items_to_u8(v), ALIGN_MASK);
        }
        for v in [
            LayoutAlignSelf::Auto,
            LayoutAlignSelf::Stretch,
            LayoutAlignSelf::Center,
            LayoutAlignSelf::Start,
            LayoutAlignSelf::End,
            LayoutAlignSelf::Baseline,
        ] {
            fits("align_self", layout_align_self_to_u8(v), ALIGN_SELF_MASK);
        }
        for v in [
            LayoutJustifySelf::Auto,
            LayoutJustifySelf::Start,
            LayoutJustifySelf::End,
            LayoutJustifySelf::Center,
            LayoutJustifySelf::Stretch,
        ] {
            fits(
                "justify_self",
                layout_justify_self_to_u8(v),
                JUSTIFY_SELF_MASK,
            );
        }
        for v in [
            LayoutJustifyItems::Stretch,
            LayoutJustifyItems::Start,
            LayoutJustifyItems::End,
            LayoutJustifyItems::Center,
        ] {
            fits(
                "justify_items",
                layout_justify_items_to_u8(v),
                JUSTIFY_ITEMS_MASK,
            );
        }
        for v in [
            LayoutGridAutoFlow::Row,
            LayoutGridAutoFlow::Column,
            LayoutGridAutoFlow::RowDense,
            LayoutGridAutoFlow::ColumnDense,
        ] {
            fits(
                "grid_auto_flow",
                layout_grid_auto_flow_to_u8(v),
                GRID_AUTO_FLOW_MASK,
            );
        }
        for v in [
            LayoutAlignContent::Stretch,
            LayoutAlignContent::Center,
            LayoutAlignContent::Start,
            LayoutAlignContent::End,
            LayoutAlignContent::SpaceBetween,
            LayoutAlignContent::SpaceAround,
        ] {
            fits("align_content", layout_align_content_to_u8(v), ALIGN_MASK);
        }
        for v in [
            LayoutWritingMode::HorizontalTb,
            LayoutWritingMode::VerticalRl,
            LayoutWritingMode::VerticalLr,
        ] {
            fits(
                "writing_mode",
                layout_writing_mode_to_u8(v),
                WRITING_MODE_MASK,
            );
        }
        for v in [
            LayoutClear::None,
            LayoutClear::Left,
            LayoutClear::Right,
            LayoutClear::Both,
        ] {
            fits("clear", layout_clear_to_u8(v), CLEAR_MASK);
        }
        for v in [
            StyleFontWeight::Normal,
            StyleFontWeight::W100,
            StyleFontWeight::W200,
            StyleFontWeight::W300,
            StyleFontWeight::W500,
            StyleFontWeight::W600,
            StyleFontWeight::Bold,
            StyleFontWeight::W800,
            StyleFontWeight::W900,
            StyleFontWeight::Lighter,
            StyleFontWeight::Bolder,
        ] {
            fits("font_weight", style_font_weight_to_u8(v), FONT_WEIGHT_MASK);
        }
        for v in [
            StyleFontStyle::Normal,
            StyleFontStyle::Italic,
            StyleFontStyle::Oblique,
        ] {
            fits("font_style", style_font_style_to_u8(v), FONT_STYLE_MASK);
        }
        for v in [
            StyleTextAlign::Left,
            StyleTextAlign::Center,
            StyleTextAlign::Right,
            StyleTextAlign::Justify,
            StyleTextAlign::Start,
            StyleTextAlign::End,
        ] {
            fits("text_align", style_text_align_to_u8(v), TEXT_ALIGN_MASK);
        }
        for v in [
            StyleVisibility::Visible,
            StyleVisibility::Hidden,
            StyleVisibility::Collapse,
        ] {
            fits("visibility", style_visibility_to_u8(v), VISIBILITY_MASK);
        }
        for v in [
            StyleWhiteSpace::Normal,
            StyleWhiteSpace::Pre,
            StyleWhiteSpace::Nowrap,
            StyleWhiteSpace::PreWrap,
            StyleWhiteSpace::PreLine,
            StyleWhiteSpace::BreakSpaces,
        ] {
            fits("white_space", style_white_space_to_u8(v), WHITE_SPACE_MASK);
        }
        for v in [StyleDirection::Ltr, StyleDirection::Rtl] {
            fits("direction", style_direction_to_u8(v), DIRECTION_MASK);
        }
        for v in [
            StyleVerticalAlign::Baseline,
            StyleVerticalAlign::Top,
            StyleVerticalAlign::Middle,
            StyleVerticalAlign::Bottom,
            StyleVerticalAlign::Sub,
            StyleVerticalAlign::Superscript,
            StyleVerticalAlign::TextTop,
            StyleVerticalAlign::TextBottom,
            StyleVerticalAlign::Percentage(PercentageValue::new(50.0)),
            StyleVerticalAlign::Length(PixelValue::px(4.0)),
        ] {
            fits(
                "vertical_align",
                style_vertical_align_to_u8(v),
                VERTICAL_ALIGN_MASK,
            );
        }
        for v in [StyleBorderCollapse::Separate, StyleBorderCollapse::Collapse] {
            fits(
                "border_collapse",
                border_collapse_to_u8(v),
                BORDER_COLLAPSE_MASK,
            );
        }
        // border-style gets a 4-bit nibble inside the packed u16, not a tier1 mask.
        for v in ALL_BORDER_STYLE {
            fits("border_style", border_style_to_u8(v), 0x0F);
        }
        // SizeMetric gets the low 4 bits of the pixel-value u32.
        for v in ALL_SIZE_METRIC {
            fits("size_metric", size_metric_to_u8(v), 0x0F);
        }
    }
    #[test]
    fn vertical_align_percentage_and_length_collapse_to_baseline() {
        // Documented lossy fallback: the 3-bit tier1 slot cannot carry a
        // length/percentage payload, so these must encode as 0 (Baseline) and
        // the caller is expected to take the slow path. What must NOT happen is
        // an out-of-range u8 leaking into the border-collapse bit next door.
        for v in [
            StyleVerticalAlign::Percentage(PercentageValue::new(0.0)),
            StyleVerticalAlign::Percentage(PercentageValue::new(-100.0)),
            StyleVerticalAlign::Percentage(PercentageValue::new(1e9)),
            StyleVerticalAlign::Length(PixelValue::px(0.0)),
            StyleVerticalAlign::Length(PixelValue::px(-1e9)),
        ] {
            assert_eq!(style_vertical_align_to_u8(v), 0);
            assert_eq!(
                style_vertical_align_from_u8(style_vertical_align_to_u8(v)),
                StyleVerticalAlign::Baseline,
            );
        }
        // …and the collapse must not disturb the neighbouring border-collapse bit.
        let mut t = T1::initial();
        t.vertical_align = StyleVerticalAlign::Percentage(PercentageValue::new(150.0));
        t.border_collapse = StyleBorderCollapse::Collapse;
        let encoded = t.encode();
        assert_eq!(decode_vertical_align(encoded), StyleVerticalAlign::Baseline);
        assert_eq!(
            decode_border_collapse(encoded),
            StyleBorderCollapse::Collapse
        );
    }
    // =========================================================================
    // Tier1 u64 packing — field isolation, saturation, arbitrary input
    // =========================================================================
    #[test]
    fn tier1_each_field_at_max_does_not_leak_into_any_other_field() {
        // One field at its highest variant, all others at CSS initial. If a
        // shift/mask pair is wrong, the extra bits land in a neighbour and that
        // neighbour decodes to something other than its initial value.
        let sat = T1::saturated();
        let mut cases: Vec<(&str, T1)> = Vec::new();
        macro_rules! case {
            ($field:ident) => {{
                let mut t = T1::initial();
                t.$field = sat.$field;
                cases.push((stringify!($field), t));
            }};
        }
        case!(display);
        case!(position);
        case!(float);
        case!(overflow_x);
        case!(overflow_y);
        case!(box_sizing);
        case!(flex_direction);
        case!(flex_wrap);
        case!(justify_content);
        case!(align_items);
        case!(align_content);
        case!(writing_mode);
        case!(clear);
        case!(font_weight);
        case!(font_style);
        case!(text_align);
        case!(visibility);
        case!(white_space);
        case!(direction);
        case!(vertical_align);
        case!(border_collapse);
        assert_eq!(cases.len(), 21, "every tier1 field must be covered");
        for (name, expected) in cases {
            let decoded = T1::decode(expected.encode());
            assert_eq!(
                decoded, expected,
                "{name} at its max variant leaked into another tier1 field",
            );
        }
    }
    #[test]
    fn tier1_all_fields_saturated_roundtrips() {
        let sat = T1::saturated();
        assert_eq!(T1::decode(sat.encode()), sat);
        assert!(tier1_is_populated(sat.encode()));
    }
    #[test]
    fn tier1_encode_never_touches_the_grid_bits_or_bits_above_63() {
        // encode_tier1 owns bits [52:0] plus the populated flag at bit 63.
        // Bits [62:53] belong to align-self / justify-self / grid-auto-flow /
        // justify-items, which the cache builder ORs in separately. If
        // encode_tier1 ever spills into that window it silently rewrites a grid
        // property that it never received as an argument.
        const GRID_WINDOW: u64 = 0x3FF << 53; // bits 53..=62
        for t in [T1::initial(), T1::saturated()] {
            let encoded = t.encode();
            assert_eq!(
                encoded & GRID_WINDOW,
                0,
                "encode_tier1 wrote into the grid bit window [62:53]",
            );
            assert_eq!(encoded & TIER1_POPULATED_BIT, TIER1_POPULATED_BIT);
        }
        // The grid fields must survive being ORed on top of a saturated tier1.
        let base = T1::saturated().encode();
        let with_grid = base
            | ((u64::from(layout_align_self_to_u8(LayoutAlignSelf::Baseline))) << ALIGN_SELF_SHIFT)
            | ((u64::from(layout_justify_self_to_u8(LayoutJustifySelf::Stretch)))
                << JUSTIFY_SELF_SHIFT)
            | ((u64::from(layout_grid_auto_flow_to_u8(LayoutGridAutoFlow::ColumnDense)))
                << GRID_AUTO_FLOW_SHIFT)
            | ((u64::from(layout_justify_items_to_u8(LayoutJustifyItems::Center)))
                << JUSTIFY_ITEMS_SHIFT);
        assert_eq!(T1::decode(with_grid), T1::saturated());
        assert_eq!(
            layout_align_self_from_u8(((with_grid >> ALIGN_SELF_SHIFT) & ALIGN_SELF_MASK) as u8),
            LayoutAlignSelf::Baseline,
        );
        assert_eq!(
            layout_justify_self_from_u8(
                ((with_grid >> JUSTIFY_SELF_SHIFT) & JUSTIFY_SELF_MASK) as u8
            ),
            LayoutJustifySelf::Stretch,
        );
        assert_eq!(
            layout_grid_auto_flow_from_u8(
                ((with_grid >> GRID_AUTO_FLOW_SHIFT) & GRID_AUTO_FLOW_MASK) as u8
            ),
            LayoutGridAutoFlow::ColumnDense,
        );
        assert_eq!(
            layout_justify_items_from_u8(
                ((with_grid >> JUSTIFY_ITEMS_SHIFT) & JUSTIFY_ITEMS_MASK) as u8
            ),
            LayoutJustifyItems::Center,
        );
    }
    #[test]
    fn tier1_zero_is_unpopulated_but_still_decodes_to_css_initial() {
        // A `with_capacity`-allocated cache holds 0 for every node until the
        // builder fills it in. Reading such a node must be safe and yield the
        // CSS initial value, not a garbage variant.
        assert!(!tier1_is_populated(0));
        assert_eq!(T1::decode(0), T1::initial());
    }
    #[test]
    fn tier1_decodes_arbitrary_u64_deterministically_without_panic() {
        // u64::MAX means every mask reads all-ones. Each decoder must clamp to a
        // real variant (usually the initial value via the `_` arm) rather than
        // panic or produce an out-of-range discriminant.
        let m = u64::MAX;
        assert!(tier1_is_populated(m));
        assert_eq!(
            T1::decode(m),
            T1 {
                display: LayoutDisplay::Block,                      // 31 → fallback
                position: LayoutPosition::Static,                   // 7  → fallback
                float: LayoutFloat::None,                           // 3  → fallback
                overflow_x: LayoutOverflow::Visible,                // 7  → fallback
                overflow_y: LayoutOverflow::Visible,                // 7  → fallback
                box_sizing: LayoutBoxSizing::BorderBox,             // 1  → real variant
                flex_direction: LayoutFlexDirection::ColumnReverse, // 3 → real
                flex_wrap: LayoutFlexWrap::NoWrap,                  // 3  → fallback
                justify_content: LayoutJustifyContent::SpaceEvenly, // 7 → real
                align_items: LayoutAlignItems::Stretch,             // 7  → fallback
                align_content: LayoutAlignContent::Stretch,         // 7 → fallback
                writing_mode: LayoutWritingMode::HorizontalTb,      // 3 → fallback
                clear: LayoutClear::Both,                           // 3  → real variant
                font_weight: StyleFontWeight::Normal,               // 15 → fallback
                font_style: StyleFontStyle::Normal,                 // 3  → fallback
                text_align: StyleTextAlign::Start,                  // 7  → fallback
                visibility: StyleVisibility::Visible,               // 3  → fallback
                white_space: StyleWhiteSpace::Normal,               // 7  → fallback
                direction: StyleDirection::Rtl,                     // 1  → real variant
                vertical_align: StyleVerticalAlign::TextBottom,     // 7 → real
                border_collapse: StyleBorderCollapse::Collapse,     // 1 → real
            },
        );
        // A deterministic sweep of adversarial bit patterns: none may panic.
        let mut x: u64 = 0x9E37_79B9_7F4A_7C15;
        for _ in 0..4096 {
            let _ = T1::decode(x);
            let _ = tier1_is_populated(x);
            x = x
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
        }
        for x in [
            0u64,
            1,
            u64::MAX,
            0xAAAA_AAAA_AAAA_AAAA,
            0x5555_5555_5555_5555,
        ] {
            let _ = T1::decode(x);
        }
    }
    // =========================================================================
    // Packed border styles (u16, four nibbles)
    // =========================================================================
    #[test]
    fn border_styles_packed_roundtrip_for_all_10000_combinations() {
        for top in ALL_BORDER_STYLE {
            for right in ALL_BORDER_STYLE {
                for bottom in ALL_BORDER_STYLE {
                    for left in ALL_BORDER_STYLE {
                        let packed = encode_border_styles_packed(top, right, bottom, left);
                        assert_eq!(decode_border_top_style(packed), top);
                        assert_eq!(decode_border_right_style(packed), right);
                        assert_eq!(decode_border_bottom_style(packed), bottom);
                        assert_eq!(decode_border_left_style(packed), left);
                    }
                }
            }
        }
    }
    #[test]
    fn border_styles_packed_nibbles_do_not_alias() {
        // Only the top nibble set — the other three must read as None (0),
        // not pick up bits from their neighbours.
        let packed = encode_border_styles_packed(
            BorderStyle::Outset, // 9 — the widest valid nibble
            BorderStyle::None,
            BorderStyle::None,
            BorderStyle::None,
        );
        assert_eq!(packed, 0x0009);
        assert_eq!(decode_border_top_style(packed), BorderStyle::Outset);
        assert_eq!(decode_border_right_style(packed), BorderStyle::None);
        assert_eq!(decode_border_bottom_style(packed), BorderStyle::None);
        assert_eq!(decode_border_left_style(packed), BorderStyle::None);
        let packed = encode_border_styles_packed(
            BorderStyle::None,
            BorderStyle::None,
            BorderStyle::None,
            BorderStyle::Outset,
        );
        assert_eq!(packed, 0x9000);
        assert_eq!(decode_border_left_style(packed), BorderStyle::Outset);
        assert_eq!(decode_border_top_style(packed), BorderStyle::None);
    }
    #[test]
    fn border_styles_packed_decodes_garbage_u16_without_panic() {
        // Nibbles 10..=15 have no variant. `0xFFFF` (an all-ones cold-tier row,
        // e.g. from a misinitialised buffer) must decode to None everywhere.
        for packed in [0u16, 0xFFFF, 0xAAAA, 0x5555, u16::MAX / 2] {
            let _ = decode_border_top_style(packed);
            let _ = decode_border_right_style(packed);
            let _ = decode_border_bottom_style(packed);
            let _ = decode_border_left_style(packed);
        }
        assert_eq!(decode_border_top_style(0xFFFF), BorderStyle::None);
        assert_eq!(decode_border_right_style(0xFFFF), BorderStyle::None);
        assert_eq!(decode_border_bottom_style(0xFFFF), BorderStyle::None);
        assert_eq!(decode_border_left_style(0xFFFF), BorderStyle::None);
        // Exhaustive: no u16 may panic any of the four decoders.
        for packed in 0..=u16::MAX {
            let _ = decode_border_top_style(packed);
            let _ = decode_border_left_style(packed);
        }
    }
    // =========================================================================
    // Colors (u32 0xRRGGBBAA)
    // =========================================================================
    #[test]
    fn color_u32_channel_order_is_rrggbbaa() {
        let c = ColorU {
            r: 0x12,
            g: 0x34,
            b: 0x56,
            a: 0x78,
        };
        assert_eq!(encode_color_u32(&c), 0x1234_5678);
        assert_eq!(decode_color_u32(0x1234_5678), Some(c));
    }
    #[test]
    fn color_u32_roundtrips_every_boundary_channel_combination() {
        for r in [0u8, 1, 127, 254, 255] {
            for g in [0u8, 1, 127, 254, 255] {
                for b in [0u8, 1, 127, 254, 255] {
                    for a in [0u8, 1, 127, 254, 255] {
                        let c = ColorU { r, g, b, a };
                        let encoded = encode_color_u32(&c);
                        if encoded == 0 {
                            // Only fully-transparent black hits the unset sentinel.
                            assert_eq!((r, g, b, a), (0, 0, 0, 0));
                            assert_eq!(decode_color_u32(encoded), None);
                        } else {
                            assert_eq!(decode_color_u32(encoded), Some(c));
                        }
                    }
                }
            }
        }
    }
    #[test]
    fn color_u32_transparent_black_is_the_documented_unset_collision() {
        // Documented limitation, pinned so it cannot regress silently:
        // rgba(0,0,0,0) is indistinguishable from "property never set".
        let transparent_black = ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
        };
        assert_eq!(encode_color_u32(&transparent_black), 0);
        assert_eq!(decode_color_u32(0), None);
        // Every other alpha-0 color must still survive the round-trip.
        let transparent_red = ColorU {
            r: 255,
            g: 0,
            b: 0,
            a: 0,
        };
        assert_eq!(encode_color_u32(&transparent_red), 0xFF00_0000);
        assert_eq!(decode_color_u32(0xFF00_0000), Some(transparent_red));
        // …including "black but only just" (alpha 1).
        let almost = ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 1,
        };
        assert_eq!(decode_color_u32(encode_color_u32(&almost)), Some(almost));
    }
    #[test]
    fn color_u32_max_decodes_to_opaque_white() {
        assert_eq!(
            decode_color_u32(u32::MAX),
            Some(ColorU {
                r: 255,
                g: 255,
                b: 255,
                a: 255
            }),
        );
    }
    // =========================================================================
    // PixelValue u32 (4-bit metric + 28-bit signed fixed-point ×1000)
    // =========================================================================
    #[test]
    fn pixel_value_u32_sentinels_all_decode_to_none_and_are_distinct() {
        let sentinels = [
            U32_SENTINEL,
            U32_AUTO,
            U32_NONE,
            U32_INHERIT,
            U32_INITIAL,
            U32_MIN_CONTENT,
            U32_MAX_CONTENT,
        ];
        for (i, a) in sentinels.iter().enumerate() {
            assert!(
                *a >= U32_SENTINEL_THRESHOLD,
                "sentinel {a:#X} sits below the threshold and would decode as a value",
            );
            assert_eq!(decode_pixel_value_u32(*a), None);
            for b in &sentinels[i + 1..] {
                assert_ne!(a, b, "two u32 sentinels share a bit pattern");
            }
        }
        // The threshold itself is the lowest reserved value.
        assert_eq!(decode_pixel_value_u32(U32_SENTINEL_THRESHOLD), None);
        // One below the threshold is still a real (negative) value.
        assert!(decode_pixel_value_u32(U32_SENTINEL_THRESHOLD - 1).is_some());
    }
    #[test]
    fn pixel_value_u32_roundtrips_at_the_28_bit_boundaries_for_every_metric() {
        // ±2^27 is the documented edge of the 28-bit signed fixed-point field.
        for metric in ALL_SIZE_METRIC {
            for raw in [0isize, 1, -1, 1000, -1000, 134_217_727, -134_217_728] {
                let pv = pv_raw(metric, raw);
                let encoded = encode_pixel_value_u32(&pv);
                // Raw -1 with a high metric nibble collides with the sentinel
                // band; that is asserted separately in the bug test below.
                if encoded >= U32_SENTINEL_THRESHOLD {
                    continue;
                }
                let decoded = decode_pixel_value_u32(encoded)
                    .unwrap_or_else(|| panic!("{metric:?} raw {raw} decoded as a sentinel"));
                assert_eq!(decoded.metric, metric, "metric nibble lost for raw {raw}");
                assert_eq!(
                    decoded.number.number(),
                    raw,
                    "{metric:?}: raw {raw} did not survive the round-trip",
                );
            }
        }
    }
    #[test]
    fn pixel_value_u32_out_of_28_bit_range_returns_sentinel() {
        for metric in ALL_SIZE_METRIC {
            for raw in [
                134_217_728isize,
                -134_217_729,
                1_000_000_000,
                -1_000_000_000,
                isize::MAX,
                isize::MIN,
            ] {
                assert_eq!(
                    encode_pixel_value_u32(&pv_raw(metric, raw)),
                    U32_SENTINEL,
                    "{metric:?}: raw {raw} is outside 28 bits and must escape to tier 3",
                );
            }
        }
    }
    #[test]
    fn pixel_value_u32_decodes_every_low_bit_pattern_without_panic() {
        // Metric nibbles 12..=15 have no SizeMetric — they must clamp to Px.
        for nibble in 12u32..16 {
            let encoded = (1u32 << 4) | nibble;
            let decoded = decode_pixel_value_u32(encoded).unwrap();
            assert_eq!(decoded.metric, SizeMetric::Px);
            assert_eq!(decoded.number.number(), 1);
        }
        // Sign extension: the top bit of the 28-bit field must arithmetic-shift.
        let neg = decode_pixel_value_u32(0x8000_0000).unwrap();
        assert_eq!(neg.metric, SizeMetric::Px);
        assert_eq!(neg.number.number(), -134_217_728);
    }
    #[test]
    fn pixel_value_u32_negative_0_001_in_vh_vmin_vmax_collides_with_sentinels() {
        // BUG (encode_pixel_value_u32 / decode_pixel_value_u32):
        //
        // raw == -1 (i.e. -0.001 of a unit) sign-extends to 0xFFFF_FFFF, and
        // `<< 4` leaves 0xFFFF_FFF0. ORing in a metric nibble >= 9 pushes the
        // word into the reserved sentinel band (>= 0xFFFF_FFF9):
        //
        //   -0.001vh   → 0xFFFF_FFF9 == U32_MAX_CONTENT
        //   -0.001vmin → 0xFFFF_FFFA == U32_MIN_CONTENT
        //   -0.001vmax → 0xFFFF_FFFB == U32_INITIAL
        //
        // So a legal (if tiny) negative viewport-relative length is written into
        // the cache as `max-content` / `min-content` / `initial`, and the decoder
        // reports None (unset) instead of the value. The encoder's range check
        // guards the 28-bit magnitude but not the sentinel band it lands in.
        //
        // Fix would be to reject any encoding that lands >= U32_SENTINEL_THRESHOLD
        // and escape to tier 3 instead.
        // FIXED (as this test's own comment prescribed): a raw -1 with a high metric
        // nibble packs into the reserved sentinel band, so the encoder now ESCAPES it to
        // U32_SENTINEL (tier 3) rather than emitting a value that decodes as a wrong,
        // aliased sentinel. decode() therefore returns None ("not in the fast cache —
        // look in tier 3"), which is the safe, non-aliasing outcome.
        for metric in [SizeMetric::Vh, SizeMetric::Vmin, SizeMetric::Vmax] {
            let pv = pv_raw(metric, -1);
            let encoded = encode_pixel_value_u32(&pv);
            assert_eq!(
                encoded, U32_SENTINEL,
                "{metric:?}: raw -1 must escape to tier 3"
            );
            assert_eq!(
                decode_pixel_value_u32(encoded),
                None,
                "{metric:?}: an escaped value decodes as None, never an aliased sentinel",
            );
        }
    }
    // =========================================================================
    // Resolved px i16 (×10)
    // =========================================================================
    #[test]
    fn resolved_px_i16_nan_and_infinity_are_defined_and_do_not_panic() {
        // `f32 as i32` saturates: NaN → 0, +inf → i32::MAX, -inf → i32::MIN.
        assert_eq!(encode_resolved_px_i16(f32::NAN), 0);
        assert_eq!(encode_resolved_px_i16(-f32::NAN), 0);
        assert_eq!(encode_resolved_px_i16(f32::INFINITY), I16_SENTINEL);
        assert_eq!(encode_resolved_px_i16(f32::NEG_INFINITY), I16_SENTINEL);
        assert_eq!(encode_resolved_px_i16(f32::MAX), I16_SENTINEL);
        assert_eq!(encode_resolved_px_i16(f32::MIN), I16_SENTINEL);
        // Subnormals round to zero rather than blowing up.
        assert_eq!(encode_resolved_px_i16(f32::MIN_POSITIVE), 0);
        assert_eq!(encode_resolved_px_i16(-0.0), 0);
    }
    #[test]
    fn resolved_px_i16_saturates_exactly_at_the_documented_range() {
        // Doc: -3276.8 ..= +3276.3 px at 0.1px precision.
        assert_eq!(encode_resolved_px_i16(3276.3), 32763);
        assert_eq!(encode_resolved_px_i16(-3276.8), -32768);
        // One tick outside in either direction escapes to tier 3.
        assert_eq!(encode_resolved_px_i16(3276.4), I16_SENTINEL);
        assert_eq!(encode_resolved_px_i16(-3276.9), I16_SENTINEL);
        assert_eq!(encode_resolved_px_i16(1e9), I16_SENTINEL);
        assert_eq!(encode_resolved_px_i16(-1e9), I16_SENTINEL);
    }
    #[test]
    fn resolved_px_i16_sentinels_decode_to_none_and_are_distinct() {
        let sentinels = [I16_SENTINEL, I16_AUTO, I16_INHERIT, I16_INITIAL];
        for (i, a) in sentinels.iter().enumerate() {
            assert!(*a >= I16_SENTINEL_THRESHOLD);
            assert_eq!(decode_resolved_px_i16(*a), None);
            for b in &sentinels[i + 1..] {
                assert_ne!(a, b, "two i16 sentinels share a bit pattern");
            }
        }
        assert_eq!(decode_resolved_px_i16(I16_SENTINEL_THRESHOLD), None);
        assert_eq!(
            decode_resolved_px_i16(I16_SENTINEL_THRESHOLD - 1),
            Some(3276.3)
        );
    }
    #[test]
    fn resolved_px_i16_every_non_sentinel_value_roundtrips() {
        // Exhaustive over the whole non-sentinel i16 domain: decode → encode must
        // be the identity, or a value written by one frame reads back shifted on
        // the next.
        for v in i16::MIN..I16_SENTINEL_THRESHOLD {
            let px = decode_resolved_px_i16(v)
                .unwrap_or_else(|| panic!("{v} is below the threshold but decoded as a sentinel"));
            assert_eq!(
                encode_resolved_px_i16(px),
                v,
                "i16 {v} decoded to {px} px which re-encodes to a different i16",
            );
        }
    }
    // =========================================================================
    // Flex u16 (×100)
    // =========================================================================
    #[test]
    fn flex_u16_nan_infinity_and_negatives_are_defined_and_do_not_panic() {
        assert_eq!(encode_flex_u16(f32::NAN), 0);
        assert_eq!(encode_flex_u16(f32::INFINITY), U16_SENTINEL);
        assert_eq!(encode_flex_u16(f32::NEG_INFINITY), U16_SENTINEL);
        assert_eq!(encode_flex_u16(f32::MAX), U16_SENTINEL);
        // flex-grow/shrink are non-negative; a negative escapes to tier 3.
        assert_eq!(encode_flex_u16(-1.0), U16_SENTINEL);
        assert_eq!(encode_flex_u16(-0.01), U16_SENTINEL);
        // …but -0.0 and values that round to zero clamp to 0, not to a sentinel.
        assert_eq!(encode_flex_u16(-0.0), 0);
        assert_eq!(encode_flex_u16(0.0), 0);
    }
    #[test]
    fn flex_u16_saturates_exactly_at_the_documented_range() {
        // Doc: 0.00 ..= 655.27 at 0.01 precision.
        assert_eq!(encode_flex_u16(655.27), 65527);
        assert_eq!(decode_flex_u16(65527), Some(655.27));
        // 65528 is representable but 65529 is the threshold.
        assert_eq!(encode_flex_u16(655.28), 65528);
        assert_eq!(encode_flex_u16(655.29), U16_SENTINEL);
        assert_eq!(encode_flex_u16(1e9), U16_SENTINEL);
    }
    #[test]
    fn flex_u16_sentinel_band_decodes_to_none() {
        for v in U16_SENTINEL_THRESHOLD..=u16::MAX {
            assert_eq!(
                decode_flex_u16(v),
                None,
                "u16 {v} is reserved and must decode as None"
            );
        }
        assert_eq!(U16_SENTINEL, u16::MAX);
        assert!(decode_flex_u16(U16_SENTINEL_THRESHOLD - 1).is_some());
    }
    #[test]
    fn flex_u16_every_non_sentinel_value_roundtrips() {
        for v in 0..U16_SENTINEL_THRESHOLD {
            let f = decode_flex_u16(v).unwrap_or_else(|| panic!("{v} decoded as a sentinel"));
            assert_eq!(
                encode_flex_u16(f),
                v,
                "u16 {v} → {f} → re-encoded differently"
            );
        }
    }
    // =========================================================================
    // encode_css_pixel_as_i16 — CssPropertyValue → i16 keyword sentinels
    // =========================================================================
    #[test]
    fn css_pixel_as_i16_maps_every_keyword_to_its_own_sentinel() {
        assert_eq!(encode_css_pixel_as_i16(&CssPropertyValue::Auto), I16_AUTO,);
        assert_eq!(
            encode_css_pixel_as_i16(&CssPropertyValue::Initial),
            I16_INITIAL,
        );
        assert_eq!(
            encode_css_pixel_as_i16(&CssPropertyValue::Inherit),
            I16_INHERIT,
        );
        // None / Revert / Unset have no dedicated slot → generic sentinel (slow path).
        assert_eq!(
            encode_css_pixel_as_i16(&CssPropertyValue::<PixelValue>::None),
            I16_SENTINEL,
        );
        assert_eq!(
            encode_css_pixel_as_i16(&CssPropertyValue::<PixelValue>::Revert),
            I16_SENTINEL,
        );
        assert_eq!(
            encode_css_pixel_as_i16(&CssPropertyValue::<PixelValue>::Unset),
            I16_SENTINEL,
        );
    }
    #[test]
    fn css_pixel_as_i16_only_takes_the_fast_path_for_absolute_px() {
        // Only SizeMetric::Px can be pre-resolved without layout context;
        // every relative unit must escape to the cascade.
        assert_eq!(
            encode_css_pixel_as_i16(&CssPropertyValue::Exact(PixelValue::px(12.5))),
            125,
        );
        for metric in ALL_SIZE_METRIC {
            if metric == SizeMetric::Px {
                continue;
            }
            assert_eq!(
                encode_css_pixel_as_i16(&CssPropertyValue::Exact(pv_raw(metric, 12_500))),
                I16_SENTINEL,
                "{metric:?} needs resolution context and must not be pre-resolved",
            );
        }
    }
    #[test]
    fn css_pixel_as_i16_out_of_range_px_escapes_to_the_sentinel() {
        assert_eq!(
            encode_css_pixel_as_i16(&CssPropertyValue::Exact(PixelValue::px(1e6))),
            I16_SENTINEL,
        );
        assert_eq!(
            encode_css_pixel_as_i16(&CssPropertyValue::Exact(PixelValue::px(-1e6))),
            I16_SENTINEL,
        );
        // A px value that happens to land on a keyword sentinel would be
        // misread as `auto`/`inherit`; the range check must exclude the band.
        for raw in [I16_SENTINEL, I16_AUTO, I16_INHERIT, I16_INITIAL] {
            let px = f32::from(raw) / 10.0;
            assert_eq!(
                encode_css_pixel_as_i16(&CssPropertyValue::Exact(PixelValue::px(px))),
                I16_SENTINEL,
                "{px} px must not silently encode as the keyword sentinel {raw}",
            );
        }
    }
    // =========================================================================
    // CompactLayoutCache — constructor invariants, bounds, predicates
    // =========================================================================
    #[test]
    fn empty_cache_is_the_neutral_element() {
        let c = CompactLayoutCache::empty();
        assert_eq!(c.node_count(), 0);
        assert!(c.tier1_enums.is_empty());
        assert!(c.tier2_dims.is_empty());
        assert!(c.tier2_cold.is_empty());
        assert!(c.tier2b_text.is_empty());
        assert!(c.font_dirty_nodes.is_empty());
        assert!(c.prev_font_hashes.is_empty());
        assert!(c.font_hash_to_families.is_empty());
        assert_eq!(c.dom_declared_flags, 0);
        // with_capacity(0) must produce exactly the same thing.
        assert_eq!(CompactLayoutCache::with_capacity(0), c);
    }
    #[test]
    fn with_capacity_keeps_every_tier_the_same_length() {
        for n in [0usize, 1, 2, 3, 17, 1024] {
            let c = CompactLayoutCache::with_capacity(n);
            assert_eq!(c.node_count(), n);
            assert_eq!(c.tier1_enums.len(), n);
            assert_eq!(c.tier2_dims.len(), n);
            assert_eq!(c.tier2_cold.len(), n);
            assert_eq!(c.tier2b_text.len(), n);
            assert_eq!(c.prev_font_hashes.len(), n);
            // Dirty list starts empty regardless of node count.
            assert!(c.font_dirty_nodes.is_empty());
            assert_eq!(c.dom_declared_flags, 0);
        }
    }
    #[test]
    fn freshly_allocated_node_reads_back_every_css_initial_value() {
        // `with_capacity` zeroes tier1 and default-fills tier2. A node the
        // builder never touched must still answer every getter with the CSS
        // initial value — this is what lets the builder skip unset properties.
        let c = CompactLayoutCache::with_capacity(3);
        for i in 0..3 {
            assert_eq!(T1::decode(c.tier1_enums[i]), T1::initial());
            assert_eq!(c.get_display(i), LayoutDisplay::Block);
            assert_eq!(c.get_position(i), LayoutPosition::Static);
            assert_eq!(c.get_float(i), LayoutFloat::None);
            assert_eq!(c.get_overflow_x(i), LayoutOverflow::Visible);
            assert_eq!(c.get_overflow_y(i), LayoutOverflow::Visible);
            assert_eq!(c.get_box_sizing(i), LayoutBoxSizing::ContentBox);
            assert_eq!(c.get_flex_direction(i), LayoutFlexDirection::Row);
            assert_eq!(c.get_flex_wrap(i), LayoutFlexWrap::NoWrap);
            assert_eq!(c.get_justify_content(i), LayoutJustifyContent::FlexStart);
            assert_eq!(c.get_align_items(i), LayoutAlignItems::Stretch);
            assert_eq!(c.get_align_content(i), LayoutAlignContent::Stretch);
            assert_eq!(c.get_writing_mode(i), LayoutWritingMode::HorizontalTb);
            assert_eq!(c.get_clear(i), LayoutClear::None);
            assert_eq!(c.get_font_weight(i), StyleFontWeight::Normal);
            assert_eq!(c.get_font_style(i), StyleFontStyle::Normal);
            assert_eq!(c.get_text_align(i), StyleTextAlign::Start);
            assert_eq!(c.get_visibility(i), StyleVisibility::Visible);
            assert_eq!(c.get_white_space(i), StyleWhiteSpace::Normal);
            assert_eq!(c.get_direction(i), StyleDirection::Ltr);
            assert_eq!(c.get_vertical_align(i), StyleVerticalAlign::Baseline);
            assert_eq!(c.get_border_collapse(i), StyleBorderCollapse::Separate);
            // Dimensions: auto / none, i.e. no decodable pixel value.
            assert_eq!(c.get_width_raw(i), U32_AUTO);
            assert_eq!(c.get_height_raw(i), U32_AUTO);
            assert_eq!(c.get_min_width_raw(i), U32_AUTO);
            assert_eq!(c.get_min_height_raw(i), U32_AUTO);
            assert_eq!(c.get_max_width_raw(i), U32_NONE);
            assert_eq!(c.get_max_height_raw(i), U32_NONE);
            assert_eq!(c.get_flex_basis_raw(i), U32_AUTO);
            assert_eq!(c.get_font_size_raw(i), U32_INITIAL);
            assert_eq!(decode_pixel_value_u32(c.get_width_raw(i)), None);
            assert_eq!(decode_pixel_value_u32(c.get_font_size_raw(i)), None);
            // Box model: zeros are real values (Some), offsets are auto (raw sentinel).
            assert_eq!(c.get_padding_top(i), Some(0.0));
            assert_eq!(c.get_padding_right(i), Some(0.0));
            assert_eq!(c.get_padding_bottom(i), Some(0.0));
            assert_eq!(c.get_padding_left(i), Some(0.0));
            assert_eq!(c.get_border_top_width(i), Some(0.0));
            assert_eq!(c.get_border_left_width(i), Some(0.0));
            // margin defaults to 0, NOT auto — centering must not kick in for free.
            assert_eq!(c.get_margin_top(i), Some(0.0));
            assert_eq!(c.get_margin_left(i), Some(0.0));
            assert!(!c.is_margin_top_auto(i));
            assert!(!c.is_margin_right_auto(i));
            assert!(!c.is_margin_bottom_auto(i));
            assert!(!c.is_margin_left_auto(i));
            // …but the inset properties DO default to auto.
            assert_eq!(c.get_top(i), I16_AUTO);
            assert_eq!(c.get_right(i), I16_AUTO);
            assert_eq!(c.get_bottom(i), I16_AUTO);
            assert_eq!(c.get_left(i), I16_AUTO);
            // Flex: grow 0, shrink 1 (the CSS defaults).
            assert_eq!(c.get_flex_grow(i), Some(0.0));
            assert_eq!(c.get_flex_shrink(i), Some(1.0));
            // Cold tier.
            assert_eq!(c.get_z_index(i), I16_AUTO);
            assert_eq!(c.get_border_styles_packed(i), 0);
            assert_eq!(c.get_border_top_style(i), BorderStyle::None);
            assert_eq!(c.get_border_right_style(i), BorderStyle::None);
            assert_eq!(c.get_border_bottom_style(i), BorderStyle::None);
            assert_eq!(c.get_border_left_style(i), BorderStyle::None);
            assert_eq!(c.get_border_top_color_raw(i), 0);
            assert_eq!(decode_color_u32(c.get_border_top_color_raw(i)), None);
            assert_eq!(c.get_border_top_left_radius_raw(i), I16_SENTINEL);
            assert_eq!(c.get_tab_size_raw(i), I16_SENTINEL);
            assert_eq!(c.get_border_spacing_h_raw(i), 0);
            assert_eq!(c.get_border_spacing_v_raw(i), 0);
            assert_eq!(c.get_opacity_raw(i), OPACITY_SENTINEL);
            assert_eq!(c.get_hot_flags(i), 0);
            assert_eq!(c.get_scrollbar_gutter_bits(i), SCROLLBAR_GUTTER_AUTO);
            // Every "has this rare prop" predicate must be false on a fresh node,
            // otherwise the fast path would take a cascade walk for every node.
            assert!(!c.has_transform(i));
            assert!(!c.has_transform_origin(i));
            assert!(!c.has_box_shadow(i));
            assert!(!c.has_text_decoration(i));
            assert!(!c.has_background(i));
            assert!(!c.has_clip_path(i));
            assert!(!c.has_scrollbar_css(i));
            assert!(!c.has_counter(i));
            assert!(!c.has_break(i));
            assert!(!c.has_text_orientation(i));
            assert!(!c.has_text_shadow(i));
            assert!(!c.has_backdrop_filter(i));
            assert!(!c.has_filter(i));
            assert!(!c.has_mix_blend_mode(i));
            // Text tier.
            assert_eq!(c.get_text_color_raw(i), 0);
            assert_eq!(c.get_font_family_hash(i), 0);
            assert_eq!(c.get_line_height(i), None); // "normal" → slow path
            assert_eq!(c.get_letter_spacing(i), Some(0.0));
            assert_eq!(c.get_word_spacing(i), Some(0.0));
            assert_eq!(c.get_text_indent(i), Some(0.0));
        }
    }
    #[test]
    fn hot_flag_predicates_read_only_their_own_bit() {
        let flags = [
            ("transform", HOT_FLAG_HAS_TRANSFORM),
            ("transform_origin", HOT_FLAG_HAS_TRANSFORM_ORIGIN),
            ("box_shadow", HOT_FLAG_HAS_BOX_SHADOW),
            ("text_decoration", HOT_FLAG_HAS_TEXT_DECORATION),
            ("background", HOT_FLAG_HAS_BACKGROUND),
            ("clip_path", HOT_FLAG_HAS_CLIP_PATH),
        ];
        for (name, bit) in flags {
            let mut c = CompactLayoutCache::with_capacity(1);
            c.tier2_cold[0].hot_flags = bit;
            let observed = [
                ("transform", c.has_transform(0)),
                ("transform_origin", c.has_transform_origin(0)),
                ("box_shadow", c.has_box_shadow(0)),
                ("text_decoration", c.has_text_decoration(0)),
                ("background", c.has_background(0)),
                ("clip_path", c.has_clip_path(0)),
            ];
            for (other, is_set) in observed {
                assert_eq!(
                    is_set,
                    other == name,
                    "hot_flags = {bit:#010b}: has_{other}() should be {}",
                    other == name,
                );
            }
            // The gutter field lives in bits 4-5 and must be unaffected.
            assert_eq!(c.get_scrollbar_gutter_bits(0), SCROLLBAR_GUTTER_AUTO);
        }
        // No two hot flags may share a bit, and none may overlap the gutter field.
        let mut seen = 0u8;
        for (_, bit) in flags {
            assert_eq!(seen & bit, 0, "two hot flags share bit {bit:#010b}");
            assert_eq!(
                bit & HOT_FLAG_SCROLLBAR_GUTTER_MASK,
                0,
                "hot flag {bit:#010b} overlaps the scrollbar-gutter field",
            );
            seen |= bit;
        }
    }
    #[test]
    fn scrollbar_gutter_bits_survive_a_fully_set_hot_flags_byte() {
        for gutter in [
            SCROLLBAR_GUTTER_AUTO,
            SCROLLBAR_GUTTER_STABLE,
            SCROLLBAR_GUTTER_BOTH_EDGES,
            SCROLLBAR_GUTTER_MIRROR,
        ] {
            let mut c = CompactLayoutCache::with_capacity(1);
            // Every boolean flag set *and* a gutter value: the gutter must still
            // read back cleanly out of the middle of the byte.
            c.tier2_cold[0].hot_flags = HOT_FLAG_HAS_TRANSFORM
                | HOT_FLAG_HAS_TRANSFORM_ORIGIN
                | HOT_FLAG_HAS_BOX_SHADOW
                | HOT_FLAG_HAS_TEXT_DECORATION
                | HOT_FLAG_HAS_BACKGROUND
                | HOT_FLAG_HAS_CLIP_PATH
                | (gutter << HOT_FLAG_SCROLLBAR_GUTTER_SHIFT);
            assert_eq!(c.get_scrollbar_gutter_bits(0), gutter);
            assert!(c.has_transform(0));
            assert!(c.has_clip_path(0));
        }
        // An all-ones byte reads the max gutter value, never something out of range.
        let mut c = CompactLayoutCache::with_capacity(1);
        c.tier2_cold[0].hot_flags = u8::MAX;
        assert_eq!(c.get_scrollbar_gutter_bits(0), SCROLLBAR_GUTTER_MIRROR);
        assert!(c.get_scrollbar_gutter_bits(0) <= 3);
    }
    #[test]
    fn extra_flag_predicates_read_only_their_own_bit() {
        let flags = [
            ("scrollbar_css", EXTRA_FLAG_HAS_SCROLLBAR_CSS),
            ("counter", EXTRA_FLAG_HAS_COUNTER),
            ("break", EXTRA_FLAG_HAS_BREAK),
            ("text_orientation", EXTRA_FLAG_HAS_TEXT_ORIENTATION),
            ("text_shadow", EXTRA_FLAG_HAS_TEXT_SHADOW),
            ("backdrop_filter", EXTRA_FLAG_HAS_BACKDROP_FILTER),
            ("filter", EXTRA_FLAG_HAS_FILTER),
            ("mix_blend_mode", EXTRA_FLAG_HAS_MIX_BLEND_MODE),
        ];
        // All 8 bits must be distinct and together cover the whole byte.
        let mut seen = 0u8;
        for (_, bit) in flags {
            assert_eq!(seen & bit, 0, "two extra flags share bit {bit:#010b}");
            seen |= bit;
        }
        assert_eq!(seen, u8::MAX);
        for (name, bit) in flags {
            let mut c = CompactLayoutCache::with_capacity(1);
            c.tier2_cold[0].extra_flags = bit;
            let observed = [
                ("scrollbar_css", c.has_scrollbar_css(0)),
                ("counter", c.has_counter(0)),
                ("break", c.has_break(0)),
                ("text_orientation", c.has_text_orientation(0)),
                ("text_shadow", c.has_text_shadow(0)),
                ("backdrop_filter", c.has_backdrop_filter(0)),
                ("filter", c.has_filter(0)),
                ("mix_blend_mode", c.has_mix_blend_mode(0)),
            ];
            for (other, is_set) in observed {
                assert_eq!(
                    is_set,
                    other == name,
                    "extra_flags = {bit:#010b}: has_{other}() should be {}",
                    other == name,
                );
            }
            // Setting an extra flag must not make any hot-flag predicate fire.
            assert!(!c.has_transform(0));
            assert!(!c.has_background(0));
        }
    }
    #[test]
    fn dom_declared_flags_are_distinct_and_queryable() {
        let flags = [
            DOM_HAS_SHAPE_INSIDE,
            DOM_HAS_SHAPE_OUTSIDE,
            DOM_HAS_TEXT_JUSTIFY,
            DOM_HAS_TEXT_INDENT,
            DOM_HAS_COLUMN_COUNT,
            DOM_HAS_COLUMN_GAP,
            DOM_HAS_INITIAL_LETTER,
            DOM_HAS_INITIAL_LETTER_ALIGN,
            DOM_HAS_LINE_CLAMP,
            DOM_HAS_HANGING_PUNCTUATION,
            DOM_HAS_TEXT_COMBINE_UPRIGHT,
            DOM_HAS_EXCLUSION_MARGIN,
            DOM_HAS_HYPHENATION_LANGUAGE,
            DOM_HAS_UNICODE_BIDI,
            DOM_HAS_TEXT_BOX_TRIM,
            DOM_HAS_HYPHENS,
            DOM_HAS_WORD_BREAK,
            DOM_HAS_OVERFLOW_WRAP,
            DOM_HAS_LINE_BREAK,
            DOM_HAS_TEXT_ALIGN_LAST,
            DOM_HAS_LINE_HEIGHT,
            DOM_HAS_COLUMN_WIDTH,
            DOM_HAS_SHAPE_MARGIN,
        ];
        let mut seen = 0u32;
        for f in flags {
            assert_eq!(f.count_ones(), 1, "{f:#X} is not a single-bit flag");
            assert_eq!(seen & f, 0, "two DOM_HAS_* flags share bit {f:#X}");
            seen |= f;
        }
        let mut c = CompactLayoutCache::empty();
        // Nothing declared: every query is false, including the degenerate ones.
        for f in flags {
            assert!(!c.dom_declared(f));
        }
        assert!(!c.dom_declared(0));
        assert!(!c.dom_declared(u32::MAX));
        // One flag declared: only that query is true.
        c.dom_declared_flags = DOM_HAS_LINE_HEIGHT;
        for f in flags {
            assert_eq!(c.dom_declared(f), f == DOM_HAS_LINE_HEIGHT);
        }
        assert!(
            !c.dom_declared(0),
            "an empty flag query must never report declared"
        );
        assert!(c.dom_declared(u32::MAX));
        // Everything declared: every query is true.
        c.dom_declared_flags = u32::MAX;
        for f in flags {
            assert!(c.dom_declared(f));
        }
    }
    #[test]
    fn getters_at_the_last_valid_index_do_not_panic() {
        let c = CompactLayoutCache::with_capacity(4);
        let last = c.node_count() - 1;
        let _ = c.get_display(last);
        let _ = c.get_width_raw(last);
        let _ = c.get_padding_top(last);
        let _ = c.get_z_index(last);
        let _ = c.get_border_top_style(last);
        let _ = c.get_line_height(last);
        let _ = c.has_transform(last);
    }
    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn tier1_getter_on_an_empty_cache_panics_rather_than_reading_oob() {
        let c = CompactLayoutCache::empty();
        let _ = c.get_display(0);
    }
    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn tier2_getter_past_the_end_panics_rather_than_reading_oob() {
        let c = CompactLayoutCache::with_capacity(2);
        let _ = c.get_padding_top(2);
    }
    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn cold_tier_getter_at_usize_max_panics_rather_than_wrapping() {
        // usize::MAX would wrap to a valid offset if the index were ever used in
        // pointer arithmetic without a bounds check.
        let c = CompactLayoutCache::with_capacity(1);
        let _ = c.get_z_index(usize::MAX);
    }
    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn text_tier_getter_past_the_end_panics_rather_than_reading_oob() {
        let c = CompactLayoutCache::with_capacity(1);
        let _ = c.get_font_family_hash(1);
    }
    // =========================================================================
    // Struct layout — the compact cache's whole point is its byte budget
    // =========================================================================
    #[test]
    fn compact_structs_stay_within_their_documented_byte_budget() {
        // These sizes are load-bearing: the cache is sized as N × these, and the
        // module header quotes them. A field added without updating the header
        // silently doubles the per-node memory cost.
        assert_eq!(size_of::<CompactNodeProps>(), 72);
        assert_eq!(size_of::<CompactNodePropsCold>(), 48);
        assert_eq!(size_of::<CompactTextProps>(), 24);
        // Tier 1 is exactly one u64 per node.
        assert_eq!(size_of::<u64>(), 8);
        // No padding surprises from #[repr(C)] reordering.
        assert_eq!(align_of::<CompactNodeProps>(), 4);
        assert_eq!(align_of::<CompactNodePropsCold>(), 4);
        assert_eq!(align_of::<CompactTextProps>(), 8);
    }
    /// Every `StyleCursor` variant survives the round trip through the byte it
    /// is stored in, and no two variants share a code.
    #[test]
    fn every_cursor_variant_survives_the_round_trip() {
        use crate::props::style::effects::StyleCursor::{
            Alias, AllScroll, Cell, ColResize, ContextMenu, Copy, Crosshair, Default as Def,
            EResize, EwResize, Grab, Grabbing, Help, Move, NResize, NeswResize, NsResize,
            NwseResize, Pointer, Progress, RowResize, SResize, SeResize, Text, Unset, VerticalText,
            WResize, Wait, ZoomIn, ZoomOut,
        };
        let all = [
            Def,
            Alias,
            AllScroll,
            Cell,
            ColResize,
            ContextMenu,
            Copy,
            Crosshair,
            EResize,
            EwResize,
            Grab,
            Grabbing,
            Help,
            Move,
            NResize,
            NsResize,
            NeswResize,
            NwseResize,
            Pointer,
            Progress,
            RowResize,
            SResize,
            SeResize,
            Text,
            Unset,
            VerticalText,
            WResize,
            Wait,
            ZoomIn,
            ZoomOut,
        ];
        let mut seen = alloc::collections::BTreeSet::new();
        for c in all {
            let code = cursor_to_u8(c);
            assert!(
                code <= CURSOR_CODE_MAX,
                "{c:?} encodes to {code}, past CURSOR_CODE_MAX",
            );
            assert!(
                seen.insert(code),
                "{c:?} shares code {code} with another variant"
            );
            assert_eq!(
                cursor_from_u8(code),
                c,
                "{c:?} did not survive the round trip"
            );
            // And through the byte it is actually stored in.
            let cold = CompactNodePropsCold {
                cursor: code,
                ..Default::default()
            };
            assert_eq!(cursor_from_u8(cold.cursor), c);
        }
        assert_eq!(seen.len(), all.len(), "every variant needs its own code");
    }
    /// No two tier-1 fields may share a bit.
    ///
    /// This replaces a test that checked the newest slot against the two
    /// neighbours its author had in mind. That is not enough: `cursor` was
    /// given bit 53 "above BORDER_COLLAPSE (52)", was duly checked against
    /// `BORDER_COLLAPSE` and `TIER1_POPULATED_BIT`, passed — and landed
    /// squarely on `ALIGN_SELF`, which is declared in a separate block 24
    /// lines further down. Writing a `cursor` overwrote the node's
    /// `align-self`, and since cursor is inheritable it did so for every
    /// descendant as well.
    ///
    /// A pairwise check over EVERY field cannot be fooled that way, so the
    /// list below must gain a row whenever a slot is added.
    #[test]
    fn tier1_bit_ranges_do_not_overlap() {
        let fields: &[(&str, u32, u64)] = &[
            ("display", DISPLAY_SHIFT, DISPLAY_MASK),
            ("position", POSITION_SHIFT, POSITION_MASK),
            ("float", FLOAT_SHIFT, FLOAT_MASK),
            ("overflow_x", OVERFLOW_X_SHIFT, OVERFLOW_MASK),
            ("overflow_y", OVERFLOW_Y_SHIFT, OVERFLOW_MASK),
            ("box_sizing", BOX_SIZING_SHIFT, BOX_SIZING_MASK),
            ("flex_direction", FLEX_DIRECTION_SHIFT, FLEX_DIR_MASK),
            ("flex_wrap", FLEX_WRAP_SHIFT, FLEX_WRAP_MASK),
            ("justify_content", JUSTIFY_CONTENT_SHIFT, JUSTIFY_MASK),
            ("align_items", ALIGN_ITEMS_SHIFT, ALIGN_MASK),
            ("align_content", ALIGN_CONTENT_SHIFT, ALIGN_MASK),
            ("writing_mode", WRITING_MODE_SHIFT, WRITING_MODE_MASK),
            ("clear", CLEAR_SHIFT, CLEAR_MASK),
            ("font_weight", FONT_WEIGHT_SHIFT, FONT_WEIGHT_MASK),
            ("font_style", FONT_STYLE_SHIFT, FONT_STYLE_MASK),
            ("text_align", TEXT_ALIGN_SHIFT, TEXT_ALIGN_MASK),
            ("visibility", VISIBILITY_SHIFT, VISIBILITY_MASK),
            ("white_space", WHITE_SPACE_SHIFT, WHITE_SPACE_MASK),
            ("direction", DIRECTION_SHIFT, DIRECTION_MASK),
            ("vertical_align", VERTICAL_ALIGN_SHIFT, VERTICAL_ALIGN_MASK),
            (
                "border_collapse",
                BORDER_COLLAPSE_SHIFT,
                BORDER_COLLAPSE_MASK,
            ),
            ("align_self", ALIGN_SELF_SHIFT, ALIGN_SELF_MASK),
            ("justify_self", JUSTIFY_SELF_SHIFT, JUSTIFY_SELF_MASK),
            ("grid_auto_flow", GRID_AUTO_FLOW_SHIFT, GRID_AUTO_FLOW_MASK),
            ("justify_items", JUSTIFY_ITEMS_SHIFT, JUSTIFY_ITEMS_MASK),
        ];
        for (name, shift, mask) in fields {
            let bits = mask << shift;
            assert_eq!(
                bits >> shift,
                *mask,
                "{name} at bit {shift} runs off the top of the word",
            );
            assert_eq!(
                bits & TIER1_POPULATED_BIT,
                0,
                "{name} overlaps TIER1_POPULATED_BIT",
            );
        }
        for (i, (an, ash, am)) in fields.iter().enumerate() {
            for (bn, bsh, bm) in &fields[i + 1..] {
                let a = am << ash;
                let b = bm << bsh;
                assert_eq!(
                    a & b,
                    0,
                    "{an} (bit {ash}, mask {am:#x}) and {bn} (bit {bsh}, mask {bm:#x}) share bits \
                     {:#x} — writing one silently corrupts the other",
                    a & b,
                );
            }
        }
    }
}