yagii 0.1.3

Yet Another Github style Identicon Implementation
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// Copyright (c) 2018 Sadaie Matsudaira (sadaie)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#![feature(rust_2018_preview, const_fn)]

//! # YAGII
//! **YAGII** stands for *Yet Another Github style Identicon Implementation* and is pronounced \[jɐɣi\].

use digest::{ExtendableOutput, Input, XofReader};
use failure::Fail;
use image::{Rgb, RgbImage};
use log::{debug, log};
use sha3::Shake128;

mod hsl;

/// Errors represent the reason why the identicon generating fails.
#[derive(Debug, Fail)]
pub enum Error {
    /// The parameter `chunk_size_in_pixel` is invalid.
    #[fail(display = "The chunk size must be 1 or above.")]
    InvalidChunkSizeError,

    /// The parameter `width_in_chunk`, `height_in_chunk` or both is/are invalid.
    #[fail(display = "The dimensions must be 1 or above.")]
    InvalidDimensionsError,
}

/// Configuration to use to decide chunk size.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChunkConfig {
    /// Square chunk.
    /// The value represents width and height size in pixel.
    Square(u32),
    /// Rectangle chunk.
    /// The first value represents width size and the second represents height in pixel.
    Rectangle(u32, u32),
}

impl ChunkConfig {
    fn validate(self) -> Result<(u32, u32), Error> {
        match self {
            ChunkConfig::Square(s) => if s > 0 {
                Ok((s, s))
            } else {
                Err(Error::InvalidChunkSizeError)
            },
            ChunkConfig::Rectangle(w, h) => if w > 0 && h > 0 {
                Ok((w, h))
            } else {
                Err(Error::InvalidChunkSizeError)
            },
        }
    }
}

/// Size configuration.
/// The values represent the size in chunk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Dimensions(pub u32, pub u32);

impl Dimensions {
    fn validate(self) -> Result<(u32, u32), Error> {
        if self.0 > 0 && self.1 > 0 {
            Ok((self.0, self.1))
        } else {
            Err(Error::InvalidDimensionsError)
        }
    }
}

fn is_colored_chunk<M, R>(bitmap_data_matrix: M, width: u32, x: u32, y: u32) -> bool
where
    M: AsRef<[R]>,
    R: AsRef<[bool]>,
{
    // x -> opposite point or as it is
    fn f(x: u32, w: u32) -> u32 {
        if x < w / 2 {
            w - (x + 1)
        } else {
            x
        }
    };

    // x -> real index in the chunk
    fn g(x: u32, w: u32, c: u32) -> u32 {
        if w % 2 == 0 {
            x - c
        } else {
            x - (c - 1)
        }
    }

    let chunk_size = (width as f32 / 2.0).ceil() as u32;
    let x = g(f(x, width), width, chunk_size) as usize;
    let y = y as usize;

    let chunk = bitmap_data_matrix.as_ref()[y].as_ref();
    chunk[x]
}

fn convert_bitmap_data_matrix<M, R>(origin: M) -> Vec<Vec<bool>>
where
    M: AsRef<[R]>,
    R: AsRef<[bool]>,
{
    let origin = origin.as_ref();
    let inner_size = origin[0].as_ref().len();
    let mut output = Vec::with_capacity(inner_size);

    let outer_size = origin.len();
    for j in 0..inner_size {
        let mut inner = Vec::with_capacity(inner_size);

        for i in 0..outer_size {
            let value = origin[i].as_ref()[j];
            inner.push(value)
        }

        output.push(inner);
    }

    output
}

fn chunk_coordinates_from_pixel_point(
    chunk_size_width_in_pixel: u32,
    chunk_size_height_in_pixel: u32,
    pixel_x: u32,
    pixel_y: u32,
) -> (u32, u32) {
    let x = pixel_x / chunk_size_width_in_pixel;
    let y = pixel_y / chunk_size_height_in_pixel;
    (x, y)
}

fn bytes_array_to_hex_string(bytes: &[u8]) -> String {
    bytes
        .iter()
        .fold(String::new(), |mut accm, v| {
            accm.push_str(&format!("{:02x}", v));
            accm
        })
}

/// Generates identicon.
///
/// If invalid `chunk_config` and/or `dimensions` is/are given, this function returns error.
/// 
/// # Example
/// 
/// ```
/// use yagii::{Dimensions, ChunkConfig, generate_identicon};
/// 
/// // Chunk is 70 pixel square.
/// let chunk_config = ChunkConfig::Square(70);
/// // 5 chunks square.
/// let dimensions = Dimensions(5, 5);
/// 
/// let image = generate_identicon("some data".as_bytes(), chunk_config, dimensions);
/// 
/// assert!(image.is_ok());
/// ```
pub fn generate_identicon(
    data_to_digest: &[u8],
    chunk_config: ChunkConfig,
    dimensions: Dimensions,
) -> Result<RgbImage, failure::Error> {
    let (chunk_size_width_in_pixel, chunk_size_height_in_pixel) = chunk_config.validate()?;
    let (width, height) = dimensions.validate()?;

    let matrix_length = height * (width as f32 / 2.0).ceil() as u32;

    // 3 chars to use as hue, 2 chars to use as saturation, 2 chars to use as lightness
    let capacity = (((matrix_length as f32 + 3.0 + 2.0 + 2.0) / 2.0).ceil()) as usize;
    let mut buffer = vec![0u8; capacity];
    let mut hasher = Shake128::default();
    hasher.process(data_to_digest);
    hasher.xof_result().read(&mut buffer);
    let digest_string = bytes_array_to_hex_string(&buffer);

    debug!("digest: {} - {} chars", digest_string, digest_string.len());

    let mut digest = digest_string.chars();
    let bitmap_data_matrix = digest
        .by_ref()
        .take(matrix_length as usize)
        .filter_map(|c| c.to_digit(16).map(|v| v % 2 == 0))
        .collect::<Vec<_>>();

    let bitmap_data_matrix = bitmap_data_matrix
        .chunks(height as usize)
        .collect::<Vec<_>>();
    let bitmap_data_matrix = convert_bitmap_data_matrix(&bitmap_data_matrix);

    let hue = digest.by_ref().take(3).collect::<String>();
    debug!("hue: {}", hue);
    let hue = u32::from_str_radix(&hue, 16).map(|v| v as f32 * (360.0 / 4095.0))?;

    let saturation = digest.by_ref().take(2).collect::<String>();
    debug!("saturation: {}", saturation);
    let saturation =
        u32::from_str_radix(&saturation, 16).map(|v| 65.0 - v as f32 * 20.0 / 255.0)?;

    let lightness = digest.take(2).collect::<String>();
    debug!("lightness: {}", lightness);
    let lightness = u32::from_str_radix(&lightness, 16).map(|v| 75.0 - v as f32 * 20.0 / 255.0)?;

    let color = hsl::convert_hsl_to_rgb(hue, saturation, lightness);

    let image_width_in_pixel = chunk_size_width_in_pixel * width;
    let image_height_in_pixel = chunk_size_height_in_pixel * height;

    let image = RgbImage::from_fn(image_width_in_pixel, image_height_in_pixel, |x, y| {
        let (chunk_x, chunk_y) = chunk_coordinates_from_pixel_point(
            chunk_size_width_in_pixel,
            chunk_size_height_in_pixel,
            x,
            y,
        );
        if is_colored_chunk(&bitmap_data_matrix, width, chunk_x, chunk_y) {
            color
        } else {
            Rgb {
                data: [0xff, 0xff, 0xff],
            }
        }
    });

    Ok(image)
}

#[test]
fn test_is_colored_chunk_5x2() {
    let linear_array = [true, false, false, true, false, false];

    let linear_array = linear_array.chunks(2).collect::<Vec<_>>();
    let linear_array = convert_bitmap_data_matrix(&linear_array);

    assert_eq!(is_colored_chunk(&linear_array, 5, 0, 0), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 1, 0), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 2, 0), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 3, 0), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 4, 0), false);

    assert_eq!(is_colored_chunk(&linear_array, 5, 0, 1), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 1, 1), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 2, 1), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 3, 1), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 4, 1), false);
}

#[test]
fn test_is_colored_chunk_5x5() {
    let linear_array = [
        true, false, false, true, false, false, true, true, true, false, true, false, true, false,
        false,
    ];

    let linear_array = linear_array.chunks(5).collect::<Vec<_>>();
    let linear_array = convert_bitmap_data_matrix(&linear_array);

    assert_eq!(is_colored_chunk(&linear_array, 5, 0, 0), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 1, 0), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 2, 0), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 3, 0), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 4, 0), true);

    assert_eq!(is_colored_chunk(&linear_array, 5, 0, 1), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 1, 1), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 2, 1), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 3, 1), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 4, 1), false);

    assert_eq!(is_colored_chunk(&linear_array, 5, 0, 2), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 1, 2), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 2, 2), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 3, 2), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 4, 2), true);

    assert_eq!(is_colored_chunk(&linear_array, 5, 0, 3), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 1, 3), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 2, 3), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 3, 3), true);
    assert_eq!(is_colored_chunk(&linear_array, 5, 4, 3), false);

    assert_eq!(is_colored_chunk(&linear_array, 5, 0, 4), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 1, 4), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 2, 4), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 3, 4), false);
    assert_eq!(is_colored_chunk(&linear_array, 5, 4, 4), false);
}

#[test]
fn test_is_colored_chunk_6x6() {
    let linear_array = [
        true, false, false, true, true, false, false, true, true, false, true, false, true, true,
        false, false, true, false,
    ];

    let linear_array = linear_array.chunks(6).collect::<Vec<_>>();
    let linear_array = convert_bitmap_data_matrix(&linear_array);

    assert_eq!(is_colored_chunk(&linear_array, 6, 0, 0), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 1, 0), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 2, 0), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 3, 0), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 4, 0), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 5, 0), true);

    assert_eq!(is_colored_chunk(&linear_array, 6, 0, 1), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 1, 1), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 2, 1), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 3, 1), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 4, 1), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 5, 1), true);

    assert_eq!(is_colored_chunk(&linear_array, 6, 0, 2), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 1, 2), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 2, 2), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 3, 2), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 4, 2), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 5, 2), false);

    assert_eq!(is_colored_chunk(&linear_array, 6, 0, 3), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 1, 3), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 2, 3), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 3, 3), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 4, 3), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 5, 3), false);

    assert_eq!(is_colored_chunk(&linear_array, 6, 0, 4), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 1, 4), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 2, 4), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 3, 4), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 4, 4), true);
    assert_eq!(is_colored_chunk(&linear_array, 6, 5, 4), true);

    assert_eq!(is_colored_chunk(&linear_array, 6, 0, 5), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 1, 5), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 2, 5), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 3, 5), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 4, 5), false);
    assert_eq!(is_colored_chunk(&linear_array, 6, 5, 5), false);
}

#[test]
fn test_convert_bitmap_data_matrix() {
    let chunks = [
        [true, true, false, true, false],
        [false, true, false, false, true],
        [true, false, true, true, false],
    ];

    let result = convert_bitmap_data_matrix(&chunks);

    assert_eq!(result[0], &[true, false, true]);
    assert_eq!(result[1], &[true, true, false]);
    assert_eq!(result[2], &[false, false, true]);
    assert_eq!(result[3], &[true, false, true]);
    assert_eq!(result[4], &[false, true, false]);
}

#[test]
fn test_chunk_coordinates_from_pixel_point() {
    assert_eq!(chunk_coordinates_from_pixel_point(10, 10, 0, 0), (0, 0));
    assert_eq!(chunk_coordinates_from_pixel_point(10, 10, 9, 9), (0, 0));
    assert_eq!(chunk_coordinates_from_pixel_point(10, 10, 10, 10), (1, 1));
    assert_eq!(chunk_coordinates_from_pixel_point(10, 10, 11, 11), (1, 1));
    assert_eq!(
        chunk_coordinates_from_pixel_point(10, 10, 123, 123),
        (12, 12)
    );

    assert_eq!(chunk_coordinates_from_pixel_point(70, 70, 0, 0), (0, 0));
    assert_eq!(chunk_coordinates_from_pixel_point(70, 70, 70, 70), (1, 1));
    assert_eq!(chunk_coordinates_from_pixel_point(70, 70, 95, 10), (1, 0));
    assert_eq!(chunk_coordinates_from_pixel_point(70, 70, 300, 200), (4, 2));
    assert_eq!(chunk_coordinates_from_pixel_point(70, 70, 349, 349), (4, 4));
}

#[test]
fn test_generate_identicon() {
    let chunk_config = ChunkConfig::Square(1);
    let dimensions = Dimensions(5, 5);
    let image = generate_identicon(&[], chunk_config, dimensions);

    assert!(image.is_ok());

    let image = image.unwrap();

    const PURPLE: [u8; 3] = [222, 133, 220];
    const WHITE: [u8; 3] = [255, 255, 255];
    const TEST_IMAGE: [[u8; 3]; 25] = [
        PURPLE, WHITE, WHITE, WHITE, PURPLE, WHITE, PURPLE, WHITE, PURPLE, WHITE, PURPLE, PURPLE,
        WHITE, PURPLE, PURPLE, PURPLE, PURPLE, PURPLE, PURPLE, PURPLE, WHITE, PURPLE, PURPLE,
        PURPLE, WHITE,
    ];

    let test_image = TEST_IMAGE
        .iter()
        .flatten()
        .map(|v| *v)
        .collect::<Vec<_>>();

    assert_eq!(image.into_raw(), test_image);
}