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
use super::*;
use std::convert::TryFrom;
use std::str::FromStr;

// To Lab /////////////////////////////////////////////////////////////////////
impl From<LchValue> for LabValue {
    fn from(lch: LchValue) -> LabValue {
        LabValue {
            l: lch.l,
            a: lch.c * lch.h.to_radians().cos(),
            b: lch.c * lch.h.to_radians().sin(),
        }
    }
}

impl From<&LchValue> for LabValue {
    fn from(lch: &LchValue) -> LabValue {
        LabValue::from(*lch)
    }
}

impl From<&LabValue> for LabValue {
    fn from(lab: &LabValue) -> LabValue {
        *lab
    }
}

impl From<XyzValue> for LabValue {
    fn from(xyz: XyzValue) -> LabValue {
        let x = xyz_to_lab_map(xyz.x / 0.9642);
        let y = xyz_to_lab_map(xyz.y);
        let z = xyz_to_lab_map(xyz.z / 0.8251);

        LabValue {
            l: (116.0 * y) - 16.0,
            a: 500.0 * (x - y),
            b: 200.0 * (y - z),
        }
    }
}

impl From<&XyzValue> for LabValue {
    fn from(xyz: &XyzValue) -> LabValue {
        LabValue::from(*xyz)
    }
}

impl TryFrom<&[f32; 3]> for LabValue {
    type Error = ValueError;
    fn try_from(slice: &[f32; 3]) -> ValueResult<LabValue> {
        LabValue {
            l: slice[0],
            a: slice[1],
            b: slice[2]
        }.validate()
    }
}

impl TryFrom<(f32, f32, f32)> for LabValue {
    type Error = ValueError;
    fn try_from(tuple: (f32, f32, f32)) -> ValueResult<LabValue> {
        LabValue {
            l: tuple.0,
            a: tuple.1,
            b: tuple.2,
        }.validate()
    }
}

impl TryFrom<&(f32, f32, f32)> for LabValue {
    type Error = ValueError;
    fn try_from(tuple: &(f32, f32, f32)) -> ValueResult<LabValue> {
        LabValue {
            l: tuple.0,
            a: tuple.1,
            b: tuple.2,
        }.validate()
    }
}

// To Lch /////////////////////////////////////////////////////////////////////
impl From<LabValue> for LchValue {
    fn from(lab: LabValue) -> LchValue {
        LchValue {
            l: lab.l,
            c: ( lab.a.powi(2) + lab.b.powi(2) ).sqrt(),
            h: get_h_prime(lab.a, lab.b),
        }
    }
}

impl From<&LabValue> for LchValue {
    fn from(lab: &LabValue) -> LchValue {
        LchValue::from(*lab)
    }
}

impl From<XyzValue> for LchValue {
    fn from(xyz: XyzValue) -> LchValue {
        LchValue::from(LabValue::from(xyz))
    }
}

impl From<&XyzValue> for LchValue {
    fn from(xyz: &XyzValue) -> LchValue {
        LchValue::from(*xyz)
    }
}

impl TryFrom<&[f32; 3]> for LchValue {
    type Error = ValueError;
    fn try_from(slice: &[f32; 3]) -> ValueResult<LchValue> {
        LchValue {
            l: slice[0],
            c: slice[1],
            h: slice[2]
        }.validate()
    }
}

impl TryFrom<(f32, f32, f32)> for LchValue {
    type Error = ValueError;
    fn try_from(tuple: (f32, f32, f32)) -> ValueResult<LchValue> {
        LchValue {
            l: tuple.0,
            c: tuple.1,
            h: tuple.2,
        }.validate()
    }
}

impl TryFrom<&(f32, f32, f32)> for LchValue {
    type Error = ValueError;
    fn try_from(tuple: &(f32, f32, f32)) -> ValueResult<LchValue> {
        LchValue {
            l: tuple.0,
            c: tuple.1,
            h: tuple.2,
        }.validate()
    }
}

// To Xyz /////////////////////////////////////////////////////////////////////
impl From<LabValue> for XyzValue {
    fn from(lab: LabValue) -> XyzValue {
        let fy = (lab.l + 16.0) / 116.0;
        let fx = (lab.a / 500.0) + fy;
        let fz = fy - (lab.b / 200.0);
        let xr = if fx > CBRT_EPSILON as f32 {
            fx.powi(3)
        } else {
            ((fx * 116.0) - 16.0) / KAPPA
        };
        let yr = if lab.l > EPSILON * KAPPA {
            fy.powi(3)
        } else {
            lab.l / KAPPA
        };
        let zr = if fz > CBRT_EPSILON as f32 {
            fz.powi(3)
        } else {
            ((fz * 116.0) - 16.0) / KAPPA
        };

        XyzValue {
            x: xr * 0.9642,
            y: yr,
            z: zr * 0.8251,
        }
    }
}

impl From<&LabValue> for XyzValue {
    fn from(lab: &LabValue) -> XyzValue {
        XyzValue::from(*lab)
    }
}

impl From<LchValue> for XyzValue {
    fn from(lch: LchValue) -> XyzValue {
        XyzValue::from(LabValue::from(lch))
    }
}

impl From<&LchValue> for XyzValue {
    fn from(lch: &LchValue) -> XyzValue {
        XyzValue::from(*lch)
    }
}

impl TryFrom<&[f32; 3]> for XyzValue {
    type Error = ValueError;
    fn try_from(slice: &[f32; 3]) -> ValueResult<XyzValue> {
        XyzValue {
            x: slice[0],
            y: slice[1],
            z: slice[2]
        }.validate()
    }
}

impl TryFrom<(f32, f32, f32)> for XyzValue {
    type Error = ValueError;
    fn try_from(tuple: (f32, f32, f32)) -> ValueResult<XyzValue> {
        XyzValue {
            x: tuple.0,
            y: tuple.1,
            z: tuple.2,
        }.validate()
    }
}

impl TryFrom<&(f32, f32, f32)> for XyzValue {
    type Error = ValueError;
    fn try_from(tuple: &(f32, f32, f32)) -> ValueResult<XyzValue> {
        XyzValue {
            x: tuple.0,
            y: tuple.1,
            z: tuple.2,
        }.validate()
    }
}

// FromStr ////////////////////////////////////////////////////////////////////
impl FromStr for DEMethod {
    type Err = std::io::Error;
    fn from_str(s: &str) -> Result<DEMethod, Self::Err> {
        match s.to_lowercase().trim() {
            "de2000"  | "de00"  | "2000"  | "00"  => Ok(DEMethod::DE2000),
            "de1976"  | "de76"  | "1976"  | "76"  => Ok(DEMethod::DE1976),
            "de1994"  | "de94"  | "1994"  | "94" |
            "de1994g" | "de94g" | "1994g" | "94g" => Ok(DEMethod::DE1994G),
            "de1994t" | "de94t" | "1994t" | "94t" => Ok(DEMethod::DE1994T),
            "decmc"   | "decmc1"| "cmc1"  | "cmc" => Ok(DEMethod::DECMC(1.0, 1.0)),
            "decmc2"  | "cmc2"                    => Ok(DEMethod::DECMC(2.0, 1.0)),
            _ => Err(io::Error::from(io::ErrorKind::InvalidInput)),
        }
    }
}

impl FromStr for LabValue {
    type Err = ValueError;
    fn from_str(s: &str) -> ValueResult<LabValue> {
        let split = parse_str_to_vecf32(s, 3)?;

        LabValue {
            l: split[0],
            a: split[1],
            b: split[2],
        }.validate()
    }
}

impl FromStr for LchValue {
    type Err = ValueError;
    fn from_str(s: &str) -> ValueResult<LchValue> {
        let split = parse_str_to_vecf32(s, 3)?;

        LchValue {
            l: split[0],
            c: split[1],
            h: split[2],
        }.validate()
    }
}

impl FromStr for XyzValue {
    type Err = ValueError;
    fn from_str(s: &str) -> ValueResult<XyzValue> {
        let split = parse_str_to_vecf32(s, 3)?;

        XyzValue {
            x: split[0],
            y: split[1],
            z: split[2],
        }.validate()
    }

}

// Helper Functions ////////////////////////////////////////////////////////////
const KAPPA: f32 = 24389.0 / 27.0; // CIE Standard: 903.3
const EPSILON: f32 = 216.0 / 24389.0; // CIE Standard: 0.008856
const CBRT_EPSILON: f64 = 0.20689655172413796;

pub fn get_h_prime(a: f32, b: f32) -> f32 {
    let h_prime = b.atan2(a).to_degrees();
    if h_prime < 0.0 {
        h_prime + 360.0
    } else {
        h_prime
    }
}

// Validate and convert strings to `LabValue`.
// Split string by comma (92.5,33.5,-18.8).
fn parse_str_to_vecf32(s: &str, length: usize) -> ValueResult<Vec<f32>> {
    let collection: Vec<&str> = s.split(',').collect();

    // Allow extraneous whitespace ("92.5, 33.5, -18.8")
    let mut v: Vec<&str> = Vec::new();
    for item in collection.iter() {
        if !item.is_empty() {
            v.push(item.trim());
        }
    }
    // Parse the f32's into a Vec
    let split: Vec<f32> = v.iter().filter_map(|s| s.parse().ok()).collect();

    // Check if it's the right number of items
    if v.len() != length || split.len() != length {
        return Err(ValueError::BadFormat);
    }

    Ok(split)
}

#[inline]
fn xyz_to_lab_map(c: f32) -> f32 {
    if c > EPSILON {
        c.powf(1.0/3.0)
    } else {
        (KAPPA * c + 16.0) / 116.0
    }
}