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
use std::fmt;
use crate::{continuous, Error, Rgb, Rgba};
/// The scale semantics of a palette.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PaletteKind {
/// Maps discrete categories to individual colors.
Discrete,
/// Maps a continuous domain through an interpolated color gradient.
Continuous,
}
impl PaletteKind {
/// Returns the canonical lowercase palette kind.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Discrete => "discrete",
Self::Continuous => "continuous",
}
}
}
impl fmt::Display for PaletteKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// Options controlling continuous palette interpolation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ContinuousOptions {
reverse: bool,
}
impl ContinuousOptions {
/// Creates interpolation options with their defaults.
#[must_use]
pub const fn new() -> Self {
Self { reverse: false }
}
/// Sets whether to reverse the colors after interpolation.
#[must_use]
pub const fn with_reverse(self, reverse: bool) -> Self {
Self { reverse }
}
/// Returns whether colors are reversed after interpolation.
#[must_use]
pub const fn reverse(self) -> bool {
self.reverse
}
}
/// A canonical palette specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PaletteSpec {
family: &'static str,
variant: &'static str,
}
impl PaletteSpec {
/// Creates a palette specification from canonical family and variant names.
#[must_use]
pub const fn new(family: &'static str, variant: &'static str) -> Self {
Self { family, variant }
}
/// Returns the canonical family name.
#[must_use]
pub const fn family(self) -> &'static str {
self.family
}
/// Returns the canonical variant name.
#[must_use]
pub const fn variant(self) -> &'static str {
self.variant
}
}
/// A generated ggsci palette with discrete or continuous scale semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Palette {
family: &'static str,
variant: &'static str,
kind: PaletteKind,
colors: &'static [Rgb],
}
impl Palette {
/// Creates a palette from canonical metadata and stored source colors.
#[must_use]
pub const fn new(
family: &'static str,
variant: &'static str,
kind: PaletteKind,
colors: &'static [Rgb],
) -> Self {
Self {
family,
variant,
kind,
colors,
}
}
/// Returns the canonical family name.
#[must_use]
pub const fn family(&self) -> &'static str {
self.family
}
/// Returns the canonical variant name.
#[must_use]
pub const fn variant(&self) -> &'static str {
self.variant
}
/// Returns whether this palette is discrete or continuous.
#[must_use]
pub const fn kind(&self) -> PaletteKind {
self.kind
}
/// Returns this palette's canonical specification.
#[must_use]
pub const fn spec(&self) -> PaletteSpec {
PaletteSpec::new(self.family, self.variant)
}
/// Returns this palette's canonical source colors.
///
/// These are category colors for a discrete palette and interpolation
/// anchors for a continuous palette.
#[must_use]
pub const fn colors(&self) -> &'static [Rgb] {
self.colors
}
/// Returns the number of stored source colors or interpolation anchors.
#[must_use]
pub const fn len(&self) -> usize {
self.colors.len()
}
/// Returns `true` if the palette has no colors.
#[must_use]
pub const fn is_empty(&self) -> bool {
self.colors.is_empty()
}
/// Returns `true` if this palette maps discrete categories.
#[must_use]
pub const fn is_discrete(&self) -> bool {
matches!(self.kind, PaletteKind::Discrete)
}
/// Returns `true` if this palette maps a continuous domain.
#[must_use]
pub const fn is_continuous(&self) -> bool {
matches!(self.kind, PaletteKind::Continuous)
}
/// Returns the first `n` category colors from a discrete palette.
///
/// # Errors
///
/// Returns [`Error::NotDiscretePalette`] for a continuous palette, or
/// [`Error::TooManyColorsRequested`] if `n` exceeds the number of stored
/// category colors. This method does not cycle colors.
pub fn take(&self, n: usize) -> Result<Vec<Rgb>, Error> {
self.ensure_discrete()?;
if n > self.colors.len() {
return Err(Error::TooManyColorsRequested {
family: self.family,
variant: self.variant,
requested: n,
available: self.colors.len(),
});
}
Ok(self.colors[..n].to_vec())
}
/// Returns the first `n` category colors as `#RRGGBB` strings.
///
/// # Errors
///
/// Returns [`Error::NotDiscretePalette`] for a continuous palette, or
/// [`Error::TooManyColorsRequested`] if `n` exceeds the number of stored
/// category colors. This method does not cycle colors.
pub fn take_hex(&self, n: usize) -> Result<Vec<String>, Error> {
self.take(n)
.map(|colors| colors.into_iter().map(Rgb::to_hex_string).collect())
}
/// Returns an explicitly infinite iterator over discrete category colors.
///
/// # Errors
///
/// Returns [`Error::NotDiscretePalette`] for a continuous palette.
pub fn cycle(&self) -> Result<impl Iterator<Item = Rgb> + '_, Error> {
self.ensure_discrete()?;
Ok(self.colors.iter().copied().cycle())
}
/// Interpolates `n` colors from a continuous palette.
///
/// # Errors
///
/// Returns [`Error::NotContinuousPalette`] for a discrete palette.
pub fn interpolate(&self, n: usize) -> Result<Vec<Rgb>, Error> {
self.interpolate_with(n, ContinuousOptions::new())
}
/// Interpolates `n` colors using the supplied continuous options.
///
/// Reversal is applied after interpolation, matching ggsci for R.
///
/// # Errors
///
/// Returns [`Error::NotContinuousPalette`] for a discrete palette.
pub fn interpolate_with(
&self,
n: usize,
options: ContinuousOptions,
) -> Result<Vec<Rgb>, Error> {
self.ensure_continuous()?;
let mut colors = continuous::interpolate(self.colors, n);
if options.reverse() {
colors.reverse();
}
Ok(colors)
}
/// Interpolates `n` colors and applies an alpha channel.
///
/// # Errors
///
/// Returns [`Error::NotContinuousPalette`] for a discrete palette, or
/// [`Error::InvalidAlpha`] unless `alpha` is finite and in `(0.0, 1.0]`.
pub fn interpolate_rgba(&self, n: usize, alpha: f32) -> Result<Vec<Rgba>, Error> {
self.interpolate_rgba_with(n, alpha, ContinuousOptions::new())
}
/// Interpolates `n` colors with an alpha channel and continuous options.
///
/// # Errors
///
/// Returns [`Error::NotContinuousPalette`] for a discrete palette, or
/// [`Error::InvalidAlpha`] unless `alpha` is finite and in `(0.0, 1.0]`.
pub fn interpolate_rgba_with(
&self,
n: usize,
alpha: f32,
options: ContinuousOptions,
) -> Result<Vec<Rgba>, Error> {
self.ensure_continuous()?;
let alpha = continuous::continuous_alpha(alpha)?;
self.interpolate_with(n, options).map(|colors| {
colors
.into_iter()
.map(|color| color.with_alpha_u8(alpha))
.collect()
})
}
/// Interpolates `n` colors as `#RRGGBB` strings.
///
/// # Errors
///
/// Returns [`Error::NotContinuousPalette`] for a discrete palette.
pub fn interpolate_hex(&self, n: usize) -> Result<Vec<String>, Error> {
self.interpolate_hex_with(n, ContinuousOptions::new())
}
/// Interpolates `n` colors as `#RRGGBB` strings with continuous options.
///
/// # Errors
///
/// Returns [`Error::NotContinuousPalette`] for a discrete palette.
pub fn interpolate_hex_with(
&self,
n: usize,
options: ContinuousOptions,
) -> Result<Vec<String>, Error> {
self.interpolate_with(n, options)
.map(|colors| colors.into_iter().map(Rgb::to_hex_string).collect())
}
/// Returns `n` colors using kind-aware palette semantics.
///
/// Discrete palettes use [`Self::take`], while continuous palettes use
/// [`Self::interpolate`].
///
/// # Errors
///
/// Returns [`Error::TooManyColorsRequested`] when a discrete palette does
/// not contain enough category colors.
pub fn sample(&self, n: usize) -> Result<Vec<Rgb>, Error> {
match self.kind {
PaletteKind::Discrete => self.take(n),
PaletteKind::Continuous => self.interpolate(n),
}
}
/// Returns `n` kind-aware colors as `#RRGGBB` strings.
///
/// # Errors
///
/// Returns [`Error::TooManyColorsRequested`] when a discrete palette does
/// not contain enough category colors.
pub fn sample_hex(&self, n: usize) -> Result<Vec<String>, Error> {
match self.kind {
PaletteKind::Discrete => self.take_hex(n),
PaletteKind::Continuous => self.interpolate_hex(n),
}
}
fn ensure_discrete(&self) -> Result<(), Error> {
if self.is_discrete() {
Ok(())
} else {
Err(Error::NotDiscretePalette {
family: self.family,
variant: self.variant,
})
}
}
fn ensure_continuous(&self) -> Result<(), Error> {
if self.is_continuous() {
Ok(())
} else {
Err(Error::NotContinuousPalette {
family: self.family,
variant: self.variant,
})
}
}
}