palette/cast/
packed.rs

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
use core::marker::PhantomData;

use crate::cast::UintCast;

use super::ArrayCast;

/// A color packed into a compact format, such as an unsigned integer.
///
/// `Packed` implements [ArrayCast](crate::cast::ArrayCast) and
/// [UintCast](crate::cast::UintCast) so it can easily be constructed from
/// slices, arrays and unsigned integers.
///
/// ```
/// // `PackedArgb` is an alias for `Packed<rgb::channels::Argb, P = u32>`.
/// use palette::{rgb::PackedArgb, cast::UintsAs};
///
/// let raw = [0x7F0080u32, 0x60BBCC];
/// let colors: &[PackedArgb] = raw.uints_as();
///
/// assert_eq!(colors.len(), 2);
/// assert_eq!(colors[0].color, 0x7F0080);
/// assert_eq!(colors[1].color, 0x60BBCC);
/// ```
///
/// ## Packed Integer Type Represented in `u32`.
///
/// A common example of a packed format is when an RGBA color is encoded as a
/// hexadecimal number (such as `0x7F0080` from above). Two hexadecimal digits
/// (8-bits) express each value of the Red, Green, Blue, and Alpha components in
/// the RGBA color.
///
/// Note that conversion from float to integer component types in Palette rounds
/// to nearest even: an `Rgb` component of `0.5` will convert to `0x80`/`128`,
/// not `0x7F`/`127`.
///
/// ```
/// use approx::assert_relative_eq;
/// use palette::{Srgb, Srgba};
/// use palette::rgb::{PackedArgb, PackedRgba};
///
/// let packed: PackedArgb = Srgb::new(0.5, 0.0, 0.5).into_format().into();
/// assert_eq!(0xFF80_0080, packed.color);
///
/// let unpacked: Srgba<u8> = PackedRgba::from(0xFFFF_FF80u32).into();
/// assert_relative_eq!(
///     Srgba::new(1.0, 1.0, 1.0, 0.5),
///     unpacked.into_format(),
///     epsilon = 0.01
/// );
///
/// // By default, `Packed` uses `Argb` order for creating `Rgb` colors to make
/// // entering 6-digit hex numbers more convenient
/// let rgb = Srgb::from(0xFF8000);
/// assert_eq!(Srgb::new(0xFF, 0x80, 0x00), rgb);
///
/// let rgba = Srgba::from(0xFF80007F);
/// assert_eq!(Srgba::new(0xFF, 0x80, 0x00, 0x7F), rgba);
/// ```
///
/// When an `Rgb` type is packed, the alpha value will be `0xFF` in the
/// corresponding `u32`. Converting from a packed color type back to an `Rgb`
/// type will disregard the alpha value.
#[derive(Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct Packed<O, P> {
    /// The color packed into a type `P`, such as `u32` or `[u8; 4]`.
    pub color: P,

    /// The channel order for the color components in the packed data. See
    /// [`ComponentOrder`].
    pub channel_order: PhantomData<O>,
}

impl<O, P> Packed<O, P> {
    /// Transform a color value into a packed memory representation.
    #[inline]
    pub fn pack<C>(color: C) -> Self
    where
        O: ComponentOrder<C, P>,
    {
        Packed {
            color: O::pack(color),
            channel_order: PhantomData,
        }
    }

    /// Transform a packed color into a regular color value.
    #[inline]
    pub fn unpack<C>(self) -> C
    where
        O: ComponentOrder<C, P>,
    {
        O::unpack(self.color)
    }
}

impl<O, P> Copy for Packed<O, P> where P: Copy {}

impl<O, P> Clone for Packed<O, P>
where
    P: Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        Self {
            color: self.color.clone(),
            channel_order: PhantomData,
        }
    }
}

// Safety:
//
// `Packed` is a transparent wrapper around `[u8; N]`, which fulfills the
// requirements of `ArrayCast`.
unsafe impl<O, T, const N: usize> ArrayCast for Packed<O, [T; N]> {
    type Array = [T; N];
}

// Safety:
//
// `Packed` is a transparent wrapper around `u8`, which fulfills the
// requirements of `UintCast`.
unsafe impl<O> UintCast for Packed<O, u8> {
    type Uint = u8;
}

// Safety:
//
// `Packed` is a transparent wrapper around `u16`, which fulfills the
// requirements of `UintCast`.
unsafe impl<O> UintCast for Packed<O, u16> {
    type Uint = u16;
}

// Safety:
//
// `Packed` is a transparent wrapper around `u32`, which fulfills the
// requirements of `UintCast`.
unsafe impl<O> UintCast for Packed<O, u32> {
    type Uint = u32;
}

// Safety:
//
// `Packed` is a transparent wrapper around `u64`, which fulfills the
// requirements of `UintCast`.
unsafe impl<O> UintCast for Packed<O, u64> {
    type Uint = u64;
}

// Safety:
//
// `Packed` is a transparent wrapper around `u128`, which fulfills the
// requirements of `UintCast`.
unsafe impl<O> UintCast for Packed<O, u128> {
    type Uint = u128;
}

impl_array_casts!([O, T, const N: usize] Packed<O, [T; N]>, [T; N]);
impl_uint_casts_self!(Packed<O, P>, P, where Packed<O, P>: UintCast<Uint = P>);
impl_uint_casts_other!([O] Packed<O, u8>, u8);
impl_uint_casts_other!([O] Packed<O, u16>, u16);
impl_uint_casts_other!([O] Packed<O, u32>, u32);
impl_uint_casts_other!([O] Packed<O, u64>, u64);
impl_uint_casts_other!([O] Packed<O, u128>, u128);

#[cfg(feature = "bytemuck")]
unsafe impl<O, P> bytemuck::Zeroable for Packed<O, P> where P: bytemuck::Zeroable {}
#[cfg(feature = "bytemuck")]
unsafe impl<O: 'static, P> bytemuck::Pod for Packed<O, P> where P: bytemuck::Pod {}

/// Packs and unpacks color types with some component order.
///
/// As an example, RGBA channels may be ordered as `ABGR`, `ARGB`, `BGRA`, or
/// `RGBA`.
pub trait ComponentOrder<C, P> {
    /// Combine the components of a color into the packed format.
    fn pack(color: C) -> P;

    /// Split the packed color into its separate components.
    fn unpack(packed: P) -> C;
}

impl<C, T> ComponentOrder<C, u8> for T
where
    T: ComponentOrder<C, [u8; 1]>,
{
    #[inline]
    fn pack(color: C) -> u8 {
        let [packed] = T::pack(color);
        packed
    }

    #[inline]
    fn unpack(packed: u8) -> C {
        T::unpack([packed])
    }
}

impl<C, T> ComponentOrder<C, u16> for T
where
    T: ComponentOrder<C, [u8; 2]>,
{
    #[inline]
    fn pack(color: C) -> u16 {
        u16::from_be_bytes(T::pack(color))
    }

    #[inline]
    fn unpack(packed: u16) -> C {
        T::unpack(packed.to_be_bytes())
    }
}

impl<C, T> ComponentOrder<C, u32> for T
where
    T: ComponentOrder<C, [u8; 4]>,
{
    #[inline]
    fn pack(color: C) -> u32 {
        u32::from_be_bytes(T::pack(color))
    }

    #[inline]
    fn unpack(packed: u32) -> C {
        T::unpack(packed.to_be_bytes())
    }
}

impl<C, T> ComponentOrder<C, u64> for T
where
    T: ComponentOrder<C, [u8; 8]>,
{
    #[inline]
    fn pack(color: C) -> u64 {
        u64::from_be_bytes(T::pack(color))
    }

    #[inline]
    fn unpack(packed: u64) -> C {
        T::unpack(packed.to_be_bytes())
    }
}

impl<C, T> ComponentOrder<C, u128> for T
where
    T: ComponentOrder<C, [u8; 16]>,
{
    #[inline]
    fn pack(color: C) -> u128 {
        u128::from_be_bytes(T::pack(color))
    }

    #[inline]
    fn unpack(packed: u128) -> C {
        T::unpack(packed.to_be_bytes())
    }
}