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
use core::{
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

use crate::cast::{self, ArrayCast};

use super::{FromColor, FromColorUnclampedMut, FromColorUnclampedMutGuard, IntoColor};

/// Temporarily convert colors in place.
///
/// It allows colors to be converted without using more additional memory than
/// what is necessary for the conversion, itself. The conversion will however
/// have to be reverted at some point, since the memory space is borrowed and
/// has to be restored to its original format. This is enforced by a scope guard
/// that does the opposite conversion when it's dropped.
///
/// See also [`IntoColorMut`] and [`FromColorUnclampedMut`].
///
/// ```
/// use palette::{FromColorMut, ShiftHueAssign, Srgb, Hsv};
///
/// let mut rgb = [
///     Srgb::new(1.0, 0.0, 0.0),
///     Srgb::new(0.0, 1.0, 0.0),
///     Srgb::new(0.0, 0.0, 1.0),
/// ];
///
/// {
///     let mut hsv = <[Hsv]>::from_color_mut(&mut rgb);
///
///     // All of the colors in `rgb` have been converted to `Hsv`:
///     assert_eq!(
///         *hsv,
///         [
///             Hsv::new(0.0, 1.0, 1.0),
///             Hsv::new(120.0, 1.0, 1.0),
///             Hsv::new(240.0, 1.0, 1.0),
///         ]
///     );
///
///     hsv.shift_hue_assign(60.0);
///
/// } // The guard is dropped here and the colors are restored to `Srgb`.
///
/// // Notice how the colors in `rgb` have changed:
/// assert_eq!(
///     rgb,
///     [
///         Srgb::new(1.0, 1.0, 0.0),
///         Srgb::new(0.0, 1.0, 1.0),
///         Srgb::new(1.0, 0.0, 1.0),
///     ]
/// );
/// ```
///
/// The scope guard, [`FromColorMutGuard`], has a few extra methods that can
/// make multiple conversion steps more efficient. One of those is
/// [`FromColorMutGuard::then_into_color_mut`], which works like
/// [`IntoColorMut::into_color_mut`], but does not add an extra step when
/// restoring to the original color type. This example will convert `Srgb → Hsv
/// → Hsl → Srgb` instead of `Srgb → Hsv → Hsl → Hsv → Srgb`:
///
/// ```
/// use palette::{FromColorMut, ShiftHueAssign, LightenAssign, Srgb, Hsv, Hsl};
///
/// let mut rgb = [
///     Srgb::new(1.0, 0.0, 0.0),
///     Srgb::new(0.0, 1.0, 0.0),
///     Srgb::new(0.0, 0.0, 1.0),
/// ];
///
/// {
///     let mut hsv = <[Hsv]>::from_color_mut(&mut rgb);
///     hsv.shift_hue_assign(60.0);
///
///     let mut hsl = hsv.then_into_color_mut::<[Hsl]>();
///     hsl.lighten_assign(0.5);
///
/// } // `then_into_color_mut` makes the guard restore directly to `Srgb` here.
///
/// // Notice how the colors in `rgb` have changed:
/// assert_eq!(
///     rgb,
///     [
///         Srgb::new(1.0, 1.0, 0.5),
///         Srgb::new(0.5, 1.0, 1.0),
///         Srgb::new(1.0, 0.5, 1.0),
///     ]
/// );
/// ```
///
/// # Note
///
/// The reused memory space could end up with unexpected values if the
/// conversion panics or if the scope guard's `drop` function doesn't run. The
/// default implementations of `FromColorMut` uses [`ArrayCast`], which is only
/// implemented for color types that can safely accept and recover from any
/// value. Other color types will have to provide their own implementations that
/// can handle this case.
pub trait FromColorMut<T>
where
    T: ?Sized + FromColorMut<Self>,
{
    /// Temporarily convert from another color type in place.
    ///
    /// This reuses the memory space, and the returned scope guard will restore
    /// the converted colors to their original type when it's dropped.
    #[must_use]
    fn from_color_mut(color: &mut T) -> FromColorMutGuard<Self, T>;
}

impl<T, U> FromColorMut<U> for T
where
    T: FromColor<U> + ArrayCast + Clone,
    U: FromColor<T> + ArrayCast<Array = T::Array> + Clone,
{
    #[inline]
    fn from_color_mut(color: &mut U) -> FromColorMutGuard<Self, U> {
        let color_clone = color.clone();

        let result: &mut T = cast::from_array_mut(cast::into_array_mut(color));

        *result = color_clone.into_color();

        FromColorMutGuard {
            current: Some(result),
            original: PhantomData,
        }
    }
}

impl<T, U> FromColorMut<[U]> for [T]
where
    T: FromColorMut<U> + ArrayCast + ?Sized,
    U: FromColorMut<T> + ArrayCast<Array = T::Array> + ?Sized,
{
    #[inline]
    fn from_color_mut(colors: &mut [U]) -> FromColorMutGuard<Self, [U]> {
        for color in &mut *colors {
            // Forgetting the guard leaves the colors in the converted state.
            core::mem::forget(T::from_color_mut(color));
        }

        FromColorMutGuard {
            current: Some(cast::from_array_slice_mut(cast::into_array_slice_mut(
                colors,
            ))),
            original: PhantomData,
        }
    }
}

/// Temporarily convert colors in place. The `Into` counterpart to
/// [`FromColorMut`].
///
/// See [`FromColorMut`] for more details and examples.
///
/// ```
/// use palette::{IntoColorMut, ShiftHueAssign, Srgb, Hsv};
///
/// let mut rgb = [
///     Srgb::new(1.0, 0.0, 0.0),
///     Srgb::new(0.0, 1.0, 0.0),
///     Srgb::new(0.0, 0.0, 1.0),
/// ];
///
/// {
///     let hsv: &mut [Hsv] = &mut rgb.into_color_mut(); // The guard is coerced into a slice.
///
///     // All of the colors in `rgb` have been converted to `Hsv`:
///     assert_eq!(
///         hsv,
///         [
///             Hsv::new(0.0, 1.0, 1.0),
///             Hsv::new(120.0, 1.0, 1.0),
///             Hsv::new(240.0, 1.0, 1.0),
///         ]
///     );
///
///     hsv.shift_hue_assign(60.0);
///
/// } // The guard is dropped here and the colors are restored to `Srgb`.
///
/// // Notice how the colors in `rgb` have changed:
/// assert_eq!(
///     rgb,
///     [
///         Srgb::new(1.0, 1.0, 0.0),
///         Srgb::new(0.0, 1.0, 1.0),
///         Srgb::new(1.0, 0.0, 1.0),
///     ]
/// );
/// ```
pub trait IntoColorMut<T>: FromColorMut<T>
where
    T: ?Sized + FromColorMut<Self>,
{
    /// Temporarily convert to another color type in place.
    ///
    /// This reuses the memory space, and the returned scope guard will restore
    /// the converted colors to their original type when it's dropped.
    #[allow(clippy::wrong_self_convention)]
    #[must_use]
    fn into_color_mut(&mut self) -> FromColorMutGuard<T, Self>;
}

impl<T, U> IntoColorMut<T> for U
where
    T: FromColorMut<U> + ?Sized,
    U: FromColorMut<T> + ?Sized,
{
    #[inline]
    fn into_color_mut(&mut self) -> FromColorMutGuard<T, Self> {
        T::from_color_mut(self)
    }
}

/// A scope guard that restores the guarded colors to their original type when
/// dropped.
#[repr(transparent)]
pub struct FromColorMutGuard<'a, T, U>
where
    T: FromColorMut<U> + ?Sized,
    U: FromColorMut<T> + ?Sized,
{
    // `Option` lets us move out without triggering `Drop`.
    pub(super) current: Option<&'a mut T>,
    pub(super) original: PhantomData<&'a mut U>,
}

impl<'a, T, U> FromColorMutGuard<'a, T, U>
where
    T: FromColorMut<U> + ?Sized,
    U: FromColorMut<T> + ?Sized,
{
    /// Convert the colors to another type and replace this guard.
    ///
    /// The colors will not be converted back to the current color type before
    /// being restored, as opposed to when `into_color_mut` is called. Instead,
    /// they are restored directly to their original type.
    #[must_use]
    #[inline]
    pub fn then_into_color_mut<C>(mut self) -> FromColorMutGuard<'a, C, U>
    where
        T: FromColorMut<C>,
        C: FromColorMut<U> + FromColorMut<T> + ?Sized,
        U: FromColorMut<C>,
    {
        FromColorMutGuard {
            current: self
                .current
                .take()
                .map(C::from_color_mut)
                .and_then(|mut guard| guard.current.take()),
            original: PhantomData,
        }
    }

    /// Convert the colors to another type, without clamping, and replace this
    /// guard.
    ///
    /// The colors will not be converted back to the current color type before
    /// being restored, as opposed to when `into_color_unclamped_mut` is called.
    /// Instead, they are restored directly to their original type.
    #[must_use]
    #[inline]
    pub fn then_into_color_unclamped_mut<C>(mut self) -> FromColorUnclampedMutGuard<'a, C, U>
    where
        T: FromColorUnclampedMut<C>,
        C: FromColorUnclampedMut<U> + FromColorUnclampedMut<T> + ?Sized,
        U: FromColorUnclampedMut<C>,
    {
        FromColorUnclampedMutGuard {
            current: self
                .current
                .take()
                .map(C::from_color_unclamped_mut)
                .and_then(|mut guard| guard.current.take()),
            original: PhantomData,
        }
    }

    /// Replace this guard with a guard that does not clamp the colors after restoring.
    #[must_use]
    #[inline]
    pub fn into_unclamped_guard(mut self) -> FromColorUnclampedMutGuard<'a, T, U>
    where
        T: FromColorUnclampedMut<U>,
        U: FromColorUnclampedMut<T>,
    {
        FromColorUnclampedMutGuard {
            current: self.current.take(),
            original: PhantomData,
        }
    }

    /// Immediately restore the colors to their original type.
    ///
    /// This happens automatically when the guard is dropped, but there may be
    /// situations where it's better or more convenient to call `restore`
    /// directly.
    #[inline]
    pub fn restore(mut self) -> &'a mut U {
        let restored = self
            .current
            .take()
            .map(U::from_color_mut)
            .and_then(|mut guard| guard.current.take());

        if let Some(restored) = restored {
            restored
        } else {
            unreachable!()
        }
    }
}

impl<'a, T, U> Deref for FromColorMutGuard<'a, T, U>
where
    T: FromColorMut<U> + ?Sized,
    U: FromColorMut<T> + ?Sized,
{
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        if let Some(current) = self.current.as_ref() {
            current
        } else {
            unreachable!()
        }
    }
}

impl<'a, T, U> DerefMut for FromColorMutGuard<'a, T, U>
where
    T: FromColorMut<U> + ?Sized,
    U: FromColorMut<T> + ?Sized,
{
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        if let Some(current) = self.current.as_mut() {
            current
        } else {
            unreachable!()
        }
    }
}

impl<'a, T, U> Drop for FromColorMutGuard<'a, T, U>
where
    T: FromColorMut<U> + ?Sized,
    U: FromColorMut<T> + ?Sized,
{
    #[inline]
    fn drop(&mut self) {
        // Forgetting the guard leaves the colors in the converted state.
        core::mem::forget(self.current.take().map(U::from_color_mut));
    }
}