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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
//! Manipulate and convert CIE L\*a\*b\* and Lch colors.
//! 
//! ### Lab
//! 
//! * **L**: Lightness     (0...100)
//! * **a**: green-magenta (-128...128)
//! * **b**: blue-yellow   (-128...128)
//! 
//! ### Lch
//! 
//! * **L**: Lightness (0...100)
//! * **c**: Chroma    (0...181.0139)
//! * **h**: Hue       (0...360°)
//!     
//! # Examples
//! 
//! ```
//! extern crate deltae;
//! use deltae::color::{LabValue, LchValue};
//! use std::str::FromStr;
//! 
//! fn main() {
//!     let lab0 = LabValue::from_str("95.08, -0.17, -10.81").unwrap();
//!     let lab1 = LabValue {
//!         l: 95.08,
//!         a: -0.17,
//!         b: -10.81,
//!     };
//! 
//!     assert_eq!(lab0, lab1);
//! 
//!     let lch0 = lab0.to_lch();
//!     let lab2 = lch0.to_lab();
//! 
//!     println!("{}", lch0); // [L:89.73, c:7.2094, h:285.1157]
//! 
//!     assert_eq!(lab0.round_to(4), lab2.round_to(4));
//! }
//! ```

use super::*;
use std::fmt;
use std::error::Error;
use std::str::FromStr;

#[derive(Debug, PartialEq, Clone)]
pub struct LabValue {
    pub l: f32,
    pub a: f32,
    pub b: f32,
}

impl LabValue {
    pub fn new(l: f32, a: f32, b: f32) -> ValueResult<LabValue> {
        //! New `LabValue` from 3 `f32`s
        LabValue {l, a, b}.validate()
    }

    fn validate(self) -> ValueResult<LabValue> {
        // Check that the Lab values are in the proper range or Error
        if  self.l < 0.0    || self.l > 100.0 ||
            self.a < -128.0 || self.a > 128.0 ||
            self.b < -128.0 || self.b > 128.0
        {
            Err(ValueError::OutOfBounds)
        } else {
            Ok(self)
        }
    }


    pub fn to_lch(&self) -> LchValue {
        //! Convert `LabValue` to `LchValue`
        LchValue {
            l: self.l,
            c: ( self.a.powi(2) + self.b.powi(2) ).sqrt(),
            h: get_h_prime(self.a, self.b),
        }
    }

    pub fn chroma(&self) -> f32 {
        self.to_lch().c
    }

    pub fn hue(&self) -> f32 {
        self.to_lch().h
    }

    pub fn hue_radians(&self) -> f32 {
        self.to_lch().h.to_radians()
    }

    pub fn to_xyz(&self) -> XyzValue {
        lab_to_xyz(self)
    }

    pub fn round_to(&self, places: i32) -> LabValue {
        //! Round `LabValue` to nearest decimal places.
        LabValue {
            l: round_to(self.l, places),
            a: round_to(self.a, places),
            b: round_to(self.b, places),
        }       
    }

    pub fn to_a(&self) -> [f32; 3] {
        //! Returns an array of [L, a, b]
        [self.l, self.a, self.b]
    }

    pub fn to_vec(&self) -> Vec<f32> {
        //! Returns a `Vec<f32>` of [L, a, b]
        vec![self.l, self.a, self.b]
    }
}

impl Default for LabValue {
    fn default() -> LabValue {
        LabValue { l: 0.0, a: 0.0, b: 0.0 }
    }
}

impl FromStr for LabValue {
    type Err = ValueError;

    fn from_str(s: &str) -> ValueResult<LabValue> {
        //! New `LabValue` from `&str`
        let split = parse_str_to_vecf32(s, 3)?;

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

impl fmt::Display for LabValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[L:{}, a:{}, b:{}]", self.l, self.a, self.b)
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct LchValue {
    pub l: f32,
    pub c: f32,
    pub h: f32,
}

impl LchValue {
    pub fn new(l: f32, c: f32, h: f32) -> ValueResult<LchValue> {
        //! New `LchValue` from 3 `f32`s
        LchValue {l, c, h}.validate()
    }

    fn validate(self) -> ValueResult<LchValue> {
        // Check that the Lab values are in the proper range or Error
        if  self.l < 0.0 || self.l > 100.0 ||
            self.c < 0.0 || self.c > (128_f32.powi(2) + 128_f32.powi(2)).sqrt() ||
            self.h < 0.0 || self.h > 360.0
        {
            Err(ValueError::OutOfBounds)
        } else {
            Ok(self)
        }
    }

    pub fn to_lab(&self) -> LabValue {
        //! Convert `LchValue` to `LabValue`
        LabValue {
            l: self.l,
            a: self.c * self.h.to_radians().cos(),
            b: self.c * self.h.to_radians().sin(),
        }
    }

    pub fn round_to(&self, places: i32) -> LchValue {
        //! Round `LchValue` to nearest decimal places.
        LchValue {
            l: round_to(self.l, places),
            c: round_to(self.c, places),
            h: round_to(self.h, places),
        }       
    }

    pub fn to_a(&self) -> [f32; 3] {
        //! Returns an array of [L, c, h]
        [self.l, self.c, self.h]
    }

    pub fn to_vec(&self) -> Vec<f32> {
        //! Returns a `Vec<f32>` of [L, c, h]
        vec![self.l, self.c, self.h]
    }
}

impl Default for LchValue {
    fn default() -> LchValue {
        LchValue { l: 0.0, c: 0.0, h: 0.0 }
    }
}

impl FromStr for LchValue {
    type Err = ValueError;

    fn from_str(s: &str) -> ValueResult<LchValue> {
        //! New `LchValue` from `&str`
        let split = parse_str_to_vecf32(s, 3)?;

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

impl fmt::Display for LchValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[L:{}, c:{}, h:{}]", self.l, self.c, self.h)
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct XyzValue {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

impl XyzValue {
    pub fn new(x: f32, y: f32, z:f32) -> ValueResult<XyzValue> {
        //! New `XyzValue` from 3 `f32`s
        XyzValue { x, y, z}.validate()
    }

    pub fn to_lab(&self) -> LabValue {
        xyz_to_lab([self.x, self.y, self.z])
    }

    pub fn round_to(&self, places: i32) -> XyzValue {
        XyzValue {
            x: round_to(self.x, places),
            y: round_to(self.y, places),
            z: round_to(self.z, places),
        }
    }

    fn validate(self) -> ValueResult<XyzValue> {
        // Check that the XYZ values are in the proper range or Error
        if self.x < 0.0 || self.x > 1.0 ||
        self.y < 0.0 || self.y > 1.0 ||
        self.z < 0.0 || self.z > 1.0
        {
            Err(ValueError::OutOfBounds)
        } else {
            Ok(self)
    }
}

}

impl Default for XyzValue {
    fn default() -> XyzValue {
        XyzValue { x: 0.0, y: 0.0, z: 0.0 }
    }
}

impl FromStr for XyzValue {
    type Err = ValueError;

    fn from_str(s: &str) -> ValueResult<XyzValue> {
        //! New `XyzValue` from `&str`
        let split = parse_str_to_vecf32(s, 3)?;

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

}

impl fmt::Display for XyzValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[X:{}, Y:{}, Z:{}]", self.x, self.y, self.z)
    }
}

#[derive(Debug)]
pub enum ValueError {
    OutOfBounds,
    BadFormat,
}

pub type ValueResult<T> = Result<T, ValueError>;

impl fmt::Display for ValueError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl Error for ValueError {
    fn description(&self) -> &str {
        match self {
            ValueError::OutOfBounds => "Value is out of range!",
            ValueError::BadFormat   => "Value is malformed!",
        }
    }
}

fn parse_str_to_vecf32(s: &str, length: usize) -> ValueResult<Vec<f32>> {
    // Validate and convert strings to `LabValue`.
    // Split string by comma (92.5,33.5,-18.8).
    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)
}

const KAPPA: f32 = 24389.0 / 27.0;
const EPSILON: f32 = 216.0 / 24389.0;
const CBRT_EPSILON: f32 = 0.20689655172413796;

fn lab_to_xyz(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 {
        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 {
        fz.powi(3)
    } else {
        ((fz * 116.0) - 16.0) / KAPPA
    };

    XyzValue {
        x: xr * 0.95047,
        y: yr,
        z: zr * 1.08883,
    }
}

#[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
    }
}

fn xyz_to_lab(xyz: [f32; 3]) -> LabValue {
    let x = xyz_to_lab_map(xyz[0] / 0.95047);
    let y = xyz_to_lab_map(xyz[1]);
    let z = xyz_to_lab_map(xyz[2] / 1.08883);

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