1
//! CSS properties for writing modes and clearing.
2
//!
3
//! Key types:
4
//! - [`LayoutWritingMode`] — `writing-mode` (`horizontal-tb`, `vertical-rl`, `vertical-lr`)
5
//! - [`LayoutClear`] — `clear` (`none`, `left`, `right`, `both`)
6
//!
7
//! Parse functions are gated behind the `parser` feature and are consumed
8
//! by the CSS property system in `property.rs`.
9

            
10
use alloc::string::{String, ToString};
11

            
12
use crate::{corety::AzString, props::formatter::PrintAsCssValue};
13

            
14
// --- writing-mode (LayoutWritingMode) ---
15

            
16
// +spec:writing-modes:ec496c - writing-mode property: horizontal-tb, vertical-rl, vertical-lr block
17
// flow directions +spec:writing-modes:fdc4cc - writing-mode property: horizontal-tb | vertical-rl |
18
// vertical-lr +spec:writing-modes:aeb9bb - writing-mode property determines block flow direction
19
/// Represents a `writing-mode` attribute
20
// +spec:writing-modes:a7f174 - line orientation: in vertical-lr the line-over (ascender) side is
21
// block-end, not block-start
22
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
23
#[repr(C)]
24
// +spec:block-formatting-context:387117 - writing-mode specifies horizontal/vertical line layout
25
// and block progression direction +spec:block-formatting-context:3815e7 - vertical-rl writing mode
26
// supported via VerticalRl variant +spec:block-formatting-context:9d7cd4 - vertical writing mode
27
// support (VerticalRl, VerticalLr)
28
#[derive(Default)]
29
pub enum LayoutWritingMode {
30
    /// Top-to-bottom block flow, left-to-right inline direction (Latin, etc.).
31
    #[default]
32
    HorizontalTb,
33
    /// Right-to-left block flow, top-to-bottom inline direction (CJK vertical).
34
    VerticalRl,
35
    // +spec:writing-modes:f35728 - vertical-lr writing mode for left-to-right block flow (Manchu,
36
    // Mongolian)
37
    /// Left-to-right block flow, top-to-bottom inline direction (Mongolian).
38
    VerticalLr,
39
}
40

            
41
impl LayoutWritingMode {
42
    /// Returns true if the writing mode is vertical (`VerticalRl` or `VerticalLr`)
43
    #[must_use]
44
873
    pub const fn is_vertical(self) -> bool {
45
873
        matches!(self, Self::VerticalRl | Self::VerticalLr)
46
873
    }
47
}
48

            
49
impl core::fmt::Debug for LayoutWritingMode {
50
1735
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
51
1735
        write!(f, "{}", self.print_as_css_value())
52
1735
    }
53
}
54

            
55
impl core::fmt::Display for LayoutWritingMode {
56
7
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
57
7
        write!(f, "{}", self.print_as_css_value())
58
7
    }
59
}
60

            
61
impl PrintAsCssValue for LayoutWritingMode {
62
1758
    fn print_as_css_value(&self) -> String {
63
1758
        match self {
64
1739
            Self::HorizontalTb => "horizontal-tb".to_string(),
65
10
            Self::VerticalRl => "vertical-rl".to_string(),
66
9
            Self::VerticalLr => "vertical-lr".to_string(),
67
        }
68
1758
    }
69
}
70

            
71
#[cfg(feature = "parser")]
72
#[derive(Clone, PartialEq, Eq)]
73
pub enum LayoutWritingModeParseError<'a> {
74
    InvalidValue(&'a str),
75
}
76

            
77
#[cfg(feature = "parser")]
78
impl_debug_as_display!(LayoutWritingModeParseError<'a>);
79
#[cfg(feature = "parser")]
80
impl_display! { LayoutWritingModeParseError<'a>, {
81
    InvalidValue(e) => format!("Invalid writing-mode value: \"{}\"", e),
82
}}
83

            
84
#[cfg(feature = "parser")]
85
#[derive(Debug, Clone, PartialEq, Eq)]
86
#[repr(C, u8)]
87
pub enum LayoutWritingModeParseErrorOwned {
88
    InvalidValue(AzString),
89
}
90

            
91
#[cfg(feature = "parser")]
92
impl LayoutWritingModeParseError<'_> {
93
    #[must_use]
94
17
    pub fn to_contained(&self) -> LayoutWritingModeParseErrorOwned {
95
17
        match self {
96
17
            LayoutWritingModeParseError::InvalidValue(s) => {
97
17
                LayoutWritingModeParseErrorOwned::InvalidValue((*s).to_string().into())
98
            }
99
        }
100
17
    }
101
}
102

            
103
#[cfg(feature = "parser")]
104
impl LayoutWritingModeParseErrorOwned {
105
    #[must_use]
106
17
    pub fn to_shared(&self) -> LayoutWritingModeParseError<'_> {
107
17
        match self {
108
17
            Self::InvalidValue(s) => LayoutWritingModeParseError::InvalidValue(s.as_str()),
109
        }
110
17
    }
111
}
112

            
113
#[cfg(feature = "parser")]
114
/// # Errors
115
///
116
/// Returns an error if `input` is not a valid CSS `writing-mode` value.
117
120
pub fn parse_layout_writing_mode(
118
120
    input: &str,
119
120
) -> Result<LayoutWritingMode, LayoutWritingModeParseError<'_>> {
120
120
    let input = input.trim();
121
120
    match input {
122
120
        "horizontal-tb" => Ok(LayoutWritingMode::HorizontalTb),
123
115
        "vertical-rl" => Ok(LayoutWritingMode::VerticalRl),
124
        // +spec:writing-modes:23147f - SVG1.1 tb-lr maps to vertical-lr
125
68
        "vertical-lr" | "tb-lr" => Ok(LayoutWritingMode::VerticalLr),
126
62
        _ => Err(LayoutWritingModeParseError::InvalidValue(input)),
127
    }
128
120
}
129

            
130
// --- clear (LayoutClear) ---
131

            
132
/// Represents a `clear` attribute
133
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
134
#[repr(C)]
135
#[derive(Default)]
136
pub enum LayoutClear {
137
    /// No clearing; element is not moved below preceding floats.
138
    #[default]
139
    None,
140
    /// Element is moved below preceding left floats.
141
    Left,
142
    /// Element is moved below preceding right floats.
143
    Right,
144
    /// Element is moved below all preceding floats.
145
    Both,
146
}
147

            
148
impl core::fmt::Debug for LayoutClear {
149
39060
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
150
39060
        write!(f, "{}", self.print_as_css_value())
151
39060
    }
152
}
153

            
154
impl core::fmt::Display for LayoutClear {
155
10
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
156
10
        write!(f, "{}", self.print_as_css_value())
157
10
    }
158
}
159

            
160
impl PrintAsCssValue for LayoutClear {
161
39087
    fn print_as_css_value(&self) -> String {
162
39087
        match self {
163
38944
            Self::None => "none".to_string(),
164
73
            Self::Left => "left".to_string(),
165
34
            Self::Right => "right".to_string(),
166
36
            Self::Both => "both".to_string(),
167
        }
168
39087
    }
169
}
170

            
171
#[cfg(feature = "parser")]
172
#[derive(Clone, PartialEq, Eq)]
173
pub enum LayoutClearParseError<'a> {
174
    InvalidValue(&'a str),
175
}
176

            
177
#[cfg(feature = "parser")]
178
impl_debug_as_display!(LayoutClearParseError<'a>);
179
#[cfg(feature = "parser")]
180
impl_display! { LayoutClearParseError<'a>, {
181
    InvalidValue(e) => format!("Invalid clear value: \"{}\"", e),
182
}}
183

            
184
#[cfg(feature = "parser")]
185
#[derive(Debug, Clone, PartialEq, Eq)]
186
#[repr(C, u8)]
187
pub enum LayoutClearParseErrorOwned {
188
    InvalidValue(AzString),
189
}
190

            
191
#[cfg(feature = "parser")]
192
impl LayoutClearParseError<'_> {
193
    #[must_use]
194
31
    pub fn to_contained(&self) -> LayoutClearParseErrorOwned {
195
31
        match self {
196
31
            LayoutClearParseError::InvalidValue(s) => {
197
31
                LayoutClearParseErrorOwned::InvalidValue((*s).to_string().into())
198
            }
199
        }
200
31
    }
201
}
202

            
203
#[cfg(feature = "parser")]
204
impl LayoutClearParseErrorOwned {
205
    #[must_use]
206
31
    pub fn to_shared(&self) -> LayoutClearParseError<'_> {
207
31
        match self {
208
31
            Self::InvalidValue(s) => LayoutClearParseError::InvalidValue(s.as_str()),
209
        }
210
31
    }
211
}
212

            
213
#[cfg(feature = "parser")]
214
/// # Errors
215
///
216
/// Returns an error if `input` is not a valid CSS `clear` value.
217
178
pub fn parse_layout_clear(input: &str) -> Result<LayoutClear, LayoutClearParseError<'_>> {
218
178
    let input = input.trim();
219
178
    match input {
220
178
        "none" => Ok(LayoutClear::None),
221
173
        "left" => Ok(LayoutClear::Left),
222
117
        "right" => Ok(LayoutClear::Right),
223
100
        "both" => Ok(LayoutClear::Both),
224
67
        _ => Err(LayoutClearParseError::InvalidValue(input)),
225
    }
226
178
}
227

            
228
#[cfg(all(test, feature = "parser"))]
229
mod tests {
230
    use super::*;
231

            
232
    // LayoutWritingMode tests
233
    #[test]
234
1
    fn test_parse_writing_mode_horizontal_tb() {
235
1
        assert_eq!(
236
1
            parse_layout_writing_mode("horizontal-tb").unwrap(),
237
            LayoutWritingMode::HorizontalTb
238
        );
239
1
    }
240

            
241
    #[test]
242
1
    fn test_parse_writing_mode_vertical_rl() {
243
1
        assert_eq!(
244
1
            parse_layout_writing_mode("vertical-rl").unwrap(),
245
            LayoutWritingMode::VerticalRl
246
        );
247
1
    }
248

            
249
    #[test]
250
1
    fn test_parse_writing_mode_vertical_lr() {
251
1
        assert_eq!(
252
1
            parse_layout_writing_mode("vertical-lr").unwrap(),
253
            LayoutWritingMode::VerticalLr
254
        );
255
1
    }
256

            
257
    #[test]
258
1
    fn test_parse_writing_mode_invalid() {
259
1
        assert!(parse_layout_writing_mode("invalid").is_err());
260
1
        assert!(parse_layout_writing_mode("horizontal").is_err());
261
1
    }
262

            
263
    #[test]
264
1
    fn test_parse_writing_mode_whitespace() {
265
1
        assert_eq!(
266
1
            parse_layout_writing_mode("  vertical-rl  ").unwrap(),
267
            LayoutWritingMode::VerticalRl
268
        );
269
1
    }
270

            
271
    // LayoutClear tests
272
    #[test]
273
1
    fn test_parse_layout_clear_none() {
274
1
        assert_eq!(parse_layout_clear("none").unwrap(), LayoutClear::None);
275
1
    }
276

            
277
    #[test]
278
1
    fn test_parse_layout_clear_left() {
279
1
        assert_eq!(parse_layout_clear("left").unwrap(), LayoutClear::Left);
280
1
    }
281

            
282
    #[test]
283
1
    fn test_parse_layout_clear_right() {
284
1
        assert_eq!(parse_layout_clear("right").unwrap(), LayoutClear::Right);
285
1
    }
286

            
287
    #[test]
288
1
    fn test_parse_layout_clear_both() {
289
1
        assert_eq!(parse_layout_clear("both").unwrap(), LayoutClear::Both);
290
1
    }
291

            
292
    #[test]
293
1
    fn test_parse_layout_clear_invalid() {
294
1
        assert!(parse_layout_clear("invalid").is_err());
295
1
        assert!(parse_layout_clear("all").is_err());
296
1
    }
297

            
298
    #[test]
299
1
    fn test_parse_layout_clear_whitespace() {
300
1
        assert_eq!(parse_layout_clear("  both  ").unwrap(), LayoutClear::Both);
301
1
    }
302

            
303
    // Print tests
304
    #[test]
305
1
    fn test_print_writing_mode() {
306
1
        assert_eq!(
307
1
            LayoutWritingMode::HorizontalTb.print_as_css_value(),
308
            "horizontal-tb"
309
        );
310
1
        assert_eq!(
311
1
            LayoutWritingMode::VerticalRl.print_as_css_value(),
312
            "vertical-rl"
313
        );
314
1
        assert_eq!(
315
1
            LayoutWritingMode::VerticalLr.print_as_css_value(),
316
            "vertical-lr"
317
        );
318
1
    }
319

            
320
    #[test]
321
1
    fn test_print_layout_clear() {
322
1
        assert_eq!(LayoutClear::None.print_as_css_value(), "none");
323
1
        assert_eq!(LayoutClear::Left.print_as_css_value(), "left");
324
1
        assert_eq!(LayoutClear::Right.print_as_css_value(), "right");
325
1
        assert_eq!(LayoutClear::Both.print_as_css_value(), "both");
326
1
    }
327
}
328

            
329
#[cfg(test)]
330
mod autotest_generated {
331
    use super::*;
332

            
333
    const ALL_WRITING_MODES: [LayoutWritingMode; 3] = [
334
        LayoutWritingMode::HorizontalTb,
335
        LayoutWritingMode::VerticalRl,
336
        LayoutWritingMode::VerticalLr,
337
    ];
338

            
339
    const ALL_CLEARS: [LayoutClear; 4] = [
340
        LayoutClear::None,
341
        LayoutClear::Left,
342
        LayoutClear::Right,
343
        LayoutClear::Both,
344
    ];
345

            
346
    // --- LayoutWritingMode::is_vertical (predicate) ---
347

            
348
    #[test]
349
    fn is_vertical_known_true_and_false() {
350
        assert!(!LayoutWritingMode::HorizontalTb.is_vertical());
351
        assert!(LayoutWritingMode::VerticalRl.is_vertical());
352
        assert!(LayoutWritingMode::VerticalLr.is_vertical());
353
    }
354

            
355
    #[test]
356
    fn is_vertical_default_is_horizontal() {
357
        assert!(!LayoutWritingMode::default().is_vertical());
358
        assert_eq!(
359
            LayoutWritingMode::default(),
360
            LayoutWritingMode::HorizontalTb
361
        );
362
    }
363

            
364
    #[test]
365
    fn is_vertical_is_const_evaluable() {
366
        const HORIZONTAL: bool = LayoutWritingMode::HorizontalTb.is_vertical();
367
        const VERTICAL: bool = LayoutWritingMode::VerticalRl.is_vertical();
368
        const _: () = assert!(!HORIZONTAL && VERTICAL);
369
    }
370

            
371
    #[test]
372
    fn is_vertical_agrees_with_css_keyword_prefix() {
373
        // Invariant: is_vertical() must agree with the serialized keyword, so the
374
        // predicate can never drift away from the CSS value it claims to describe.
375
        for mode in ALL_WRITING_MODES {
376
            let css = mode.print_as_css_value();
377
            assert_eq!(
378
                mode.is_vertical(),
379
                css.starts_with("vertical-"),
380
                "is_vertical() disagrees with keyword {css}"
381
            );
382
        }
383
    }
384

            
385
    #[test]
386
    fn is_vertical_is_pure_and_does_not_consume() {
387
        // `self`-by-value on a Copy enum: repeated calls must be stable.
388
        let mode = LayoutWritingMode::VerticalLr;
389
        assert!(mode.is_vertical());
390
        assert!(mode.is_vertical());
391
        assert_eq!(mode, LayoutWritingMode::VerticalLr);
392
    }
393

            
394
    // --- Debug / Display / PrintAsCssValue (serializers) ---
395

            
396
    #[test]
397
    fn writing_mode_debug_display_and_css_value_all_agree() {
398
        for mode in ALL_WRITING_MODES {
399
            let css = mode.print_as_css_value();
400
            assert!(!css.is_empty());
401
            assert_eq!(format!("{mode:?}"), css);
402
            assert_eq!(format!("{mode}"), css);
403
        }
404
    }
405

            
406
    #[test]
407
    fn clear_debug_display_and_css_value_all_agree() {
408
        for clear in ALL_CLEARS {
409
            let css = clear.print_as_css_value();
410
            assert!(!css.is_empty());
411
            assert_eq!(format!("{clear:?}"), css);
412
            assert_eq!(format!("{clear}"), css);
413
        }
414
    }
415

            
416
    #[test]
417
    fn serializing_defaults_does_not_panic() {
418
        assert_eq!(
419
            LayoutWritingMode::default().print_as_css_value(),
420
            "horizontal-tb"
421
        );
422
        assert_eq!(LayoutClear::default().print_as_css_value(), "none");
423
    }
424

            
425
    #[test]
426
    fn serialized_keywords_are_distinct() {
427
        // Two variants sharing a keyword would silently collapse on re-parse.
428
        let modes: alloc::collections::BTreeSet<String> = ALL_WRITING_MODES
429
            .iter()
430
            .map(PrintAsCssValue::print_as_css_value)
431
            .collect();
432
        assert_eq!(modes.len(), ALL_WRITING_MODES.len());
433

            
434
        let clears: alloc::collections::BTreeSet<String> = ALL_CLEARS
435
            .iter()
436
            .map(PrintAsCssValue::print_as_css_value)
437
            .collect();
438
        assert_eq!(clears.len(), ALL_CLEARS.len());
439
    }
440

            
441
    #[test]
442
    fn display_impl_ignores_width_and_precision_flags() {
443
        // The Display impl forwards through `write!(f, "{}", String)`, which writes
444
        // straight to the underlying buffer and drops the outer formatter's flags.
445
        // Padding/truncation therefore does NOT apply — pinning the real behaviour so
446
        // callers never build a stylesheet assuming `{:>20}` aligns.
447
        assert_eq!(format!("{:>20}", LayoutClear::Both), "both");
448
        assert_eq!(format!("{:.2}", LayoutClear::Both), "both");
449
        assert_eq!(
450
            format!("{:>20}", LayoutWritingMode::VerticalRl),
451
            "vertical-rl"
452
        );
453
    }
454

            
455
    // --- ordering / hashing invariants on the plain enums ---
456

            
457
    #[test]
458
    fn writing_mode_ord_follows_declaration_order() {
459
        assert!(LayoutWritingMode::HorizontalTb < LayoutWritingMode::VerticalRl);
460
        assert!(LayoutWritingMode::VerticalRl < LayoutWritingMode::VerticalLr);
461
    }
462

            
463
    #[test]
464
    fn clear_ord_follows_declaration_order() {
465
        assert!(LayoutClear::None < LayoutClear::Left);
466
        assert!(LayoutClear::Left < LayoutClear::Right);
467
        assert!(LayoutClear::Right < LayoutClear::Both);
468
    }
469

            
470
    #[test]
471
    fn equal_values_hash_equally() {
472
        use core::hash::{Hash, Hasher};
473
        use std::collections::hash_map::DefaultHasher;
474

            
475
        fn hash_of<T: Hash>(value: &T) -> u64 {
476
            let mut hasher = DefaultHasher::new();
477
            value.hash(&mut hasher);
478
            hasher.finish()
479
        }
480

            
481
        // Hash must agree with Eq: independently-constructed equal values hash alike.
482
        assert_eq!(
483
            hash_of(&LayoutWritingMode::VerticalRl),
484
            hash_of(&ALL_WRITING_MODES[1])
485
        );
486
        assert_eq!(hash_of(&LayoutClear::Both), hash_of(&ALL_CLEARS[3]));
487
        assert_ne!(
488
            hash_of(&LayoutWritingMode::HorizontalTb),
489
            hash_of(&LayoutWritingMode::VerticalRl)
490
        );
491
    }
492

            
493
    // --- parsers ---
494

            
495
    #[cfg(feature = "parser")]
496
    #[test]
497
    fn parse_writing_mode_valid_minimal() {
498
        assert_eq!(
499
            parse_layout_writing_mode("horizontal-tb"),
500
            Ok(LayoutWritingMode::HorizontalTb)
501
        );
502
    }
503

            
504
    #[cfg(feature = "parser")]
505
    #[test]
506
    fn parse_writing_mode_accepts_svg_tb_lr_alias() {
507
        // SVG 1.1 `tb-lr` is an accepted alias for `vertical-lr`.
508
        assert_eq!(
509
            parse_layout_writing_mode("tb-lr"),
510
            Ok(LayoutWritingMode::VerticalLr)
511
        );
512
        // ...but the other SVG 1.1 writing-mode aliases are NOT mapped.
513
        for unsupported in ["lr", "lr-tb", "rl", "rl-tb", "tb"] {
514
            assert!(
515
                parse_layout_writing_mode(unsupported).is_err(),
516
                "{unsupported} unexpectedly parsed"
517
            );
518
        }
519
    }
520

            
521
    #[cfg(feature = "parser")]
522
    #[test]
523
    fn parse_clear_valid_minimal() {
524
        assert_eq!(parse_layout_clear("none"), Ok(LayoutClear::None));
525
    }
526

            
527
    #[cfg(feature = "parser")]
528
    #[test]
529
    fn parse_empty_input_errors_with_empty_payload() {
530
        let err = parse_layout_writing_mode("").unwrap_err();
531
        assert_eq!(err, LayoutWritingModeParseError::InvalidValue(""));
532
        let err = parse_layout_clear("").unwrap_err();
533
        assert_eq!(err, LayoutClearParseError::InvalidValue(""));
534
    }
535

            
536
    #[cfg(feature = "parser")]
537
    #[test]
538
    fn parse_whitespace_only_input_errors_after_trimming() {
539
        for blank in ["   ", "\t\n", "\r\n\r\n", "\u{0c}", " \t \n \r "] {
540
            assert_eq!(
541
                parse_layout_writing_mode(blank).unwrap_err(),
542
                LayoutWritingModeParseError::InvalidValue(""),
543
                "whitespace {blank:?} should trim to the empty payload"
544
            );
545
            assert_eq!(
546
                parse_layout_clear(blank).unwrap_err(),
547
                LayoutClearParseError::InvalidValue("")
548
            );
549
        }
550
    }
551

            
552
    #[cfg(feature = "parser")]
553
    #[test]
554
    fn parse_garbage_returns_err_and_echoes_trimmed_input() {
555
        for garbage in [
556
            "invalid",
557
            "!!!",
558
            "\u{0}",
559
            "none\u{0}",
560
            "{}[]();",
561
            "-",
562
            "--",
563
            "vertical-",
564
            "-rl",
565
            "vertical rl",
566
            "vertical - rl",
567
            "vertical_rl",
568
            "verticalrl",
569
        ] {
570
            let err = parse_layout_writing_mode(garbage).unwrap_err();
571
            assert_eq!(
572
                err,
573
                LayoutWritingModeParseError::InvalidValue(garbage.trim())
574
            );
575
            let err = parse_layout_clear(garbage).unwrap_err();
576
            assert_eq!(err, LayoutClearParseError::InvalidValue(garbage.trim()));
577
        }
578
    }
579

            
580
    #[cfg(feature = "parser")]
581
    #[test]
582
    fn parse_rejects_css_wide_keywords() {
583
        // These are handled (if at all) by the caller in property.rs, not here —
584
        // the value parser itself must not silently accept them as keywords.
585
        for wide in ["inherit", "initial", "unset", "revert", "revert-layer"] {
586
            assert!(parse_layout_writing_mode(wide).is_err(), "{wide} accepted");
587
            assert!(parse_layout_clear(wide).is_err(), "{wide} accepted");
588
        }
589
    }
590

            
591
    #[cfg(feature = "parser")]
592
    #[test]
593
    fn parse_is_ascii_case_sensitive() {
594
        // NOTE: CSS keywords are ASCII case-insensitive per css-values-4, but these
595
        // parsers match case-sensitively. Locking in the CURRENT behaviour; see the
596
        // report for the spec deviation.
597
        for upper in ["HORIZONTAL-TB", "Vertical-Rl", "VERTICAL-LR", "TB-LR"] {
598
            assert!(
599
                parse_layout_writing_mode(upper).is_err(),
600
                "{upper} parsed — case-insensitive matching was added, update this test"
601
            );
602
        }
603
        for upper in ["NONE", "Left", "RIGHT", "Both"] {
604
            assert!(
605
                parse_layout_clear(upper).is_err(),
606
                "{upper} parsed — case-insensitive matching was added, update this test"
607
            );
608
        }
609
    }
610

            
611
    #[cfg(feature = "parser")]
612
    #[test]
613
    fn parse_leading_trailing_ascii_whitespace_is_trimmed() {
614
        assert_eq!(
615
            parse_layout_writing_mode("  vertical-rl  "),
616
            Ok(LayoutWritingMode::VerticalRl)
617
        );
618
        assert_eq!(
619
            parse_layout_writing_mode("\t\nvertical-lr\r\n"),
620
            Ok(LayoutWritingMode::VerticalLr)
621
        );
622
        assert_eq!(parse_layout_clear("\t both \n"), Ok(LayoutClear::Both));
623
    }
624

            
625
    #[cfg(feature = "parser")]
626
    #[test]
627
    fn parse_rejects_trailing_junk_after_valid_keyword() {
628
        for junk in [
629
            "both;garbage",
630
            "both;",
631
            "both both",
632
            "both!important",
633
            "both,",
634
        ] {
635
            assert_eq!(
636
                parse_layout_clear(junk).unwrap_err(),
637
                LayoutClearParseError::InvalidValue(junk.trim())
638
            );
639
        }
640
        assert!(parse_layout_writing_mode("vertical-rl;garbage").is_err());
641
    }
642

            
643
    #[cfg(feature = "parser")]
644
    #[test]
645
    fn parse_trims_unicode_whitespace_beyond_css_whitespace() {
646
        // `str::trim` uses the Unicode White_Space property, which is a SUPERSET of
647
        // CSS whitespace (space, tab, LF, CR, FF). So NBSP-padded keywords parse
648
        // here even though a spec-conformant CSS tokenizer would reject them.
649
        // Asserting the CURRENT behaviour; see the report.
650
        assert_eq!(
651
            parse_layout_clear("\u{00a0}both\u{00a0}"),
652
            Ok(LayoutClear::Both)
653
        );
654
        assert_eq!(
655
            parse_layout_writing_mode("\u{2003}vertical-rl\u{2003}"),
656
            Ok(LayoutWritingMode::VerticalRl)
657
        );
658
        // Zero-width space and BOM are NOT White_Space, so they stay in the payload.
659
        assert_eq!(
660
            parse_layout_clear("\u{200b}both").unwrap_err(),
661
            LayoutClearParseError::InvalidValue("\u{200b}both")
662
        );
663
        assert_eq!(
664
            parse_layout_clear("\u{feff}both").unwrap_err(),
665
            LayoutClearParseError::InvalidValue("\u{feff}both")
666
        );
667
    }
668

            
669
    #[cfg(feature = "parser")]
670
    #[test]
671
    fn parse_unicode_input_does_not_panic_on_char_boundaries() {
672
        for weird in [
673
            "\u{1F600}",
674
            "🙂🙃",
675
            "e\u{0301}",    // combining acute
676
            "n\u{0303}one", // combining tilde inside a keyword
677
            "none",     // fullwidth
678
            "نص",           // RTL
679
            "\u{202E}both", // RTL override
680
            "both\u{0301}",
681
        ] {
682
            let err = parse_layout_writing_mode(weird).unwrap_err();
683
            assert_eq!(err, LayoutWritingModeParseError::InvalidValue(weird.trim()));
684
            let err = parse_layout_clear(weird).unwrap_err();
685
            assert_eq!(err, LayoutClearParseError::InvalidValue(weird.trim()));
686
            // The borrowed payload must still be valid UTF-8 we can round-trip.
687
            assert_eq!(err.to_contained().to_shared(), err);
688
        }
689
    }
690

            
691
    #[cfg(feature = "parser")]
692
    #[test]
693
    fn parse_boundary_numeric_strings_are_rejected() {
694
        for numeric in [
695
            "0",
696
            "-0",
697
            "0.0",
698
            "NaN",
699
            "nan",
700
            "inf",
701
            "-inf",
702
            "infinity",
703
            "1e999",
704
            "-1e-999",
705
            "9223372036854775807",  // i64::MAX
706
            "-9223372036854775808", // i64::MIN
707
            "18446744073709551616", // u64::MAX + 1
708
            "179769313486231570000000000000000000000000000000000000000000000000000000000000000",
709
        ] {
710
            assert!(
711
                parse_layout_writing_mode(numeric).is_err(),
712
                "{numeric} parsed"
713
            );
714
            assert!(parse_layout_clear(numeric).is_err(), "{numeric} parsed");
715
        }
716
    }
717

            
718
    #[cfg(feature = "parser")]
719
    #[test]
720
    fn parse_extremely_long_input_does_not_panic_or_hang() {
721
        let long = "a".repeat(1_000_000);
722
        let err = parse_layout_clear(&long).unwrap_err();
723
        assert_eq!(err, LayoutClearParseError::InvalidValue(long.as_str()));
724

            
725
        // A megabyte of whitespace must trim down to the empty payload, not hang.
726
        let blank = " ".repeat(1_000_000);
727
        assert_eq!(
728
            parse_layout_writing_mode(&blank).unwrap_err(),
729
            LayoutWritingModeParseError::InvalidValue("")
730
        );
731

            
732
        // A valid keyword buried in a megabyte of padding still parses.
733
        let padded = format!("{blank}vertical-rl{blank}");
734
        assert_eq!(
735
            parse_layout_writing_mode(&padded),
736
            Ok(LayoutWritingMode::VerticalRl)
737
        );
738

            
739
        // A near-miss keyword repeated: still exactly one Err, no quadratic blowup.
740
        let repeated = "both ".repeat(200_000);
741
        assert!(parse_layout_clear(&repeated).is_err());
742
    }
743

            
744
    #[cfg(feature = "parser")]
745
    #[test]
746
    fn parse_deeply_nested_input_does_not_stack_overflow() {
747
        let nested = "(".repeat(10_000) + &")".repeat(10_000);
748
        assert!(parse_layout_clear(&nested).is_err());
749
        assert!(parse_layout_writing_mode(&nested).is_err());
750

            
751
        let brackets = "[".repeat(10_000);
752
        assert_eq!(
753
            parse_layout_clear(&brackets).unwrap_err(),
754
            LayoutClearParseError::InvalidValue(brackets.as_str())
755
        );
756
    }
757

            
758
    #[cfg(feature = "parser")]
759
    #[test]
760
    fn parse_error_payload_borrows_the_trimmed_slice_not_the_whole_input() {
761
        let input = "   bogus-value   ";
762
        let LayoutClearParseError::InvalidValue(payload) = parse_layout_clear(input).unwrap_err();
763
        // The error echoes the TRIMMED slice, not the raw input.
764
        assert_eq!(payload, "bogus-value");
765
        assert_eq!(payload.len(), 11);
766
        // ...and it is a borrowed subslice of the original buffer, not a copy.
767
        assert!(input.as_ptr() <= payload.as_ptr());
768
    }
769

            
770
    // --- round-trip: serialize -> parse -> same value ---
771

            
772
    #[test]
773
    #[cfg(feature = "parser")]
774
    fn writing_mode_round_trips_through_css_value() {
775
        for mode in ALL_WRITING_MODES {
776
            let css = mode.print_as_css_value();
777
            assert_eq!(
778
                parse_layout_writing_mode(&css),
779
                Ok(mode),
780
                "round-trip {css}"
781
            );
782
            // Display and Debug are the same wire format, so they round-trip too.
783
            assert_eq!(parse_layout_writing_mode(&format!("{mode}")), Ok(mode));
784
            assert_eq!(parse_layout_writing_mode(&format!("{mode:?}")), Ok(mode));
785
        }
786
    }
787

            
788
    #[test]
789
    #[cfg(feature = "parser")]
790
    fn clear_round_trips_through_css_value() {
791
        for clear in ALL_CLEARS {
792
            let css = clear.print_as_css_value();
793
            assert_eq!(parse_layout_clear(&css), Ok(clear), "round-trip {css}");
794
            assert_eq!(parse_layout_clear(&format!("{clear}")), Ok(clear));
795
            assert_eq!(parse_layout_clear(&format!("{clear:?}")), Ok(clear));
796
        }
797
    }
798

            
799
    // --- error getters: to_contained / to_shared ---
800

            
801
    #[cfg(feature = "parser")]
802
    #[test]
803
    fn writing_mode_error_to_contained_preserves_the_value() {
804
        let err = parse_layout_writing_mode("bogus").unwrap_err();
805
        assert_eq!(
806
            err.to_contained(),
807
            LayoutWritingModeParseErrorOwned::InvalidValue("bogus".into())
808
        );
809
    }
810

            
811
    #[cfg(feature = "parser")]
812
    #[test]
813
    fn clear_error_to_contained_preserves_the_value() {
814
        let err = parse_layout_clear("bogus").unwrap_err();
815
        assert_eq!(
816
            err.to_contained(),
817
            LayoutClearParseErrorOwned::InvalidValue("bogus".into())
818
        );
819
    }
820

            
821
    #[cfg(feature = "parser")]
822
    #[test]
823
    fn error_to_contained_outlives_the_parsed_input() {
824
        // The whole point of to_contained(): escape the input's lifetime.
825
        let owned = {
826
            let scratch = String::from("temporary-garbage");
827
            parse_layout_clear(&scratch).unwrap_err().to_contained()
828
        };
829
        assert_eq!(
830
            owned,
831
            LayoutClearParseErrorOwned::InvalidValue("temporary-garbage".into())
832
        );
833
        assert_eq!(
834
            owned.to_shared(),
835
            LayoutClearParseError::InvalidValue("temporary-garbage")
836
        );
837
    }
838

            
839
    #[cfg(feature = "parser")]
840
    #[test]
841
    fn error_shared_owned_round_trip_is_lossless() {
842
        for value in [
843
            "",
844
            " ",
845
            "\u{0}",
846
            "🙂",
847
            "e\u{0301}",
848
            "quote\"inside",
849
            "back\\slash",
850
            "new\nline",
851
        ] {
852
            let shared = LayoutClearParseError::InvalidValue(value);
853
            let owned = shared.to_contained();
854
            assert_eq!(owned.to_shared(), shared, "clear round-trip {value:?}");
855
            // to_contained -> to_shared -> to_contained is idempotent.
856
            assert_eq!(owned.to_shared().to_contained(), owned);
857

            
858
            let shared = LayoutWritingModeParseError::InvalidValue(value);
859
            let owned = shared.to_contained();
860
            assert_eq!(
861
                owned.to_shared(),
862
                shared,
863
                "writing-mode round-trip {value:?}"
864
            );
865
            assert_eq!(owned.to_shared().to_contained(), owned);
866
        }
867
    }
868

            
869
    #[cfg(feature = "parser")]
870
    #[test]
871
    fn error_round_trip_survives_a_huge_payload() {
872
        let huge = "x".repeat(100_000);
873
        let shared = LayoutClearParseError::InvalidValue(huge.as_str());
874
        let owned = shared.to_contained();
875
        let LayoutClearParseError::InvalidValue(back) = owned.to_shared();
876
        assert_eq!(back.len(), 100_000);
877
        assert_eq!(back, huge.as_str());
878
    }
879

            
880
    #[cfg(feature = "parser")]
881
    #[test]
882
    fn error_to_shared_on_default_azstring_does_not_panic() {
883
        // AzString::default() is the empty &'static str — the degenerate case for
884
        // the unchecked from_utf8 inside AzString::as_str().
885
        let owned = LayoutClearParseErrorOwned::InvalidValue(AzString::default());
886
        assert_eq!(owned.to_shared(), LayoutClearParseError::InvalidValue(""));
887

            
888
        let owned = LayoutWritingModeParseErrorOwned::InvalidValue(AzString::default());
889
        assert_eq!(
890
            owned.to_shared(),
891
            LayoutWritingModeParseError::InvalidValue("")
892
        );
893
    }
894

            
895
    #[cfg(feature = "parser")]
896
    #[test]
897
    fn error_display_and_debug_include_the_offending_value() {
898
        let err = parse_layout_writing_mode("  bogus  ").unwrap_err();
899
        let display = format!("{err}");
900
        assert_eq!(display, "Invalid writing-mode value: \"bogus\"");
901
        // impl_debug_as_display!: Debug must be identical to Display.
902
        assert_eq!(format!("{err:?}"), display);
903

            
904
        let err = parse_layout_clear("bogus").unwrap_err();
905
        let display = format!("{err}");
906
        assert_eq!(display, "Invalid clear value: \"bogus\"");
907
        assert_eq!(format!("{err:?}"), display);
908
    }
909

            
910
    #[cfg(feature = "parser")]
911
    #[test]
912
    fn error_display_does_not_panic_on_empty_or_unicode_payloads() {
913
        for value in ["", "\u{0}", "🙂", "\u{202E}"] {
914
            let err = LayoutClearParseError::InvalidValue(value);
915
            assert!(format!("{err}").contains(value));
916
            let owned = err.to_contained();
917
            assert!(format!("{:?}", owned.to_shared()).contains(value));
918
        }
919
    }
920
}