hyperchad_color 0.4.0

HyperChad color package
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! A lightweight color parsing and manipulation library.
//!
//! This crate provides a simple [`Color`] type representing RGB/RGBA colors with 8-bit channels,
//! along with utilities for parsing hex color strings in various formats.
//!
//! # Features
//!
//! * Parse hex color strings in multiple formats (RGB, RGBA, RRGGBB, RRGGBBAA)
//! * Support for optional alpha channel
//! * Conversion to/from hex strings
//! * Optional integration with egui (via `egui` feature)
//! * Optional property testing support (via `arb` feature)
//! * Optional serialization support (via `serde` feature)
//!
//! # Examples
//!
//! ```rust
//! use hyperchad_color::Color;
//!
//! // Parse a hex color string
//! let color = Color::from_hex("#FF5733");
//! assert_eq!(color.r, 255);
//! assert_eq!(color.g, 87);
//! assert_eq!(color.b, 51);
//!
//! // Use predefined constants
//! let black = Color::BLACK;
//! let white = Color::WHITE;
//!
//! // Convert back to hex string
//! assert_eq!(color.to_string(), "#FF5733");
//! ```

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

/// Re-export of the `color_from_hex!` macro from the `color-hex` crate.
///
/// This macro provides compile-time hex color parsing. Use it when you need
/// to parse hex colors at compile time rather than runtime.
///
/// # Examples
///
/// ```rust
/// use hyperchad_color::color_from_hex;
///
/// let color = color_from_hex!("#FF5733");
/// ```
pub use color_hex::color_from_hex;
use thiserror::Error;

/// Property testing support via proptest.
///
/// This module provides an [`Arbitrary`] implementation for [`Color`],
/// enabling property-based testing with the [`proptest`] crate.
///
/// [`Arbitrary`]: proptest::arbitrary::Arbitrary
/// [`proptest`]: https://docs.rs/proptest/latest/proptest/
#[cfg(feature = "arb")]
pub mod arb;

/// Errors that can occur when parsing a hex color string.
#[derive(Debug, Error)]
pub enum ParseHexError {
    /// An invalid hex character was encountered at the specified index.
    #[error("Invalid character at index {0} '{1}'")]
    InvalidCharacter(usize, char),
    /// A non-ASCII character was encountered at the specified index.
    #[error("Invalid non-ASCII character at index {0}")]
    InvalidNonAsciiCharacter(usize),
    /// The hex string is longer than 8 characters (excluding '#' prefix and whitespace).
    #[error("Hex string too long")]
    StringTooLong,
    /// The hex string has an invalid length (e.g., incomplete alpha channel).
    #[error("Hex string invalid length")]
    InvalidLength,
}

/// Represents an RGB or RGBA color with 8-bit channels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Color {
    /// Red channel (0-255).
    pub r: u8,
    /// Green channel (0-255).
    pub g: u8,
    /// Blue channel (0-255).
    pub b: u8,
    /// Optional alpha channel (0-255). `None` represents fully opaque.
    pub a: Option<u8>,
}

impl Color {
    /// Black color constant (RGB: 0, 0, 0).
    pub const BLACK: Self = Self {
        r: 0,
        g: 0,
        b: 0,
        a: None,
    };

    /// White color constant (RGB: 255, 255, 255).
    pub const WHITE: Self = Self {
        r: 255,
        g: 255,
        b: 255,
        a: None,
    };

    /// Parses a hex string (a-f/A-F/0-9) as a `Color` from the &str,
    /// ignoring surrounding whitespace.
    ///
    /// Accepts hex strings in formats: RGB (3 chars), RGBA (4 chars),
    /// RRGGBB (6 chars), or RRGGBBAA (8 chars). The '#' prefix is optional.
    ///
    /// # Errors
    ///
    /// * `ParseHexError::InvalidCharacter` - If a non-hex, non-whitespace ASCII character is encountered.
    /// * `ParseHexError::InvalidNonAsciiCharacter` - If a non-ASCII character is encountered.
    /// * `ParseHexError::StringTooLong` - If the hex string is longer than 8 characters (excluding '#' and whitespace).
    /// * `ParseHexError::InvalidLength` - If the hex string has an incomplete alpha channel (7 characters).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hyperchad_color::Color;
    ///
    /// let parsed = Color::try_from_hex("#0F8").expect("short RGB should parse");
    /// assert_eq!(parsed.r, 0x00);
    /// assert_eq!(parsed.g, 0xFF);
    /// assert_eq!(parsed.b, 0x88);
    /// assert_eq!(parsed.a, None);
    /// ```
    #[allow(clippy::many_single_char_names)]
    pub fn try_from_hex(hex: &str) -> Result<Self, ParseHexError> {
        let mut short_r = 0;
        let mut short_g = 0;
        let mut short_b = 0;
        let mut short_a = 0;
        let mut three_chars = false;
        let mut four_chars = false;

        let mut r = 0;
        let mut g = 0;
        let mut b = 0;
        let mut maybe_a = None;
        let mut a = None;

        let hex = hex.strip_prefix('#').unwrap_or(hex);

        for (i, value) in hex.trim().chars().enumerate().map(|(i, x)| {
            (
                i,
                match x {
                    '0'..='9' => Ok(x as u8 - 48),
                    'A'..='F' => Ok(x as u8 - 55),
                    'a'..='f' => Ok(x as u8 - 87),
                    c if c.is_ascii() => Err(ParseHexError::InvalidCharacter(i, x)),
                    _ => Err(ParseHexError::InvalidNonAsciiCharacter(i)),
                },
            )
        }) {
            let value = value?;
            match i {
                0 => {
                    short_r = value;
                    r = value << 4;
                }
                1 => {
                    short_g = value;
                    r += value;
                }
                2 => {
                    three_chars = true;
                    short_b = value;
                    g = value << 4;
                }
                3 => {
                    three_chars = false;
                    four_chars = true;
                    short_a = value;
                    g += value;
                }
                4 => {
                    four_chars = false;
                    b = value << 4;
                }
                5 => {
                    b += value;
                }
                6 => {
                    maybe_a = Some(value << 4);
                }
                7 => {
                    a = maybe_a.map(|a| a + value);
                }
                _ => {
                    return Err(ParseHexError::StringTooLong);
                }
            }
        }

        moosicbox_assert::assert_or_err!(
            maybe_a.is_none() || a.is_some(),
            ParseHexError::InvalidLength,
        );

        if three_chars {
            r = (short_r << 4) + short_r;
            g = (short_g << 4) + short_g;
            b = (short_b << 4) + short_b;
        }
        if four_chars {
            r = (short_r << 4) + short_r;
            g = (short_g << 4) + short_g;
            b = (short_b << 4) + short_b;
            a = Some((short_a << 4) + short_a);
        }

        Ok(Self { r, g, b, a })
    }

    /// Parses a hex string (a-f/A-F/0-9) as a `Color` from the &str,
    /// ignoring surrounding whitespace.
    ///
    /// # Panics
    ///
    /// * If the input contains invalid hex characters.
    /// * If the input is longer than 8 hex characters (excluding `#` and surrounding whitespace).
    /// * If the input has an invalid length (for example, 7 hex characters).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hyperchad_color::Color;
    ///
    /// let color = Color::from_hex("#336699CC");
    /// assert_eq!(color.r, 0x33);
    /// assert_eq!(color.g, 0x66);
    /// assert_eq!(color.b, 0x99);
    /// assert_eq!(color.a, Some(0xCC));
    /// ```
    #[must_use]
    pub fn from_hex(hex: &str) -> Self {
        Self::try_from_hex(hex).unwrap()
    }
}

/// Converts [`Color`] to [`egui::Color32`].
///
/// If the color has an alpha channel, it creates an RGBA color; otherwise,
/// it creates an opaque RGB color.
#[cfg(feature = "egui")]
impl From<Color> for egui::Color32 {
    fn from(value: Color) -> Self {
        value.a.map_or_else(
            || Self::from_rgb(value.r, value.g, value.b),
            |a| Self::from_rgba_unmultiplied(value.r, value.g, value.b, a),
        )
    }
}

/// Converts a reference to [`Color`] to [`egui::Color32`].
///
/// If the color has an alpha channel, it creates an RGBA color; otherwise,
/// it creates an opaque RGB color.
#[cfg(feature = "egui")]
impl From<&Color> for egui::Color32 {
    fn from(value: &Color) -> Self {
        value.a.map_or_else(
            || Self::from_rgb(value.r, value.g, value.b),
            |a| Self::from_rgba_unmultiplied(value.r, value.g, value.b, a),
        )
    }
}

/// Converts [`Color`] to a hex string representation.
///
/// Outputs uppercase hex format with '#' prefix:
/// * RGB colors: `#RRGGBB` (6 characters)
/// * RGBA colors: `#RRGGBBAA` (8 characters)
impl std::fmt::Display for Color {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(a) = self.a {
            f.write_fmt(format_args!(
                "#{:02X}{:02X}{:02X}{:02X}",
                self.r, self.g, self.b, a
            ))
        } else {
            f.write_fmt(format_args!("#{:02X}{:02X}{:02X}", self.r, self.g, self.b))
        }
    }
}

/// Converts a hex string to [`Color`].
///
/// # Panics
///
/// * If the string contains invalid hex characters or has an invalid format.
impl From<&str> for Color {
    fn from(s: &str) -> Self {
        Self::from_hex(s)
    }
}

/// Converts an owned [`String`] containing a hex color to [`Color`].
///
/// # Panics
///
/// * If the string contains invalid hex characters or has an invalid format.
impl From<String> for Color {
    fn from(s: String) -> Self {
        Self::from_hex(&s)
    }
}

/// Converts a reference to [`String`] containing a hex color to [`Color`].
///
/// # Panics
///
/// * If the string contains invalid hex characters or has an invalid format.
impl From<&String> for Color {
    fn from(s: &String) -> Self {
        Self::from_hex(s)
    }
}

#[cfg(test)]
mod test {
    use pretty_assertions::assert_eq;

    use crate::Color;

    #[test_log::test]
    fn can_parse_rgb_hex_string_to_color() {
        assert_eq!(
            Color::from_hex("#010203"),
            Color {
                r: 1,
                g: 2,
                b: 3,
                a: None
            }
        );
    }

    #[test_log::test]
    fn can_parse_rgba_hex_string_to_color() {
        assert_eq!(
            Color::from_hex("#01020304"),
            Color {
                r: 1,
                g: 2,
                b: 3,
                a: Some(4)
            }
        );
    }

    #[test_log::test]
    fn can_display_small_rgb_as_hex_string() {
        assert_eq!(
            Color {
                r: 1,
                g: 2,
                b: 3,
                a: None
            }
            .to_string(),
            "#010203".to_string(),
        );
    }

    #[test_log::test]
    fn can_display_large_rgb_as_hex_string() {
        assert_eq!(
            Color {
                r: 255,
                g: 2,
                b: 254,
                a: None
            }
            .to_string(),
            "#FF02FE".to_string(),
        );
    }

    #[test_log::test]
    fn can_display_small_rgba_as_hex_string() {
        assert_eq!(
            Color {
                r: 1,
                g: 2,
                b: 3,
                a: Some(4)
            }
            .to_string(),
            "#01020304".to_string(),
        );
    }

    #[test_log::test]
    fn can_display_large_rgba_as_hex_string() {
        assert_eq!(
            Color {
                r: 255,
                g: 2,
                b: 254,
                a: Some(4)
            }
            .to_string(),
            "#FF02FE04".to_string(),
        );
    }

    // Short hex format tests (3 and 4 character formats)
    #[test_log::test]
    fn can_parse_short_rgb_hex_string() {
        // #ABC should expand to #AABBCC
        assert_eq!(
            Color::from_hex("#ABC"),
            Color {
                r: 0xAA,
                g: 0xBB,
                b: 0xCC,
                a: None
            }
        );
    }

    #[test_log::test]
    fn can_parse_short_rgba_hex_string() {
        // #ABCD should expand to #AABBCCDD
        assert_eq!(
            Color::from_hex("#ABCD"),
            Color {
                r: 0xAA,
                g: 0xBB,
                b: 0xCC,
                a: Some(0xDD)
            }
        );
    }

    #[test_log::test]
    fn can_parse_short_rgb_with_zero_values() {
        // #000 should expand to #000000
        assert_eq!(
            Color::from_hex("#000"),
            Color {
                r: 0,
                g: 0,
                b: 0,
                a: None
            }
        );
    }

    #[test_log::test]
    fn can_parse_short_rgb_with_max_values() {
        // #FFF should expand to #FFFFFF
        assert_eq!(
            Color::from_hex("#FFF"),
            Color {
                r: 255,
                g: 255,
                b: 255,
                a: None
            }
        );
    }

    #[test_log::test]
    fn can_parse_short_rgba_with_zero_alpha() {
        // #ABC0 should expand to #AABBCC00
        assert_eq!(
            Color::from_hex("#ABC0"),
            Color {
                r: 0xAA,
                g: 0xBB,
                b: 0xCC,
                a: Some(0)
            }
        );
    }

    // Error handling tests
    #[test_log::test]
    fn invalid_character_returns_error() {
        let result = Color::try_from_hex("#GGHHII");
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::ParseHexError::InvalidCharacter(idx, ch) => {
                assert_eq!(idx, 0);
                assert_eq!(ch, 'G');
            }
            _ => panic!("Expected InvalidCharacter error"),
        }
    }

    #[test_log::test]
    fn non_ascii_character_returns_error() {
        let result = Color::try_from_hex("#日本語");
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::ParseHexError::InvalidNonAsciiCharacter(idx) => {
                assert_eq!(idx, 0);
            }
            _ => panic!("Expected InvalidNonAsciiCharacter error"),
        }
    }

    #[test_log::test]
    fn string_too_long_returns_error() {
        let result = Color::try_from_hex("#123456789");
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::ParseHexError::StringTooLong => {}
            _ => panic!("Expected StringTooLong error"),
        }
    }

    #[test_log::test]
    fn invalid_length_returns_error() {
        // 7 characters is invalid (incomplete alpha channel)
        let result = Color::try_from_hex("#1234567");
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::ParseHexError::InvalidLength => {}
            _ => panic!("Expected InvalidLength error"),
        }
    }

    // Edge cases in parsing
    #[test_log::test]
    fn can_parse_hex_without_hash_prefix() {
        assert_eq!(
            Color::from_hex("FF5733"),
            Color {
                r: 255,
                g: 87,
                b: 51,
                a: None
            }
        );
    }

    #[test_log::test]
    fn can_parse_hex_with_trailing_whitespace() {
        assert_eq!(
            Color::from_hex("#FF5733  "),
            Color {
                r: 255,
                g: 87,
                b: 51,
                a: None
            }
        );
    }

    #[test_log::test]
    fn can_parse_hex_with_trailing_whitespace_no_prefix() {
        assert_eq!(
            Color::from_hex("FF5733  "),
            Color {
                r: 255,
                g: 87,
                b: 51,
                a: None
            }
        );
    }

    #[test_log::test]
    fn can_parse_lowercase_hex() {
        assert_eq!(
            Color::from_hex("#ff5733"),
            Color {
                r: 255,
                g: 87,
                b: 51,
                a: None
            }
        );
    }

    #[test_log::test]
    fn can_parse_mixed_case_hex() {
        assert_eq!(
            Color::from_hex("#Ff5733"),
            Color {
                r: 255,
                g: 87,
                b: 51,
                a: None
            }
        );
    }

    #[test_log::test]
    fn can_parse_uppercase_hex() {
        assert_eq!(
            Color::from_hex("#FF5733"),
            Color {
                r: 255,
                g: 87,
                b: 51,
                a: None
            }
        );
    }

    // Additional edge cases for robustness
    #[test_log::test]
    fn can_parse_all_zeros_rgba() {
        assert_eq!(
            Color::from_hex("#00000000"),
            Color {
                r: 0,
                g: 0,
                b: 0,
                a: Some(0)
            }
        );
    }

    #[test_log::test]
    fn can_parse_all_max_rgba() {
        assert_eq!(
            Color::from_hex("#FFFFFFFF"),
            Color {
                r: 255,
                g: 255,
                b: 255,
                a: Some(255)
            }
        );
    }

    #[test_log::test]
    fn invalid_character_in_middle_returns_error() {
        let result = Color::try_from_hex("#FF5G33");
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::ParseHexError::InvalidCharacter(idx, ch) => {
                assert_eq!(idx, 3);
                assert_eq!(ch, 'G');
            }
            _ => panic!("Expected InvalidCharacter error"),
        }
    }

    #[test_log::test]
    fn special_ascii_character_returns_error() {
        let result = Color::try_from_hex("#FF5@33");
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::ParseHexError::InvalidCharacter(idx, ch) => {
                assert_eq!(idx, 3);
                assert_eq!(ch, '@');
            }
            _ => panic!("Expected InvalidCharacter error"),
        }
    }

    #[test_log::test]
    fn empty_string_parses_as_black() {
        // Empty strings result in all zeros (black)
        assert_eq!(
            Color::from_hex(""),
            Color {
                r: 0,
                g: 0,
                b: 0,
                a: None
            }
        );
    }

    #[test_log::test]
    fn only_hash_parses_as_black() {
        // Just a hash results in all zeros (black)
        assert_eq!(
            Color::from_hex("#"),
            Color {
                r: 0,
                g: 0,
                b: 0,
                a: None
            }
        );
    }

    #[test_log::test]
    fn single_character_parses_as_color() {
        // Single character is treated as incomplete short format
        // Based on the logic, this would set short_r and r
        let result = Color::try_from_hex("#A");
        assert!(result.is_ok());
    }

    #[test_log::test]
    fn two_characters_parses_as_color() {
        // Two characters would set r and g values
        let result = Color::try_from_hex("#AB");
        assert!(result.is_ok());
    }

    #[test_log::test]
    fn five_characters_parses_as_color() {
        // Five characters would parse successfully
        let result = Color::try_from_hex("#ABCDE");
        assert!(result.is_ok());
    }

    #[test_log::test]
    fn leading_whitespace_before_hash_is_not_supported() {
        // Leading whitespace before '#' prefix causes the '#' to be treated as invalid character
        // because strip_prefix('#') runs before trim()
        let result = Color::try_from_hex("  #FF5733");
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::ParseHexError::InvalidCharacter(idx, ch) => {
                assert_eq!(idx, 0);
                assert_eq!(ch, '#');
            }
            _ => panic!("Expected InvalidCharacter error"),
        }
    }

    #[test_log::test]
    fn leading_whitespace_without_hash_is_supported() {
        // Leading whitespace without '#' IS supported because strip_prefix doesn't remove
        // anything, and then trim() handles the whitespace
        assert_eq!(
            Color::from_hex("  FF5733"),
            Color {
                r: 255,
                g: 87,
                b: 51,
                a: None
            }
        );
    }

    #[test_log::test]
    fn round_trip_rgb_color_is_consistent() {
        let original = Color {
            r: 171,
            g: 205,
            b: 239,
            a: None,
        };
        let hex_string = original.to_string();
        let parsed = Color::from_hex(&hex_string);
        assert_eq!(original, parsed);
    }

    #[test_log::test]
    fn round_trip_rgba_color_is_consistent() {
        let original = Color {
            r: 171,
            g: 205,
            b: 239,
            a: Some(128),
        };
        let hex_string = original.to_string();
        let parsed = Color::from_hex(&hex_string);
        assert_eq!(original, parsed);
    }

    #[test_log::test]
    fn short_rgb_expands_correctly_then_round_trips() {
        // Short format #ABC expands to #AABBCC
        let from_short = Color::from_hex("#ABC");
        let hex_string = from_short.to_string();
        // Should output as the expanded form
        assert_eq!(hex_string, "#AABBCC");
        // And round-trip back correctly
        let round_tripped = Color::from_hex(&hex_string);
        assert_eq!(from_short, round_tripped);
    }

    #[test_log::test]
    fn short_rgba_expands_correctly_then_round_trips() {
        // Short format #ABCD expands to #AABBCCDD
        let from_short = Color::from_hex("#ABCD");
        let hex_string = from_short.to_string();
        // Should output as the expanded form
        assert_eq!(hex_string, "#AABBCCDD");
        // And round-trip back correctly
        let round_tripped = Color::from_hex(&hex_string);
        assert_eq!(from_short, round_tripped);
    }
}

#[cfg(all(test, feature = "arb"))]
mod prop_tests {
    use proptest::prelude::*;

    use crate::Color;

    proptest! {
        /// Verifies that any Color can be converted to a hex string and parsed back
        /// to produce an identical Color. This property must hold for all possible
        /// Color values, including edge cases with boundary values (0, 255) and
        /// both Some and None alpha channels.
        #[test]
        fn roundtrip_to_string_then_from_hex_preserves_color(color: Color) {
            let hex_string = color.to_string();
            let parsed = Color::from_hex(&hex_string);
            prop_assert_eq!(color, parsed);
        }
    }
}