1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod audit_tests {
5
    use azul_css::{
6
        compact_cache::{decode_pixel_value_u32, encode_pixel_value_u32, CompactNodeProps},
7
        props::basic::pixel::PixelValue,
8
    };
9

            
10
    use super::resolve_font_size_to_px;
11
    use crate::dom::NodeId;
12

            
13
    // Happy path: an `em` font-size resolves against a valid (pre-order) parent.
14
    #[test]
15
1
    fn resolve_font_size_em_from_parent() {
16
1
        let mut dims = vec![CompactNodeProps::default(); 2];
17
1
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::px(20.0));
18
1
        dims[1].font_size = encode_pixel_value_u32(&PixelValue::em(2.0));
19
1
        resolve_font_size_to_px(&mut dims, 1, Some(NodeId::new(0)));
20
1
        let pv = decode_pixel_value_u32(dims[1].font_size).unwrap();
21
1
        assert!(
22
1
            (pv.number.get() - 40.0).abs() < 0.01,
23
            "got {}",
24
            pv.number.get()
25
        );
26
1
    }
27

            
28
    // Root `em` (no parent) uses the 16px CSS initial value.
29
    #[test]
30
1
    fn resolve_font_size_root_em_uses_default() {
31
1
        let mut dims = vec![CompactNodeProps::default()];
32
1
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::em(2.0));
33
1
        resolve_font_size_to_px(&mut dims, 0, None);
34
1
        let pv = decode_pixel_value_u32(dims[0].font_size).unwrap();
35
1
        assert!(
36
1
            (pv.number.get() - 32.0).abs() < 0.01,
37
            "got {}",
38
            pv.number.get()
39
        );
40
1
    }
41

            
42
    // A `rem` value reads the root (index 0) via the `.first()` guard without
43
    // panicking (previously indexed `tier2_dims[0]` directly).
44
    #[test]
45
1
    fn resolve_font_size_rem_reads_root() {
46
1
        let mut dims = vec![CompactNodeProps::default(); 2];
47
1
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::px(10.0)); // root
48
1
        dims[1].font_size = encode_pixel_value_u32(&PixelValue::rem(3.0)); // child rem
49
1
        resolve_font_size_to_px(&mut dims, 1, Some(NodeId::new(0)));
50
1
        let pv = decode_pixel_value_u32(dims[1].font_size).unwrap();
51
1
        assert!(
52
1
            (pv.number.get() - 30.0).abs() < 0.01,
53
            "got {}",
54
            pv.number.get()
55
        );
56
1
    }
57
}
58

            
59
#[cfg(test)]
60
#[allow(
61
    clippy::float_cmp,
62
    clippy::unreadable_literal,
63
    clippy::too_many_lines,
64
    clippy::cast_lossless
65
)]
66
mod autotest_generated {
67
    use alloc::collections::BTreeMap;
68

            
69
    use azul_css::props::{
70
        basic::{
71
            color::ColorU,
72
            font::{StyleFontFamily, StyleFontFamilyVec},
73
            length::{FloatValue, PercentageValue},
74
            pixel::PixelValue,
75
        },
76
        layout::{
77
            dimensions::LayoutMinWidth,
78
            display::LayoutDisplay,
79
            flex::{LayoutFlexGrow, LayoutFlexShrink},
80
            grid::{GridLine, GridPlacement, LayoutGap, NamedGridLine},
81
            overflow::StyleScrollbarGutter,
82
            position::LayoutPosition,
83
            spacing::{LayoutMarginTop, LayoutPaddingTop},
84
            table::StyleBorderCollapse,
85
        },
86
        style::{
87
            border::{BorderStyle, StyleBorderTopStyle},
88
            effects::StyleOpacity,
89
            text::{StyleLineHeight, StyleTextColor, StyleTextDecoration, StyleTextIndent},
90
        },
91
    };
92

            
93
    use super::*;
94
    use crate::{dom::NodeType, styled_dom::NodeHierarchyItem};
95

            
96
    // -------------------------------------------------------------------------
97
    // Fixtures
98
    // -------------------------------------------------------------------------
99

            
100
    /// The four compact output slots + the font reverse-map, as one value, so a
101
    /// test can snapshot "everything the writer could have touched".
102
    struct Sink {
103
        tier1: u64,
104
        dims: CompactNodeProps,
105
        cold: CompactNodePropsCold,
106
        text: CompactTextProps,
107
        fonts: BTreeMap<u64, StyleFontFamilyVec>,
108
    }
109

            
110
    impl Sink {
111
        fn new() -> Self {
112
            Self {
113
                tier1: 0,
114
                dims: CompactNodeProps::default(),
115
                cold: CompactNodePropsCold::default(),
116
                text: CompactTextProps::default(),
117
                fonts: BTreeMap::new(),
118
            }
119
        }
120

            
121
        fn apply(&mut self, prop: &CssProperty) {
122
            apply_css_property_to_compact(
123
                prop,
124
                &mut self.tier1,
125
                &mut self.dims,
126
                &mut self.cold,
127
                &mut self.text,
128
                &mut self.fonts,
129
            );
130
        }
131

            
132
        fn ua(&mut self, node_type: &NodeType) {
133
            apply_ua_css_to_compact(
134
                &crate::dom::NodeData::create_node(node_type.clone()),
135
                false,
136
                None,
137
                &mut self.tier1,
138
                &mut self.dims,
139
                &mut self.cold,
140
                &mut self.text,
141
                &mut self.fonts,
142
            );
143
        }
144

            
145
        fn snapshot(
146
            &self,
147
        ) -> (
148
            u64,
149
            CompactNodeProps,
150
            CompactNodePropsCold,
151
            CompactTextProps,
152
        ) {
153
            (self.tier1, self.dims, self.cold, self.text)
154
        }
155
    }
156

            
157
    fn div_nodes(n: usize) -> Vec<NodeData> {
158
        (0..n)
159
            .map(|_| NodeData::create_node(NodeType::Div))
160
            .collect()
161
    }
162

            
163
    /// Pre-order chain: node 0 is the root, node `i` is the child of node `i-1`.
164
    /// `NodeHierarchyItem` uses 1-based encoding (0 = None, n = `NodeId(n-1)`).
165
    fn linear_hierarchy(n: usize) -> Vec<NodeHierarchyItem> {
166
        (0..n)
167
            .map(|i| NodeHierarchyItem {
168
                parent: i, // i == 0 -> None; i > 0 -> NodeId(i-1)
169
                previous_sibling: 0,
170
                next_sibling: 0,
171
                last_child: if i + 1 < n { i + 2 } else { 0 },
172
            })
173
            .collect()
174
    }
175

            
176
    fn padding(px: f32) -> CssPropertyValue<LayoutPaddingTop> {
177
        CssPropertyValue::Exact(LayoutPaddingTop {
178
            inner: PixelValue::px(px),
179
        })
180
    }
181

            
182
    // -------------------------------------------------------------------------
183
    // encode_grid_line
184
    // -------------------------------------------------------------------------
185

            
186
    #[test]
187
    fn grid_line_auto_and_named_map_to_their_sentinels() {
188
        assert_eq!(encode_grid_line(&GridLine::Auto), I16_AUTO);
189
        let named = GridLine::Named(NamedGridLine {
190
            grid_line_name: "sidebar".into(),
191
            span_count: 0,
192
        });
193
        assert_eq!(encode_grid_line(&named), I16_SENTINEL);
194
    }
195

            
196
    #[test]
197
    fn grid_line_number_boundaries_saturate_instead_of_truncating() {
198
        assert_eq!(encode_grid_line(&GridLine::Line(0)), 0);
199
        assert_eq!(encode_grid_line(&GridLine::Line(1)), 1);
200
        assert_eq!(encode_grid_line(&GridLine::Line(-1)), -1);
201
        assert_eq!(encode_grid_line(&GridLine::Line(32_000)), 32_000);
202
        assert_eq!(encode_grid_line(&GridLine::Line(-32_000)), -32_000);
203
        // One past the guarded range: must become the sentinel, never a wrapped i16.
204
        assert_eq!(encode_grid_line(&GridLine::Line(32_001)), I16_SENTINEL);
205
        assert_eq!(encode_grid_line(&GridLine::Line(-32_001)), I16_SENTINEL);
206
        assert_eq!(encode_grid_line(&GridLine::Line(i32::MAX)), I16_SENTINEL);
207
        assert_eq!(encode_grid_line(&GridLine::Line(i32::MIN)), I16_SENTINEL);
208
    }
209

            
210
    #[test]
211
    fn grid_line_span_boundaries_and_nonsense_spans() {
212
        assert_eq!(encode_grid_line(&GridLine::Span(1)), -1);
213
        assert_eq!(encode_grid_line(&GridLine::Span(32_000)), -32_000);
214
        // `span 0` / negative spans are not representable -> sentinel, NOT 0 (which
215
        // would silently mean "grid line 0").
216
        assert_eq!(encode_grid_line(&GridLine::Span(0)), I16_SENTINEL);
217
        assert_eq!(encode_grid_line(&GridLine::Span(-1)), I16_SENTINEL);
218
        assert_eq!(encode_grid_line(&GridLine::Span(32_001)), I16_SENTINEL);
219
        assert_eq!(encode_grid_line(&GridLine::Span(i32::MAX)), I16_SENTINEL);
220
        assert_eq!(encode_grid_line(&GridLine::Span(i32::MIN)), I16_SENTINEL);
221
    }
222

            
223
    #[test]
224
    fn grid_line_in_range_values_never_alias_the_sentinel_band() {
225
        // A real line number that lands on >= I16_SENTINEL_THRESHOLD would decode
226
        // as "auto" / "overflow" and move the item to a different grid cell.
227
        for n in [-32_000i32, -1_000, -1, 0, 1, 1_000, 32_000] {
228
            let e = encode_grid_line(&GridLine::Line(n));
229
            assert!(
230
                e < I16_SENTINEL_THRESHOLD,
231
                "Line({n}) encoded into the sentinel band as {e}"
232
            );
233
        }
234
        for n in [1i32, 2, 1_000, 32_000] {
235
            let e = encode_grid_line(&GridLine::Span(n));
236
            assert!(e < 0, "Span({n}) must encode as a negative value, got {e}");
237
            assert!(
238
                e < I16_SENTINEL_THRESHOLD,
239
                "Span({n}) encoded into the sentinel band as {e}"
240
            );
241
        }
242
    }
243

            
244
    // -------------------------------------------------------------------------
245
    // encode_layout_width / encode_layout_height
246
    // -------------------------------------------------------------------------
247

            
248
    #[test]
249
    fn layout_width_keywords_map_to_distinct_sentinels() {
250
        let auto: CssPropertyValue<LayoutWidth> = CssPropertyValue::Auto;
251
        let none: CssPropertyValue<LayoutWidth> = CssPropertyValue::None;
252
        let initial: CssPropertyValue<LayoutWidth> = CssPropertyValue::Initial;
253
        let inherit: CssPropertyValue<LayoutWidth> = CssPropertyValue::Inherit;
254
        assert_eq!(encode_layout_width(&auto), U32_AUTO);
255
        assert_eq!(encode_layout_width(&none), U32_NONE);
256
        assert_eq!(encode_layout_width(&initial), U32_INITIAL);
257
        assert_eq!(encode_layout_width(&inherit), U32_INHERIT);
258
    }
259

            
260
    #[test]
261
    fn layout_width_revert_and_unset_fall_back_to_the_overflow_sentinel() {
262
        // `revert` / `unset` have no compact slot. They must land on U32_SENTINEL
263
        // (= "ask the slow path"), never on a *semantic* sentinel like AUTO.
264
        let revert: CssPropertyValue<LayoutWidth> = CssPropertyValue::Revert;
265
        let unset: CssPropertyValue<LayoutWidth> = CssPropertyValue::Unset;
266
        assert_eq!(encode_layout_width(&revert), U32_SENTINEL);
267
        assert_eq!(encode_layout_width(&unset), U32_SENTINEL);
268
        assert_eq!(encode_layout_height(&revert), U32_SENTINEL);
269
        assert_eq!(encode_layout_height(&unset), U32_SENTINEL);
270
    }
271

            
272
    #[test]
273
    fn layout_width_exact_keyword_variants() {
274
        assert_eq!(
275
            encode_layout_width(&CssPropertyValue::Exact(LayoutWidth::Auto)),
276
            U32_AUTO
277
        );
278
        assert_eq!(
279
            encode_layout_width(&CssPropertyValue::Exact(LayoutWidth::MinContent)),
280
            U32_MIN_CONTENT
281
        );
282
        assert_eq!(
283
            encode_layout_width(&CssPropertyValue::Exact(LayoutWidth::MaxContent)),
284
            U32_MAX_CONTENT
285
        );
286
        // fit-content() is not compact-encodable -> tier 3
287
        assert_eq!(
288
            encode_layout_width(&CssPropertyValue::Exact(LayoutWidth::FitContent(
289
                PixelValue::px(10.0)
290
            ))),
291
            U32_SENTINEL
292
        );
293
    }
294

            
295
    #[test]
296
    fn layout_width_px_round_trips() {
297
        for px in [0.0f32, 0.5, 1.0, 100.0, 1234.567, -50.0] {
298
            let enc = encode_layout_width(&CssPropertyValue::Exact(LayoutWidth::Px(
299
                PixelValue::px(px),
300
            )));
301
            let dec = decode_pixel_value_u32(enc)
302
                .expect("an in-range px value must not encode to a sentinel");
303
            assert_eq!(dec.metric, SizeMetric::Px);
304
            assert!(
305
                (dec.number.get() - px).abs() < 0.002,
306
                "round-trip of {px}px produced {}px",
307
                dec.number.get()
308
            );
309
        }
310
    }
311

            
312
    #[test]
313
    fn layout_width_extreme_values_saturate_to_the_overflow_sentinel() {
314
        // Past the 28-bit fixed-point range the encoder must bail to tier 3 rather
315
        // than wrapping the low bits into a small (and plausible-looking) width.
316
        for px in [
317
            1.0e9f32,
318
            -1.0e9,
319
            f32::MAX,
320
            f32::MIN,
321
            f32::INFINITY,
322
            f32::NEG_INFINITY,
323
        ] {
324
            let enc = encode_layout_width(&CssPropertyValue::Exact(LayoutWidth::Px(
325
                PixelValue::px(px),
326
            )));
327
            assert_eq!(
328
                enc, U32_SENTINEL,
329
                "width {px}px should overflow to U32_SENTINEL, got {enc:#x}"
330
            );
331
        }
332
    }
333

            
334
    #[test]
335
    fn layout_width_nan_degrades_to_zero_without_panicking() {
336
        // `NaN as isize` saturates to 0, so a NaN width becomes 0px — deterministic
337
        // and finite, which is what the layout solver needs.
338
        let enc = encode_layout_width(&CssPropertyValue::Exact(LayoutWidth::Px(PixelValue::px(
339
            f32::NAN,
340
        ))));
341
        let dec = decode_pixel_value_u32(enc).expect("NaN must degrade to a value, not a sentinel");
342
        assert!(dec.number.get().is_finite());
343
        assert_eq!(dec.number.get(), 0.0);
344
    }
345

            
346
    #[test]
347
    fn layout_height_never_diverges_from_layout_width() {
348
        let vals = [
349
            CssPropertyValue::Exact(LayoutWidth::Auto),
350
            CssPropertyValue::Exact(LayoutWidth::MinContent),
351
            CssPropertyValue::Exact(LayoutWidth::MaxContent),
352
            CssPropertyValue::Exact(LayoutWidth::Px(PixelValue::px(42.0))),
353
            CssPropertyValue::Exact(LayoutWidth::Px(PixelValue::px(1.0e9))),
354
            CssPropertyValue::Unset,
355
        ];
356
        for v in &vals {
357
            assert_eq!(encode_layout_width(v), encode_layout_height(v));
358
        }
359
    }
360

            
361
    // -------------------------------------------------------------------------
362
    // encode_pixel_prop
363
    // -------------------------------------------------------------------------
364

            
365
    #[test]
366
    fn pixel_prop_keywords_map_to_distinct_sentinels() {
367
        let auto: CssPropertyValue<LayoutMinWidth> = CssPropertyValue::Auto;
368
        let none: CssPropertyValue<LayoutMinWidth> = CssPropertyValue::None;
369
        let initial: CssPropertyValue<LayoutMinWidth> = CssPropertyValue::Initial;
370
        let inherit: CssPropertyValue<LayoutMinWidth> = CssPropertyValue::Inherit;
371
        let revert: CssPropertyValue<LayoutMinWidth> = CssPropertyValue::Revert;
372
        let unset: CssPropertyValue<LayoutMinWidth> = CssPropertyValue::Unset;
373
        assert_eq!(encode_pixel_prop(&auto), U32_AUTO);
374
        assert_eq!(encode_pixel_prop(&none), U32_NONE);
375
        assert_eq!(encode_pixel_prop(&initial), U32_INITIAL);
376
        assert_eq!(encode_pixel_prop(&inherit), U32_INHERIT);
377
        assert_eq!(encode_pixel_prop(&revert), U32_SENTINEL);
378
        assert_eq!(encode_pixel_prop(&unset), U32_SENTINEL);
379
    }
380

            
381
    #[test]
382
    fn pixel_prop_round_trips_value_and_metric() {
383
        for pv in [
384
            PixelValue::px(50.0),
385
            PixelValue::em(1.5),
386
            PixelValue::percent(80.0),
387
            PixelValue::pt(12.0),
388
            PixelValue::rem(2.0),
389
        ] {
390
            let enc = encode_pixel_prop(&CssPropertyValue::Exact(LayoutMinWidth { inner: pv }));
391
            let dec = decode_pixel_value_u32(enc).expect("must round-trip");
392
            assert_eq!(dec.metric, pv.metric, "metric lost in the round-trip");
393
            assert!(
394
                (dec.number.get() - pv.number.get()).abs() < 0.002,
395
                "value lost in the round-trip: {} -> {}",
396
                pv.number.get(),
397
                dec.number.get()
398
            );
399
        }
400
    }
401

            
402
    #[test]
403
    fn pixel_prop_overflow_saturates() {
404
        let enc = encode_pixel_prop(&CssPropertyValue::Exact(LayoutMinWidth {
405
            inner: PixelValue::px(1.0e9),
406
        }));
407
        assert_eq!(enc, U32_SENTINEL);
408
    }
409

            
410
    #[test]
411
    fn pixel_prop_exact_value_never_aliases_a_semantic_sentinel() {
412
        // INVARIANT: an `Exact` length may overflow to U32_SENTINEL (= "slow path"),
413
        // but must never collide with a sentinel that means something *else*
414
        // (auto / none / inherit / initial / min-content / max-content) — that turns
415
        // a length into a different keyword with no way to tell.
416
        //
417
        // `encode_pixel_value_u32` packs `value << 4 | metric`. For the raw
418
        // fixed-point value -1 (i.e. -0.001) the value bits are 0xFFFF_FFF0, so any
419
        // metric whose code is >= 9 (vh = 9, vmin = 10, vmax = 11) ORs straight into
420
        // the sentinel band:
421
        //     -0.001vh   -> 0xFFFF_FFF9 == U32_MAX_CONTENT
422
        //     -0.001vmin -> 0xFFFF_FFFA == U32_MIN_CONTENT
423
        //     -0.001vmax -> 0xFFFF_FFFB == U32_INITIAL
424
        for metric in [SizeMetric::Vh, SizeMetric::Vmin, SizeMetric::Vmax] {
425
            let pv = PixelValue::from_metric(metric, -0.001);
426
            let enc = encode_pixel_prop(&CssPropertyValue::Exact(LayoutMinWidth { inner: pv }));
427
            assert!(
428
                enc == U32_SENTINEL || enc < U32_SENTINEL_THRESHOLD,
429
                "an Exact viewport length encoded to {enc:#x}, which aliases a semantic sentinel",
430
            );
431
        }
432
    }
433

            
434
    // -------------------------------------------------------------------------
435
    // encode_css_pixel_as_i16 / encode_margin_i16
436
    // -------------------------------------------------------------------------
437

            
438
    #[test]
439
    fn css_pixel_i16_scales_by_ten() {
440
        assert_eq!(encode_css_pixel_as_i16(&padding(0.0)), 0);
441
        assert_eq!(encode_css_pixel_as_i16(&padding(10.5)), 105);
442
        assert_eq!(encode_css_pixel_as_i16(&padding(-10.5)), -105);
443
    }
444

            
445
    #[test]
446
    fn css_pixel_i16_boundaries() {
447
        // 3276.3px is the largest representable value (one below the sentinel band)
448
        assert_eq!(encode_css_pixel_as_i16(&padding(3276.3)), 32_763);
449
        // one tick further must saturate, NOT alias I16_INITIAL (32764)
450
        assert_eq!(encode_css_pixel_as_i16(&padding(3276.4)), I16_SENTINEL);
451
        // and the negative end
452
        assert_eq!(encode_css_pixel_as_i16(&padding(-3276.8)), -32_768);
453
        assert_eq!(encode_css_pixel_as_i16(&padding(-3276.9)), I16_SENTINEL);
454
    }
455

            
456
    #[test]
457
    fn css_pixel_i16_non_px_units_need_the_slow_path() {
458
        let em = CssPropertyValue::Exact(LayoutPaddingTop {
459
            inner: PixelValue::em(2.0),
460
        });
461
        let pct = CssPropertyValue::Exact(LayoutPaddingTop {
462
            inner: PixelValue::percent(50.0),
463
        });
464
        assert_eq!(encode_css_pixel_as_i16(&em), I16_SENTINEL);
465
        assert_eq!(encode_css_pixel_as_i16(&pct), I16_SENTINEL);
466
    }
467

            
468
    #[test]
469
    fn css_pixel_i16_keywords_are_distinguishable() {
470
        let auto: CssPropertyValue<LayoutPaddingTop> = CssPropertyValue::Auto;
471
        let initial: CssPropertyValue<LayoutPaddingTop> = CssPropertyValue::Initial;
472
        let inherit: CssPropertyValue<LayoutPaddingTop> = CssPropertyValue::Inherit;
473
        let none: CssPropertyValue<LayoutPaddingTop> = CssPropertyValue::None;
474
        let revert: CssPropertyValue<LayoutPaddingTop> = CssPropertyValue::Revert;
475
        let unset: CssPropertyValue<LayoutPaddingTop> = CssPropertyValue::Unset;
476
        assert_eq!(encode_css_pixel_as_i16(&auto), I16_AUTO);
477
        assert_eq!(encode_css_pixel_as_i16(&initial), I16_INITIAL);
478
        assert_eq!(encode_css_pixel_as_i16(&inherit), I16_INHERIT);
479
        // none / revert / unset have no dedicated slot -> generic sentinel
480
        assert_eq!(encode_css_pixel_as_i16(&none), I16_SENTINEL);
481
        assert_eq!(encode_css_pixel_as_i16(&revert), I16_SENTINEL);
482
        assert_eq!(encode_css_pixel_as_i16(&unset), I16_SENTINEL);
483
    }
484

            
485
    #[test]
486
    fn css_pixel_i16_nan_and_infinity_are_safe() {
487
        assert_eq!(encode_css_pixel_as_i16(&padding(f32::NAN)), 0);
488
        assert_eq!(
489
            encode_css_pixel_as_i16(&padding(f32::INFINITY)),
490
            I16_SENTINEL
491
        );
492
        assert_eq!(
493
            encode_css_pixel_as_i16(&padding(f32::NEG_INFINITY)),
494
            I16_SENTINEL
495
        );
496
        assert_eq!(encode_css_pixel_as_i16(&padding(f32::MAX)), I16_SENTINEL);
497
        assert_eq!(encode_css_pixel_as_i16(&padding(f32::MIN)), I16_SENTINEL);
498
    }
499

            
500
    #[test]
501
    fn css_pixel_i16_exact_value_never_aliases_a_keyword_sentinel() {
502
        // The i16 encoder range-checks *both* ends before narrowing, so — unlike the
503
        // u32 path — an Exact px value can never be mistaken for auto/inherit/initial.
504
        for px in [
505
            -3276.8f32, -100.0, -0.1, 0.0, 0.1, 100.0, 3276.3, 1.0e9, -1.0e9,
506
        ] {
507
            let e = encode_css_pixel_as_i16(&padding(px));
508
            assert!(
509
                e != I16_AUTO && e != I16_INHERIT && e != I16_INITIAL,
510
                "{px}px aliased a keyword sentinel ({e})"
511
            );
512
        }
513
    }
514

            
515
    #[test]
516
    fn margin_i16_keeps_auto_and_otherwise_matches_the_pixel_encoder() {
517
        let auto: CssPropertyValue<LayoutMarginTop> = CssPropertyValue::Auto;
518
        assert_eq!(encode_margin_i16(&auto), I16_AUTO);
519
        for px in [-50.0f32, 0.0, 12.5, 3276.3, 5.0e9, f32::NAN] {
520
            let m = CssPropertyValue::Exact(LayoutMarginTop {
521
                inner: PixelValue::px(px),
522
            });
523
            assert_eq!(encode_margin_i16(&m), encode_css_pixel_as_i16(&padding(px)));
524
        }
525
    }
526

            
527
    // -------------------------------------------------------------------------
528
    // encode_flex_basis
529
    // -------------------------------------------------------------------------
530

            
531
    #[test]
532
    fn flex_basis_all_variants() {
533
        assert_eq!(
534
            encode_flex_basis(&CssPropertyValue::Exact(LayoutFlexBasis::Auto)),
535
            U32_AUTO
536
        );
537
        let enc = encode_flex_basis(&CssPropertyValue::Exact(LayoutFlexBasis::Exact(
538
            PixelValue::px(120.0),
539
        )));
540
        let dec = decode_pixel_value_u32(enc).expect("px flex-basis must round-trip");
541
        assert!((dec.number.get() - 120.0).abs() < 0.002);
542

            
543
        assert_eq!(encode_flex_basis(&CssPropertyValue::Auto), U32_AUTO);
544
        assert_eq!(encode_flex_basis(&CssPropertyValue::None), U32_NONE);
545
        assert_eq!(encode_flex_basis(&CssPropertyValue::Initial), U32_INITIAL);
546
        assert_eq!(encode_flex_basis(&CssPropertyValue::Inherit), U32_INHERIT);
547
        assert_eq!(encode_flex_basis(&CssPropertyValue::Revert), U32_SENTINEL);
548
        assert_eq!(encode_flex_basis(&CssPropertyValue::Unset), U32_SENTINEL);
549
    }
550

            
551
    #[test]
552
    fn flex_basis_overflow_saturates() {
553
        assert_eq!(
554
            encode_flex_basis(&CssPropertyValue::Exact(LayoutFlexBasis::Exact(
555
                PixelValue::px(1.0e9)
556
            ))),
557
            U32_SENTINEL
558
        );
559
        assert_eq!(
560
            encode_flex_basis(&CssPropertyValue::Exact(LayoutFlexBasis::Exact(
561
                PixelValue::px(f32::INFINITY)
562
            ))),
563
            U32_SENTINEL
564
        );
565
    }
566

            
567
    // -------------------------------------------------------------------------
568
    // update_dom_declared_flags
569
    // -------------------------------------------------------------------------
570

            
571
    fn text_indent_prop() -> CssProperty {
572
        CssProperty::TextIndent(CssPropertyValue::Exact(StyleTextIndent::default()))
573
    }
574

            
575
    fn line_height_prop(pct: f32) -> CssProperty {
576
        CssProperty::LineHeight(CssPropertyValue::Exact(StyleLineHeight {
577
            inner: PercentageValue::new(pct),
578
        }))
579
    }
580

            
581
    #[test]
582
    fn dom_flags_set_the_right_bit_from_zero() {
583
        let mut flags = 0u32;
584
        update_dom_declared_flags(&text_indent_prop(), &mut flags);
585
        assert_eq!(flags, DOM_HAS_TEXT_INDENT);
586

            
587
        let mut flags2 = 0u32;
588
        update_dom_declared_flags(&line_height_prop(150.0), &mut flags2);
589
        assert_eq!(flags2, DOM_HAS_LINE_HEIGHT);
590
    }
591

            
592
    #[test]
593
    fn dom_flags_only_ever_or_never_clear() {
594
        // Starting from all-ones, the function must not clear a single bit.
595
        let mut flags = u32::MAX;
596
        update_dom_declared_flags(&text_indent_prop(), &mut flags);
597
        update_dom_declared_flags(&line_height_prop(150.0), &mut flags);
598
        update_dom_declared_flags(
599
            &CssProperty::Width(CssPropertyValue::Exact(LayoutWidth::px(10.0))),
600
            &mut flags,
601
        );
602
        assert_eq!(flags, u32::MAX);
603
    }
604

            
605
    #[test]
606
    fn dom_flags_accumulate_and_are_idempotent() {
607
        let mut flags = 0u32;
608
        update_dom_declared_flags(&text_indent_prop(), &mut flags);
609
        update_dom_declared_flags(&line_height_prop(150.0), &mut flags);
610
        let after_two = flags;
611
        assert_eq!(after_two, DOM_HAS_TEXT_INDENT | DOM_HAS_LINE_HEIGHT);
612
        // re-applying the same properties must be a no-op
613
        update_dom_declared_flags(&text_indent_prop(), &mut flags);
614
        update_dom_declared_flags(&line_height_prop(150.0), &mut flags);
615
        assert_eq!(flags, after_two);
616
    }
617

            
618
    #[test]
619
    fn dom_flags_are_not_set_for_a_valueless_property() {
620
        // `line-height: initial` / `text-indent: auto` carry no Exact payload, so the
621
        // "declared" fast-path bit must stay clear (the slow walk would find nothing).
622
        let mut flags = 0u32;
623
        update_dom_declared_flags(
624
            &CssProperty::LineHeight(CssPropertyValue::Initial),
625
            &mut flags,
626
        );
627
        update_dom_declared_flags(&CssProperty::TextIndent(CssPropertyValue::Auto), &mut flags);
628
        update_dom_declared_flags(
629
            &CssProperty::TextIndent(CssPropertyValue::Unset),
630
            &mut flags,
631
        );
632
        assert_eq!(flags, 0);
633
    }
634

            
635
    #[test]
636
    fn dom_flags_ignore_unrelated_properties() {
637
        let mut flags = 0u32;
638
        update_dom_declared_flags(
639
            &CssProperty::Width(CssPropertyValue::Exact(LayoutWidth::px(10.0))),
640
            &mut flags,
641
        );
642
        update_dom_declared_flags(
643
            &CssProperty::ZIndex(CssPropertyValue::Exact(LayoutZIndex::Integer(3))),
644
            &mut flags,
645
        );
646
        assert_eq!(flags, 0);
647
    }
648

            
649
    // -------------------------------------------------------------------------
650
    // apply_css_property_to_compact — tier 1 bitfield
651
    // -------------------------------------------------------------------------
652

            
653
    #[test]
654
    fn apply_tier1_fields_do_not_bleed_into_each_other() {
655
        let mut s = Sink::new();
656
        s.apply(&CssProperty::Display(CssPropertyValue::Exact(
657
            LayoutDisplay::InlineBlock,
658
        )));
659
        s.apply(&CssProperty::Position(CssPropertyValue::Exact(
660
            LayoutPosition::Absolute,
661
        )));
662
        // border-collapse lives at bit 52, i.e. at the far end of the bitfield
663
        s.apply(&CssProperty::BorderCollapse(CssPropertyValue::Exact(
664
            StyleBorderCollapse::Collapse,
665
        )));
666

            
667
        assert_eq!(
668
            (s.tier1 >> DISPLAY_SHIFT) & DISPLAY_MASK,
669
            u64::from(layout_display_to_u8(LayoutDisplay::InlineBlock))
670
        );
671
        assert_eq!(
672
            (s.tier1 >> POSITION_SHIFT) & POSITION_MASK,
673
            u64::from(layout_position_to_u8(LayoutPosition::Absolute))
674
        );
675
        assert_eq!(
676
            (s.tier1 >> BORDER_COLLAPSE_SHIFT) & BORDER_COLLAPSE_MASK,
677
            u64::from(border_collapse_to_u8(StyleBorderCollapse::Collapse))
678
        );
679

            
680
        let known = (DISPLAY_MASK << DISPLAY_SHIFT)
681
            | (POSITION_MASK << POSITION_SHIFT)
682
            | (BORDER_COLLAPSE_MASK << BORDER_COLLAPSE_SHIFT);
683
        assert_eq!(
684
            s.tier1 & !known,
685
            0,
686
            "tier1 = {:#x} has bits set outside the three fields that were written",
687
            s.tier1
688
        );
689
    }
690

            
691
    #[test]
692
    fn apply_tier1_overwrite_clears_only_its_own_field() {
693
        // Hostile starting state: every bit set. The clear-then-set in `set_tier1!`
694
        // must wipe exactly the display field and leave every neighbour intact.
695
        let mut s = Sink::new();
696
        s.tier1 = u64::MAX;
697
        s.apply(&CssProperty::Display(CssPropertyValue::Exact(
698
            LayoutDisplay::Block,
699
        )));
700
        assert_eq!(
701
            (s.tier1 >> DISPLAY_SHIFT) & DISPLAY_MASK,
702
            u64::from(layout_display_to_u8(LayoutDisplay::Block))
703
        );
704
        let others = !(DISPLAY_MASK << DISPLAY_SHIFT);
705
        assert_eq!(
706
            s.tier1 & others,
707
            u64::MAX & others,
708
            "neighbouring tier-1 fields were clobbered"
709
        );
710
    }
711

            
712
    #[test]
713
    fn apply_tier1_ignores_a_valueless_property() {
714
        let mut s = Sink::new();
715
        s.apply(&CssProperty::Display(CssPropertyValue::Inherit));
716
        assert_eq!(
717
            s.tier1, 0,
718
            "`display: inherit` has no Exact payload to encode"
719
        );
720
    }
721

            
722
    // -------------------------------------------------------------------------
723
    // apply_css_property_to_compact — tier 2 dims
724
    // -------------------------------------------------------------------------
725

            
726
    #[test]
727
    fn apply_width_round_trips_and_touches_nothing_else() {
728
        let mut s = Sink::new();
729
        let before_cold = s.cold;
730
        let before_text = s.text;
731
        s.apply(&CssProperty::Width(CssPropertyValue::Exact(
732
            LayoutWidth::Px(PixelValue::px(320.0)),
733
        )));
734
        let dec = decode_pixel_value_u32(s.dims.width).expect("width must round-trip");
735
        assert!((dec.number.get() - 320.0).abs() < 0.002);
736
        assert_eq!(
737
            s.tier1, 0,
738
            "a tier-2 property must not touch the tier-1 bitfield"
739
        );
740
        assert_eq!(
741
            s.cold, before_cold,
742
            "a tier-2 property must not touch tier-2 cold"
743
        );
744
        assert_eq!(
745
            s.text, before_text,
746
            "a tier-2 property must not touch tier-2b text"
747
        );
748
        assert!(s.fonts.is_empty());
749
    }
750

            
751
    #[test]
752
    fn apply_flex_grow_saturates_and_rejects_negatives() {
753
        let mut s = Sink::new();
754
        s.apply(&CssProperty::FlexGrow(CssPropertyValue::Exact(
755
            LayoutFlexGrow {
756
                inner: FloatValue::new(2.5),
757
            },
758
        )));
759
        assert_eq!(s.dims.flex_grow, 250);
760

            
761
        // A negative flex-grow must not wrap around into a huge positive u16.
762
        let mut neg = Sink::new();
763
        neg.apply(&CssProperty::FlexGrow(CssPropertyValue::Exact(
764
            LayoutFlexGrow {
765
                inner: FloatValue::new(-1.0),
766
            },
767
        )));
768
        assert_eq!(neg.dims.flex_grow, U16_SENTINEL);
769

            
770
        // ...and neither must an absurdly large one.
771
        let mut big = Sink::new();
772
        big.apply(&CssProperty::FlexGrow(CssPropertyValue::Exact(
773
            LayoutFlexGrow {
774
                inner: FloatValue::new(1.0e9),
775
            },
776
        )));
777
        assert_eq!(big.dims.flex_grow, U16_SENTINEL);
778

            
779
        // NaN degrades to 0 rather than to a wrapped value.
780
        let mut nan = Sink::new();
781
        nan.apply(&CssProperty::FlexShrink(CssPropertyValue::Exact(
782
            LayoutFlexShrink {
783
                inner: FloatValue::new(f32::NAN),
784
            },
785
        )));
786
        assert_eq!(nan.dims.flex_shrink, 0);
787
    }
788

            
789
    #[test]
790
    fn apply_gap_px_sets_both_axes_and_ignores_unresolvable_units() {
791
        let mut s = Sink::new();
792
        s.apply(&CssProperty::Gap(CssPropertyValue::Exact(LayoutGap {
793
            inner: PixelValue::px(8.0),
794
        })));
795
        assert_eq!(s.dims.row_gap, 80);
796
        assert_eq!(s.dims.column_gap, 80);
797

            
798
        // An `em` gap cannot be resolved without a font context — it must be left
799
        // untouched (so the slow path can handle it), not silently encoded as 2px.
800
        let mut em = Sink::new();
801
        em.apply(&CssProperty::Gap(CssPropertyValue::Exact(LayoutGap {
802
            inner: PixelValue::em(2.0),
803
        })));
804
        assert_eq!(em.dims.row_gap, 0);
805
        assert_eq!(em.dims.column_gap, 0);
806
    }
807

            
808
    // -------------------------------------------------------------------------
809
    // apply_css_property_to_compact — tier 2 cold
810
    // -------------------------------------------------------------------------
811

            
812
    #[test]
813
    fn apply_z_index_auto_and_in_range_values() {
814
        let mut s = Sink::new();
815
        s.apply(&CssProperty::ZIndex(CssPropertyValue::Exact(
816
            LayoutZIndex::Auto,
817
        )));
818
        assert_eq!(s.cold.z_index, I16_AUTO);
819
        s.apply(&CssProperty::ZIndex(CssPropertyValue::Exact(
820
            LayoutZIndex::Integer(100),
821
        )));
822
        assert_eq!(s.cold.z_index, 100);
823
        // last value below the sentinel band
824
        s.apply(&CssProperty::ZIndex(CssPropertyValue::Exact(
825
            LayoutZIndex::Integer(32_763),
826
        )));
827
        assert_eq!(s.cold.z_index, 32_763);
828
    }
829

            
830
    #[test]
831
    fn apply_z_index_large_positive_saturates() {
832
        for z in [32_764i32, 100_000, i32::MAX] {
833
            let mut s = Sink::new();
834
            s.apply(&CssProperty::ZIndex(CssPropertyValue::Exact(
835
                LayoutZIndex::Integer(z),
836
            )));
837
            assert_eq!(s.cold.z_index, I16_SENTINEL, "z-index {z} should saturate");
838
        }
839
    }
840

            
841
    #[test]
842
    fn apply_z_index_large_negative_must_not_wrap_positive() {
843
        // The encoder range-checks only the UPPER bound:
844
        //     if *z >= I16_SENTINEL_THRESHOLD { I16_SENTINEL } else { *z as i16 }
845
        // so a large negative z-index truncates instead of saturating, e.g.
846
        //     z-index: -40000  ->  -40000 as i16  ==  +25536
847
        // which flips the node from the very back of the stacking context to the
848
        // front. Compare with the line-height encoder, which *does* check
849
        // `pct_x10 >= -32768` before narrowing.
850
        for z in [-32_769i32, -40_000, -99_999, i32::MIN] {
851
            let mut s = Sink::new();
852
            s.apply(&CssProperty::ZIndex(CssPropertyValue::Exact(
853
                LayoutZIndex::Integer(z),
854
            )));
855
            assert!(
856
                s.cold.z_index < 0 || s.cold.z_index == I16_SENTINEL,
857
                "z-index {z} encoded to {}: a negative z-index must stay negative (or saturate to \
858
                 the sentinel), it must never wrap to a positive value",
859
                s.cold.z_index,
860
            );
861
        }
862
    }
863

            
864
    #[test]
865
    fn apply_border_styles_pack_into_independent_nibbles() {
866
        let mut s = Sink::new();
867
        s.apply(&CssProperty::BorderTopStyle(CssPropertyValue::Exact(
868
            StyleBorderTopStyle {
869
                inner: BorderStyle::Solid,
870
            },
871
        )));
872
        assert_eq!(
873
            s.cold.border_styles_packed & 0x000F,
874
            u16::from(border_style_to_u8(BorderStyle::Solid))
875
        );
876
        assert_eq!(
877
            s.cold.border_styles_packed & 0xFFF0,
878
            0,
879
            "the top-style nibble leaked into the other three sides"
880
        );
881

            
882
        // Re-applying must REPLACE the nibble, not OR into it: Solid(1) | Double(2)
883
        // would be Dotted(3), a different border style entirely.
884
        s.apply(&CssProperty::BorderTopStyle(CssPropertyValue::Exact(
885
            StyleBorderTopStyle {
886
                inner: BorderStyle::Double,
887
            },
888
        )));
889
        assert_eq!(
890
            s.cold.border_styles_packed & 0x000F,
891
            u16::from(border_style_to_u8(BorderStyle::Double))
892
        );
893
    }
894

            
895
    #[test]
896
    fn apply_opacity_clamps_into_the_0_254_range() {
897
        for (pct, expected) in [
898
            (-1.0e9f32, 0u8),
899
            (-100.0, 0),
900
            (0.0, 0),
901
            (50.0, 127),
902
            (100.0, 254),
903
            (500.0, 254),
904
            (1.0e9, 254),
905
        ] {
906
            let mut s = Sink::new();
907
            s.apply(&CssProperty::Opacity(CssPropertyValue::Exact(
908
                StyleOpacity {
909
                    inner: PercentageValue::new(pct),
910
                },
911
            )));
912
            assert_eq!(s.cold.opacity, expected, "opacity: {pct}%");
913
            assert_ne!(
914
                s.cold.opacity, OPACITY_SENTINEL,
915
                "an explicitly set opacity must never encode as the 'unset' sentinel"
916
            );
917
        }
918
    }
919

            
920
    #[test]
921
    fn apply_grid_column_encodes_both_lines() {
922
        let mut s = Sink::new();
923
        s.apply(&CssProperty::GridColumn(CssPropertyValue::Exact(
924
            GridPlacement {
925
                grid_start: GridLine::Line(2),
926
                grid_end: GridLine::Span(3),
927
            },
928
        )));
929
        assert_eq!(s.cold.grid_col_start, 2);
930
        assert_eq!(s.cold.grid_col_end, -3);
931
        // grid-row must be untouched by a grid-column declaration
932
        assert_eq!(s.cold.grid_row_start, I16_AUTO);
933
        assert_eq!(s.cold.grid_row_end, I16_AUTO);
934
    }
935

            
936
    #[test]
937
    fn apply_hot_flags_or_in_without_clobbering_each_other() {
938
        let mut s = Sink::new();
939
        s.apply(&CssProperty::TextDecoration(CssPropertyValue::Exact(
940
            StyleTextDecoration::Underline,
941
        )));
942
        assert_eq!(
943
            s.cold.hot_flags & HOT_FLAG_HAS_TEXT_DECORATION,
944
            HOT_FLAG_HAS_TEXT_DECORATION
945
        );
946

            
947
        // scrollbar-gutter writes a 2-bit *field* into the same byte; it must not
948
        // wipe the has-* bits around it.
949
        s.apply(&CssProperty::ScrollbarGutter(CssPropertyValue::Exact(
950
            StyleScrollbarGutter::Stable,
951
        )));
952
        assert_eq!(
953
            (s.cold.hot_flags & HOT_FLAG_SCROLLBAR_GUTTER_MASK) >> HOT_FLAG_SCROLLBAR_GUTTER_SHIFT,
954
            SCROLLBAR_GUTTER_STABLE
955
        );
956
        assert_eq!(
957
            s.cold.hot_flags & HOT_FLAG_HAS_TEXT_DECORATION,
958
            HOT_FLAG_HAS_TEXT_DECORATION,
959
            "scrollbar-gutter cleared the has-text-decoration bit"
960
        );
961

            
962
        // ...and replacing the gutter value must clear the old bits, not OR into them
963
        s.apply(&CssProperty::ScrollbarGutter(CssPropertyValue::Exact(
964
            StyleScrollbarGutter::Auto,
965
        )));
966
        assert_eq!(
967
            (s.cold.hot_flags & HOT_FLAG_SCROLLBAR_GUTTER_MASK) >> HOT_FLAG_SCROLLBAR_GUTTER_SHIFT,
968
            SCROLLBAR_GUTTER_AUTO
969
        );
970
        assert_eq!(
971
            s.cold.hot_flags & HOT_FLAG_HAS_TEXT_DECORATION,
972
            HOT_FLAG_HAS_TEXT_DECORATION
973
        );
974
    }
975

            
976
    #[test]
977
    fn apply_valueless_property_does_not_set_a_has_flag() {
978
        // The has-* bits exist so the getter can skip the cascade walk. A property
979
        // with no Exact payload must leave them clear, or every node pays for a walk
980
        // that would find nothing.
981
        let mut s = Sink::new();
982
        s.apply(&CssProperty::TextDecoration(CssPropertyValue::Initial));
983
        s.apply(&CssProperty::ScrollbarGutter(CssPropertyValue::Unset));
984
        assert_eq!(s.cold.hot_flags, 0);
985
    }
986

            
987
    // -------------------------------------------------------------------------
988
    // apply_css_property_to_compact — tier 2b text
989
    // -------------------------------------------------------------------------
990

            
991
    #[test]
992
    fn apply_text_color_packs_rgba_big_endian() {
993
        let mut s = Sink::new();
994
        s.apply(&CssProperty::TextColor(CssPropertyValue::Exact(
995
            StyleTextColor {
996
                inner: ColorU {
997
                    r: 0x12,
998
                    g: 0x34,
999
                    b: 0x56,
                    a: 0x78,
                },
            },
        )));
        assert_eq!(s.text.text_color, 0x1234_5678);
        // Documented limitation: rgba(0,0,0,0) is indistinguishable from "unset".
        let mut transparent = Sink::new();
        transparent.apply(&CssProperty::TextColor(CssPropertyValue::Exact(
            StyleTextColor {
                inner: ColorU {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 0,
                },
            },
        )));
        assert_eq!(transparent.text.text_color, 0);
    }
    #[test]
    fn apply_line_height_round_trips_and_saturates_at_both_ends() {
        let mut s = Sink::new();
        s.apply(&line_height_prop(120.0));
        assert_eq!(s.text.line_height, 1200, "120% must encode as % x 10");
        // Absurd values must saturate - no wrap-around. The two signs land
        // differently by design: a huge POSITIVE (unitless multiple) falls to
        // the sentinel ("normal" - a 10^7x multiple is meaningless), while a
        // huge NEGATIVE (= absolute px per the parser convention) CLAMPS to
        // the largest representable px (-32768 = 3276.8px) instead of being
        // silently reinterpreted as "normal".
        let mut big = Sink::new();
        big.apply(&line_height_prop(1.0e9f32));
        assert_eq!(
            big.text.line_height, I16_SENTINEL,
            "a huge unitless multiple saturates to the sentinel"
        );
        let mut neg = Sink::new();
        neg.apply(&line_height_prop(-1.0e9f32));
        assert_eq!(
            neg.text.line_height, -32768,
            "a huge absolute px line-height clamps instead of dropping to normal"
        );
        // The split scale itself: 48px (normalized -48) stores as -480 and
        // decodes back to 48px - the old x1000 scale overflowed at 32.76px.
        let mut px48 = Sink::new();
        px48.apply(&line_height_prop(-4800.0));
        assert_eq!(
            px48.text.line_height, -480,
            "line-height: 48px stores as -px x 10"
        );
    }
    #[test]
    fn apply_font_family_hash_is_nonzero_stable_and_registered() {
        let arial = StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("Arial".into())]);
        let mut s = Sink::new();
        s.apply(&CssProperty::FontFamily(CssPropertyValue::Exact(
            arial.clone(),
        )));
        let h = s.text.font_family_hash;
        assert_ne!(
            h, 0,
            "0 is the 'unset' sentinel — a set font-family must never hash to it"
        );
        assert!(
            s.fonts.contains_key(&h),
            "the hash must be registered in the reverse map, or consumers cannot resolve it"
        );
        // Same input -> same hash (the whole dirty-tracking scheme depends on this).
        let mut same = Sink::new();
        same.apply(&CssProperty::FontFamily(CssPropertyValue::Exact(arial)));
        assert_eq!(same.text.font_family_hash, h);
        // Different input -> different hash.
        let mut other = Sink::new();
        other.apply(&CssProperty::FontFamily(CssPropertyValue::Exact(
            StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("Times".into())]),
        )));
        assert_ne!(other.text.font_family_hash, h);
    }
    // -------------------------------------------------------------------------
    // apply_ua_css_to_compact
    // -------------------------------------------------------------------------
    #[test]
    fn ua_css_is_idempotent_for_every_representative_node_type() {
        let nodes = [
            NodeData::create_node(NodeType::Html),
            NodeData::create_node(NodeType::Body),
            NodeData::create_node(NodeType::Div),
            NodeData::create_node(NodeType::P),
            NodeData::create_node(NodeType::Br),
            NodeData::create_text_do_not_use_without_block_level_wrapper("hello"),
        ];
        for nd in &nodes {
            let mut s = Sink::new();
            s.ua(&nd.node_type);
            let once = s.snapshot();
            s.ua(&nd.node_type);
            assert_eq!(
                s.snapshot(),
                once,
                "applying UA CSS twice must be a no-op the second time"
            );
        }
    }
    #[test]
    fn ua_css_never_touches_the_tier1_populated_bit() {
        // Bit 63 is owned by the builder, not by the UA stylesheet.
        for nt in [NodeType::Html, NodeType::Body, NodeType::Div, NodeType::P] {
            let mut s = Sink::new();
            s.ua(&nt);
            assert_eq!(s.tier1 & TIER1_POPULATED_BIT, 0);
        }
    }
    #[test]
    fn ua_css_survives_a_hostile_pre_filled_sink() {
        // Every bit set / every numeric field at an extreme: the writer must still
        // only touch its own fields and must not panic on the sentinel inputs.
        let mut s = Sink::new();
        s.tier1 = u64::MAX;
        s.dims.width = U32_SENTINEL;
        s.dims.font_size = U32_SENTINEL;
        s.dims.flex_grow = U16_SENTINEL;
        s.cold.z_index = i16::MIN;
        s.cold.opacity = OPACITY_SENTINEL;
        s.text.line_height = i16::MIN;
        s.ua(&NodeType::Div);
        assert_eq!(
            s.tier1 & TIER1_POPULATED_BIT,
            TIER1_POPULATED_BIT,
            "UA CSS must not clear bits it does not own"
        );
    }
    // -------------------------------------------------------------------------
    // build_compact_cache
    // -------------------------------------------------------------------------
    #[test]
    fn build_compact_cache_handles_zero_nodes() {
        let cache = CssPropertyCache::empty(0);
        let r = cache.build_compact_cache(&[], &[]);
        assert_eq!(r.node_count(), 0);
        assert!(r.tier2_dims.is_empty());
        assert!(r.font_dirty_nodes.is_empty());
        assert!(r.prev_font_hashes.is_empty());
    }
    #[test]
    fn build_compact_cache_tolerates_a_mismatched_prev_font_hash_slice() {
        let cache = CssPropertyCache::empty(3);
        let nodes = div_nodes(3);
        // longer than node_count, shorter than node_count, and empty — none may panic
        for prev in [vec![1u64, 2, 3, 4, 5, 6], vec![7u64], Vec::new()] {
            let r = cache.build_compact_cache(&nodes, &prev);
            assert_eq!(r.prev_font_hashes.len(), 3);
            assert_eq!(r.node_count(), 3);
        }
    }
    #[test]
    fn build_compact_cache_tolerates_short_node_data() {
        // node_count claims 4 but only 2 NodeDatas are supplied: the trailing nodes
        // must keep their defaults instead of indexing out of bounds.
        let cache = CssPropertyCache::empty(4);
        let r = cache.build_compact_cache(&div_nodes(2), &[]);
        assert_eq!(r.node_count(), 4);
        assert_eq!(r.tier2_dims.len(), 4);
        assert_eq!(r.tier2_cold.len(), 4);
        assert_eq!(r.tier2b_text.len(), 4);
        assert_eq!(r.prev_font_hashes.len(), 4);
    }
    #[test]
    fn build_compact_cache_honours_node_count_over_node_data_len() {
        let cache = CssPropertyCache::empty(2);
        let r = cache.build_compact_cache(&div_nodes(5), &[]);
        assert_eq!(r.node_count(), 2);
    }
    #[test]
    fn build_compact_cache_rebuild_with_unchanged_fonts_is_not_dirty() {
        let cache = CssPropertyCache::empty(3);
        let nodes = div_nodes(3);
        let first = cache.build_compact_cache(&nodes, &[]);
        let second = cache.build_compact_cache(&nodes, &first.prev_font_hashes);
        assert!(
            second.font_dirty_nodes.is_empty(),
            "a rebuild with identical font hashes must not re-resolve any font chain"
        );
    }
    // -------------------------------------------------------------------------
    // build_compact_cache_with_inheritance{,_debug}
    // -------------------------------------------------------------------------
    #[test]
    fn build_with_inheritance_handles_zero_nodes() {
        let cache = CssPropertyCache::empty(0);
        let r = cache.build_compact_cache_with_inheritance(&[], &[], &[]);
        assert_eq!(r.node_count(), 0);
        let mut msgs = None;
        let r2 = cache.build_compact_cache_with_inheritance_debug(&[], &[], &[], &mut msgs);
        assert_eq!(r2.node_count(), 0);
        assert!(msgs.is_none());
    }
    #[test]
    fn build_with_inheritance_propagates_font_size_down_the_chain() {
        let n = 3;
        let cache = CssPropertyCache::empty(n);
        let r =
            cache.build_compact_cache_with_inheritance(&div_nodes(n), &linear_hierarchy(n), &[]);
        assert_eq!(r.node_count(), n);
        // font-size is inheritable: property-less children must match the root exactly.
        assert_eq!(r.tier2_dims[1].font_size, r.tier2_dims[0].font_size);
        assert_eq!(r.tier2_dims[2].font_size, r.tier2_dims[0].font_size);
    }
    #[test]
    fn build_with_inheritance_marks_all_nodes_dirty_on_the_first_build() {
        let n = 3;
        let cache = CssPropertyCache::empty(n);
        let nodes = div_nodes(n);
        let hierarchy = linear_hierarchy(n);
        // Empty prev_font_hashes == first build for this DOM -> force ALL nodes dirty.
        let first = cache.build_compact_cache_with_inheritance(&nodes, &hierarchy, &[]);
        assert_eq!(first.font_dirty_nodes, vec![0, 1, 2]);
        // Second build with the previous hashes -> nothing changed, nothing dirty.
        let second =
            cache.build_compact_cache_with_inheritance(&nodes, &hierarchy, &first.prev_font_hashes);
        assert!(second.font_dirty_nodes.is_empty());
    }
    #[test]
    fn build_with_inheritance_global_star_rules_skip_text_nodes() {
        // Per CSS, `*` matches ELEMENTS. A text node is not an element — it may only
        // inherit from its parent, otherwise `* { padding: 5px }` would overwrite the
        // value a text node inherited from `<p>`.
        let mut cache = CssPropertyCache::empty(2);
        cache
            .global_css_props
            .push(CssProperty::PaddingTop(padding(5.0)));
        let nodes = vec![
            NodeData::create_node(NodeType::Div),
            NodeData::create_text_do_not_use_without_block_level_wrapper("hi"),
        ];
        let r = cache.build_compact_cache_with_inheritance(&nodes, &linear_hierarchy(2), &[]);
        assert_eq!(
            r.tier2_dims[0].padding_top, 50,
            "the `*` rule must apply to the element"
        );
        assert_ne!(
            r.tier2_dims[1].padding_top, 50,
            "the `*` rule must NOT apply to a text node"
        );
    }
    #[test]
    fn build_with_inheritance_debug_messages_are_opt_in() {
        let n = 2;
        let cache = CssPropertyCache::empty(n);
        let nodes = div_nodes(n);
        let hierarchy = linear_hierarchy(n);
        let mut on = Some(Vec::new());
        let _ = cache.build_compact_cache_with_inheritance_debug(&nodes, &hierarchy, &[], &mut on);
        assert!(
            !on.expect("still Some").is_empty(),
            "debug logging must emit at least one cascade message"
        );
        let mut off = None;
        let _ = cache.build_compact_cache_with_inheritance_debug(&nodes, &hierarchy, &[], &mut off);
        assert!(off.is_none(), "a None sink must stay None");
    }
    // -------------------------------------------------------------------------
    // resolve_font_size_to_px
    // -------------------------------------------------------------------------
    #[test]
    fn resolve_font_size_percent_uses_the_parent() {
        let mut dims = vec![CompactNodeProps::default(); 2];
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::px(20.0));
        dims[1].font_size = encode_pixel_value_u32(&PixelValue::percent(50.0));
        resolve_font_size_to_px(&mut dims, 1, Some(NodeId::new(0)));
        let pv = decode_pixel_value_u32(dims[1].font_size).expect("must resolve to px");
        assert_eq!(pv.metric, SizeMetric::Px);
        assert!(
            (pv.number.get() - 10.0).abs() < 0.01,
            "got {}",
            pv.number.get()
        );
    }
    #[test]
    fn resolve_font_size_pt_converts_to_px() {
        let mut dims = vec![CompactNodeProps::default()];
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::pt(12.0));
        resolve_font_size_to_px(&mut dims, 0, None);
        let pv = decode_pixel_value_u32(dims[0].font_size).expect("must resolve to px");
        assert!(
            (pv.number.get() - 16.0).abs() < 0.01,
            "12pt should be 16px, got {}",
            pv.number.get()
        );
    }
    #[test]
    fn resolve_font_size_leaves_absolute_and_sentinel_values_alone() {
        // an already-px value must not be re-scaled by the parent
        let mut dims = vec![CompactNodeProps::default(); 2];
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::px(20.0));
        dims[1].font_size = encode_pixel_value_u32(&PixelValue::px(13.0));
        let before = dims[1].font_size;
        resolve_font_size_to_px(&mut dims, 1, Some(NodeId::new(0)));
        assert_eq!(dims[1].font_size, before);
        // an explicit sentinel must survive untouched
        let mut sent = vec![CompactNodeProps::default(); 2];
        sent[0].font_size = encode_pixel_value_u32(&PixelValue::px(20.0));
        sent[1].font_size = U32_SENTINEL;
        resolve_font_size_to_px(&mut sent, 1, Some(NodeId::new(0)));
        assert_eq!(sent[1].font_size, U32_SENTINEL);
        // ...as must the CSS-initial default (which also sits above the threshold)
        let mut def = vec![CompactNodeProps::default(); 2];
        assert_eq!(def[1].font_size, U32_INITIAL);
        resolve_font_size_to_px(&mut def, 1, Some(NodeId::new(0)));
        assert_eq!(def[1].font_size, U32_INITIAL);
    }
    #[test]
    fn resolve_font_size_negative_em_is_deterministic() {
        let mut dims = vec![CompactNodeProps::default(); 2];
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::px(20.0));
        dims[1].font_size = encode_pixel_value_u32(&PixelValue::em(-2.0));
        resolve_font_size_to_px(&mut dims, 1, Some(NodeId::new(0)));
        let pv = decode_pixel_value_u32(dims[1].font_size).expect("must stay decodable");
        assert!(
            (pv.number.get() + 40.0).abs() < 0.01,
            "-2em of 20px should be -40px, got {}",
            pv.number.get()
        );
    }
    #[test]
    fn resolve_font_size_overflow_saturates_instead_of_wrapping() {
        let mut dims = vec![CompactNodeProps::default(); 2];
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::px(20.0));
        // 100_000em x 20px = 2_000_000px, past the 28-bit fixed-point range
        dims[1].font_size = encode_pixel_value_u32(&PixelValue::em(100_000.0));
        resolve_font_size_to_px(&mut dims, 1, Some(NodeId::new(0)));
        assert_eq!(
            dims[1].font_size, U32_SENTINEL,
            "an overflowing font-size must land on the tier-3 sentinel, not wrap"
        );
    }
    #[test]
    fn resolve_font_size_nan_em_degrades_to_zero() {
        let mut dims = vec![CompactNodeProps::default(); 2];
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::px(20.0));
        dims[1].font_size = encode_pixel_value_u32(&PixelValue::em(f32::NAN));
        resolve_font_size_to_px(&mut dims, 1, Some(NodeId::new(0)));
        let pv = decode_pixel_value_u32(dims[1].font_size).expect("must stay decodable");
        assert!(
            pv.number.get().is_finite(),
            "a NaN font-size must not propagate"
        );
        assert_eq!(pv.number.get(), 0.0);
    }
    #[test]
    fn resolve_font_size_root_rem_uses_the_16px_initial_value() {
        // For the ROOT node, `tier2_dims.first()` IS the node itself — and at this
        // point its font-size is still the *unresolved* rem value. The Rem arm then
        // multiplies the rem factor by itself:
        //     html { font-size: 2rem }  ->  2 * 2 = 4px   (should be 2 * 16 = 32px)
        // Every other unit handles the no-parent case correctly via `map_or(16.0, ..)`.
        let mut dims = vec![CompactNodeProps::default()];
        dims[0].font_size = encode_pixel_value_u32(&PixelValue::rem(2.0));
        resolve_font_size_to_px(&mut dims, 0, None);
        let pv = decode_pixel_value_u32(dims[0].font_size).expect("must resolve to px");
        assert!(
            (pv.number.get() - 32.0).abs() < 0.01,
            "root `font-size: 2rem` should resolve against the 16px initial value (= 32px), got \
             {}px",
            pv.number.get()
        );
    }
}
/// The tier-1 inheritance mask must agree with `CssPropertyType::is_inheritable`
/// SLOT BY SLOT.
#[cfg(test)]
mod inheritance_mask_tests {
    use azul_css::{compact_cache::*, props::property::CssPropertyType};
    use super::INHERITABLE_TIER1_MASK;
    /// Every tier-1 slot, paired with the property it holds. Adding a slot to
    /// `compact_cache` without adding it here leaves it unchecked, so the list
    /// is asserted to be complete against the shift constants below.
    const TIER1_SLOTS: &[(CssPropertyType, u32, u64)] = &[
        (CssPropertyType::Display, DISPLAY_SHIFT, DISPLAY_MASK),
        (CssPropertyType::Position, POSITION_SHIFT, POSITION_MASK),
        (CssPropertyType::Float, FLOAT_SHIFT, FLOAT_MASK),
        (CssPropertyType::OverflowX, OVERFLOW_X_SHIFT, OVERFLOW_MASK),
        (CssPropertyType::OverflowY, OVERFLOW_Y_SHIFT, OVERFLOW_MASK),
        (
            CssPropertyType::BoxSizing,
            BOX_SIZING_SHIFT,
            BOX_SIZING_MASK,
        ),
        (
            CssPropertyType::FlexDirection,
            FLEX_DIRECTION_SHIFT,
            FLEX_DIR_MASK,
        ),
        (CssPropertyType::FlexWrap, FLEX_WRAP_SHIFT, FLEX_WRAP_MASK),
        (
            CssPropertyType::JustifyContent,
            JUSTIFY_CONTENT_SHIFT,
            JUSTIFY_MASK,
        ),
        (CssPropertyType::AlignItems, ALIGN_ITEMS_SHIFT, ALIGN_MASK),
        (
            CssPropertyType::AlignContent,
            ALIGN_CONTENT_SHIFT,
            ALIGN_MASK,
        ),
        (
            CssPropertyType::WritingMode,
            WRITING_MODE_SHIFT,
            WRITING_MODE_MASK,
        ),
        (CssPropertyType::Clear, CLEAR_SHIFT, CLEAR_MASK),
        (
            CssPropertyType::FontWeight,
            FONT_WEIGHT_SHIFT,
            FONT_WEIGHT_MASK,
        ),
        (
            CssPropertyType::FontStyle,
            FONT_STYLE_SHIFT,
            FONT_STYLE_MASK,
        ),
        (
            CssPropertyType::TextAlign,
            TEXT_ALIGN_SHIFT,
            TEXT_ALIGN_MASK,
        ),
        (
            CssPropertyType::Visibility,
            VISIBILITY_SHIFT,
            VISIBILITY_MASK,
        ),
        (
            CssPropertyType::WhiteSpace,
            WHITE_SPACE_SHIFT,
            WHITE_SPACE_MASK,
        ),
        (CssPropertyType::Direction, DIRECTION_SHIFT, DIRECTION_MASK),
        (
            CssPropertyType::VerticalAlign,
            VERTICAL_ALIGN_SHIFT,
            VERTICAL_ALIGN_MASK,
        ),
        (
            CssPropertyType::BorderCollapse,
            BORDER_COLLAPSE_SHIFT,
            BORDER_COLLAPSE_MASK,
        ),
        // `cursor` is inheritable, but it is NOT a tier-1 slot: the word is
        // full, and the bits it was given belonged to `align-self`. It lives
        // in `CompactNodePropsCold::cursor`, and
        // `an_inherited_cursor_does_not_disturb_align_self` covers it.
        //
        // These four are declared in a second constant block further down in
        // compact_cache.rs, and this table used to stop above them. That is
        // why `the_tier1_slots_do_not_overlap` stayed green while `cursor`
        // sat on top of `align_self`: the table never named the field being
        // corrupted. A slot missing from here is not checked by ANY test in
        // this module.
        (
            CssPropertyType::AlignSelf,
            ALIGN_SELF_SHIFT,
            ALIGN_SELF_MASK,
        ),
        (
            CssPropertyType::JustifySelf,
            JUSTIFY_SELF_SHIFT,
            JUSTIFY_SELF_MASK,
        ),
        (
            CssPropertyType::GridAutoFlow,
            GRID_AUTO_FLOW_SHIFT,
            GRID_AUTO_FLOW_MASK,
        ),
        (
            CssPropertyType::JustifyItems,
            JUSTIFY_ITEMS_SHIFT,
            JUSTIFY_ITEMS_MASK,
        ),
    ];
    /// A property that CSS inherits must be in the mask, and one it does not
    /// must not be.
    ///
    /// `writing-mode` failed this: inheritable, with a tier-1 slot since the
    /// cache was written, and never copied from the parent — so
    /// `writing-mode: vertical-rl` on a container laid its children out
    /// horizontally in the compact path while `get_property_slow` inherited it
    /// correctly. Two cascade paths, two answers, no error anywhere.
    #[test]
1
    fn every_inheritable_tier1_property_is_actually_inherited() {
1
        let mut wrong = Vec::new();
26
        for &(ty, shift, mask) in TIER1_SLOTS {
25
            let bits = mask << shift;
25
            let in_mask = (INHERITABLE_TIER1_MASK & bits) == bits;
25
            if in_mask != ty.is_inheritable() {
                wrong.push(format!(
                    "{ty:?}: is_inheritable()={} but {} the inheritance mask",
                    ty.is_inheritable(),
                    if in_mask { "IS in" } else { "is NOT in" },
                ));
25
            }
        }
1
        assert!(
1
            wrong.is_empty(),
            "INHERITABLE_TIER1_MASK disagrees with CssPropertyType::is_inheritable, so the \
             compact and slow cascade paths compute different values:\n  {}",
            wrong.join("\n  "),
        );
1
    }
    /// No two tier-1 slots may overlap, and none may touch the populated bit.
    /// A collision silently corrupts both properties.
    #[test]
1
    fn the_tier1_slots_do_not_overlap() {
1
        let mut used: u64 = 0;
26
        for &(ty, shift, mask) in TIER1_SLOTS {
25
            let bits = mask << shift;
25
            assert_eq!(
25
                bits & TIER1_POPULATED_BIT,
                0,
                "{ty:?} overlaps TIER1_POPULATED_BIT",
            );
            // OverflowX/Y legitimately share a MASK constant but not a shift;
            // the overlap check is on the shifted bits, which are distinct.
25
            assert_eq!(used & bits, 0, "{ty:?} overlaps an earlier tier-1 slot");
25
            used |= bits;
        }
1
    }
}