ecolor/
hex_color_macro.rs

1/// Construct a [`crate::Color32`] from a hex RGB or RGBA string literal.
2///
3/// Requires the "color-hex" feature.
4///
5/// The string is checked at compile time. If the format is invalid, compilation fails. The valid
6/// format is the one described in <https://drafts.csswg.org/css-color-4/#hex-color>. Only 6 (RGB) or 8 (RGBA)
7/// digits are supported, and the leading `#` character is optional.
8///
9/// Note that despite being checked at compile-time, this macro is not usable in `const` contexts
10/// because creating the [`crate::Color32`] instance requires floating-point arithmetic.
11///
12/// See also [`crate::Color32::from_hex`] and [`crate::Color32::to_hex`].
13///
14/// # Examples
15///
16/// ```
17/// # use ecolor::{hex_color, Color32};
18/// assert_eq!(hex_color!("#202122"), Color32::from_hex("#202122").unwrap());
19/// assert_eq!(hex_color!("#202122"), Color32::from_rgb(0x20, 0x21, 0x22));
20/// assert_eq!(hex_color!("#202122"), hex_color!("202122"));
21/// assert_eq!(hex_color!("#abcdef12"), Color32::from_rgba_unmultiplied(0xab, 0xcd, 0xef, 0x12));
22/// ```
23///
24/// If the literal string has the wrong format, the code does not compile.
25///
26/// ```compile_fail
27/// let _ = ecolor::hex_color!("#abc");
28/// ```
29///
30/// ```compile_fail
31/// let _ = ecolor::hex_color!("#20212x");
32/// ```
33///
34/// The macro can be used in a `const` context.
35///
36/// ```
37/// const COLOR: ecolor::Color32 = ecolor::hex_color!("#202122");
38/// assert_eq!(COLOR, ecolor::Color32::from_rgb(0x20, 0x21, 0x22));
39/// ```
40#[macro_export]
41macro_rules! hex_color {
42    ($s:literal) => {{
43        let array = $crate::color_hex::color_from_hex!($s);
44        match array.as_slice() {
45            [r, g, b] => $crate::Color32::from_rgb(*r, *g, *b),
46            [r, g, b, a] => $crate::Color32::from_rgba_unmultiplied_const(*r, *g, *b, *a),
47            _ => panic!("Invalid hex color length: expected 3 (RGB) or 4 (RGBA) bytes"),
48        }
49    }};
50}
51
52#[test]
53fn test_from_rgb_hex() {
54    assert_eq!(
55        crate::Color32::from_rgb(0x20, 0x21, 0x22),
56        hex_color!("#202122")
57    );
58    assert_eq!(
59        crate::Color32::from_rgb_additive(0x20, 0x21, 0x22),
60        hex_color!("#202122").additive()
61    );
62}
63
64#[test]
65fn test_from_rgba_hex() {
66    assert_eq!(
67        crate::Color32::from_rgba_unmultiplied(0x20, 0x21, 0x22, 0x50),
68        hex_color!("20212250")
69    );
70}