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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! A lightweight library to get Ethereum blockies raw data,
//! which can be used for creating blockies icon images, printing to terminal, etc.
//!
//! Useful when getting raw data of Ethereum blockies, not a full image file.
//!
//! * Rust implementation of following JavaScript package: <https://www.npmjs.com/package/ethereum-blockies-base64>
//!
//!
//! # Example
//!
//! * For all functions, each address argument for Ethereum (`eth_addr`) should be all lowercase, with leading '`0x`'.  
//!   This can be done with [`addr_canonicalize`](eth_addr::EthAddr::addr_canonicalize).
//! ```
//! use eth_blockies::*;
//!
//! // "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC"
//! // -> "0xe686c14ff9c11038f2b1c9ad617f2346cfb817dc"
//! let addr =
//!     "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC".to_owned()
//!     .addr_canonicalize();
//! assert_eq!(addr, "0xe686c14ff9c11038f2b1c9ad617f2346cfb817dc");
//!
//! let blockies_data = eth_blockies_data(addr);
//! ```
//!
//! * Get a raw blockies data
//! ```
//! use eth_blockies::*;
//!
//! let addr = "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC"
//!      .addr_canonicalize();
//!
//!
//! // get 2D array of (r, g, b)
//! {
//!     let blockies_data_rgb = eth_blockies_data(&addr);
//! }
//!
//!
//! // get 2D array of grayscale
//! {
//!     fn rgb_to_grayscale((r, g, b): RgbPixel) -> u8 {
//!         (r as f64 * 0.299 + g as f64 * 0.587 + b as f64 * 0.114)
//!             as u8
//!     }
//!
//!     let blockies_data_grayscale =
//!         eth_blockies_data_mapped(&addr, rgb_to_grayscale);
//! }
//!
//!
//! // get (color palette, palette index of each pixel)
//! {
//!     let (color_palette, palette_idx_bitmap) =
//!         eth_blockies_indexed_data(&addr);
//!
//!     assert_eq!(
//!         color_palette[palette_idx_bitmap[0][0]],
//!         (132, 222, 77)
//!     );
//! }
//! ```
//!
//!
//!
//! * Write a generated blockies to png file `text.png`,
//!   on Rust binary/library target
//! ```
//! use eth_blockies::*;
//!
//! let addr = "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC"
//!      .addr_canonicalize();
//! let dimension = (128, 128);
//! let img_png_data = eth_blockies_png_data(addr, dimension);
//!
//! use std::io::Write;
//! std::fs::File::create("test.png").unwrap()
//!     .write_all(&img_png_data);
//! ```
//!
//!
//!
//! * Generate an html `img` element of a generated blockies, on wasm target
//! ```ignore
//! // addr to blockies data_uri,
//! // which can be used directly in img elem 'src' or css 'url()'
//! fn eth_blockies_data_uri(addr: &str) -> Option<String> {
//!     use eth_blockies::*;
//!
//!     let img_data_base64 =
//!         eth_blockies_png_data_base64(
//!             addr.addr_canonicalize(),
//!             (8, 8)
//!         );
//!
//!     String::from_utf8(img_data_base64)
//!         .map(|data| "data:image/png;base64,".to_owned() + &data)
//!         .ok()
//! }
//!
//! use web_sys::*;
//!
//! let addr = "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC";
//!
//! window()
//!     .and_then(|w| w.document())
//!     .and_then(|doc| doc.body().zip(doc.create_element("img").ok()))
//!     .and_then(|(body, img)| {
//!         // set data uri to img src
//!         eth_blockies_data_uri(addr)
//!             .and_then(|data_uri|
//!                 img.set_attribute("src", &data_uri).ok()
//!             );
//!
//!         img.set_attribute(
//!             "style",
//!             concat!(
//!                 // no blur on scaling
//!                 "image-rendering: pixelated !important; ",
//!                 "width: 120px; height: 120px;",
//!             ),
//!         );
//!
//!         body.append_child(&img).ok()
//!     });
//! ```

#![no_std]
extern crate alloc;
use alloc::vec::Vec;
use core::{
    mem::{transmute, MaybeUninit},
    ptr::addr_of_mut,
};

mod colorclass;
pub use colorclass::{ColorClass, ColorClassArrayMap};
mod eth_addr;
pub use eth_addr::EthAddr;
mod indexed_png;
use indexed_png::*;

/// Unit RGB pixel data
pub type RgbPixel = (u8, u8, u8);

/// Dimension of Ethereum blockies data
const BLOCKIES_SIZE: usize = 8;

/// Ethereum blockies row data with type `T`
pub type EthBlockiesRow<T> = [T; BLOCKIES_SIZE];
/// Ethereum blockies data with type `T`
pub type EthBlockies<T> = [EthBlockiesRow<T>; BLOCKIES_SIZE];

/// Array map of colors composing Ethereum blockies
///
/// # Example
/// ```
/// use eth_blockies::*;
///
/// let colorclass_map: Palette = [(0, 0, 0), (127, 127, 127), (255, 255, 255)];
///
/// assert_eq!(colorclass_map[ColorClass::BgColor], (0, 0, 0));
/// assert_eq!(colorclass_map[ColorClass::Color], (127, 127, 127));
/// assert_eq!(colorclass_map[ColorClass::SpotColor], (255, 255, 255));
/// ```
pub type Palette = ColorClassArrayMap<RgbPixel>;

/// Get Ethereum blockies data
///
/// # Arguments
///
/// * `eth_addr` - Ethereum address
///
/// # Return
///
/// * 2D array of [`RgbPixel`]
///
/// # Example
/// ```
/// use eth_blockies::*;
/// let addr = "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC"
///     .addr_canonicalize();
/// let blockies_data_rgb = eth_blockies_data(addr);
///
/// let COLORS: Palette = [(38, 173, 52), (132, 222, 77), (4, 201, 40)];
///
/// assert_eq!(blockies_data_rgb, [ [
///         COLORS[1], COLORS[1], COLORS[1], COLORS[1],
///         COLORS[1], COLORS[1], COLORS[1], COLORS[1],
///     ], [
///         COLORS[1], COLORS[0], COLORS[0], COLORS[2],
///         COLORS[2], COLORS[0], COLORS[0], COLORS[1],
///     ], [
///         COLORS[2], COLORS[1], COLORS[1], COLORS[0],
///         COLORS[0], COLORS[1], COLORS[1], COLORS[2],
///     ], [
///         COLORS[0], COLORS[0], COLORS[2], COLORS[0],
///         COLORS[0], COLORS[2], COLORS[0], COLORS[0],
///     ], [
///         COLORS[1], COLORS[0], COLORS[1], COLORS[2],
///         COLORS[2], COLORS[1], COLORS[0], COLORS[1],
///     ], [
///         COLORS[1], COLORS[2], COLORS[1], COLORS[2],
///         COLORS[2], COLORS[1], COLORS[2], COLORS[1],
///     ], [
///         COLORS[0], COLORS[2], COLORS[1], COLORS[2],
///         COLORS[2], COLORS[1], COLORS[2], COLORS[0],
///     ], [
///         COLORS[1], COLORS[0], COLORS[0], COLORS[1],
///         COLORS[1], COLORS[0], COLORS[0], COLORS[1],
///     ], ]
/// );
/// ```
///
#[allow(dead_code)]
pub fn eth_blockies_data<W: EthAddr>(eth_addr: W) -> EthBlockies<RgbPixel> {
    eth_blockies_data_mapped(eth_addr, |rgb_pixel| rgb_pixel)
}

/// Get Ethereum blockies data in mapped format with `map_fn`
///
/// Same with [`eth_blockies_data`],  
/// except that each [`RgbPixel`] output is mapped
/// with the function argument `map_fn` \(input mapping function\)
///
/// # Arguments
///
/// * `eth_addr` - Ethereum address
/// * `map_fn` - Mapping function for each element in array return
///
/// # Return
///
/// * 2D array of `T`, which is returned by `map_fn`
///
/// # Example
/// ```
/// use eth_blockies::*;
///
/// fn rgb_to_grayscale((r, g, b): RgbPixel) -> u8 {
///     (r as f64 * 0.299 + g as f64 * 0.587 + b as f64 * 0.114) as u8
/// }
///
/// let addr = "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC"
///     .addr_canonicalize();
/// let blockies_data_grayscale = eth_blockies_data_mapped(addr, rgb_to_grayscale);
///
/// assert_eq!(blockies_data_grayscale, [
///        [178, 178, 178, 178, 178, 178, 178, 178],
///        [178, 118, 118, 123, 123, 118, 118, 178],
///        [123, 178, 178, 118, 118, 178, 178, 123],
///        [118, 118, 123, 118, 118, 123, 118, 118],
///        [178, 118, 178, 123, 123, 178, 118, 178],
///        [178, 123, 178, 123, 123, 178, 123, 178],
///        [118, 123, 178, 123, 123, 178, 123, 118],
///        [178, 118, 118, 178, 178, 118, 118, 178],
///    ]);
/// ```
///
#[allow(dead_code)]
pub fn eth_blockies_data_mapped<W: EthAddr, T: Clone, F: Fn(RgbPixel) -> T>(
    eth_addr: W,
    map_fn: F,
) -> EthBlockies<T> {
    let (palette, class_bitmap) = eth_blockies_indexed_data(eth_addr);

    // initialize ret_bitmap using MaybeUninit
    {
        let mut ret_bitmap_uninit: MaybeUninit<EthBlockies<T>> = MaybeUninit::uninit();

        class_bitmap
            .iter()
            .enumerate()
            .for_each(|(idx_row, class_row)| {
                class_row.iter().enumerate().for_each(|(idx, class)| {
                    let value = map_fn(palette[class]);

                    unsafe {
                        addr_of_mut!(
                            // calculate current bitmap ptr address
                            (*ret_bitmap_uninit.as_mut_ptr())[idx_row][idx]
                        )
                        .write_unaligned(value)
                    };
                });
            });

        unsafe { ret_bitmap_uninit.assume_init() }
    }
}

/// Get Ethereum blockies data in indexed image format
///
/// # Arguments
///
/// * `eth_addr` - Ethereum address
///
/// # Return
///
/// * A tuple of [(](tuple) `Array of colors`, `2D array of color indices` [)](tuple)
///
/// # Example
/// ```
/// use eth_blockies::*;
/// let addr = "0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC"
///     .addr_canonicalize();
/// let (color_palette, palette_idx_bitmap) = eth_blockies_indexed_data(addr);
///
/// // get (r, g, b) from palette
/// assert_eq!(color_palette[ColorClass::BgColor], (38, 173, 52));
/// assert_eq!(color_palette[ColorClass::Color], (132, 222, 77));
/// assert_eq!(color_palette[ColorClass::SpotColor], (4, 201, 40));
///
/// // get color class from pixels
/// assert_eq!(palette_idx_bitmap[0][0], ColorClass::Color);
/// assert_eq!(palette_idx_bitmap[2][0], ColorClass::SpotColor);
/// assert_eq!(palette_idx_bitmap[1][1], ColorClass::BgColor);
///
/// // get (r, g, b) from pixels
/// assert_eq!(color_palette[palette_idx_bitmap[0][0]], (132, 222, 77));
/// assert_eq!(color_palette[palette_idx_bitmap[2][0]], (4, 201, 40));
/// assert_eq!(color_palette[palette_idx_bitmap[1][1]], (38, 173, 52));
/// ```
///
#[allow(dead_code)]
pub fn eth_blockies_indexed_data<W: EthAddr>(eth_addr: W) -> (Palette, EthBlockies<ColorClass>) {
    let mut keygen = BlockiesGenerator::new(eth_addr.addr_as_ref().as_bytes());

    // initialize palette using MaybeUninit
    let palette = {
        let mut palette_uninit: MaybeUninit<Palette> = MaybeUninit::uninit();
        [
            ColorClass::Color,
            ColorClass::BgColor,
            ColorClass::SpotColor,
        ]
        .iter()
        .for_each(|class| unsafe {
            addr_of_mut!((*palette_uninit.as_mut_ptr())[class]).write_unaligned(keygen.next_rgb())
        });
        unsafe { palette_uninit.assume_init() }
    };

    // initialize bitmap using MaybeUninit
    let bitmap = {
        // MaybeUninit::uninit().assume_init() here is safe:
        //   https://doc.rust-lang.org/core/mem/union.MaybeUninit.html#initializing-an-array-element-by-element
        let mut bitmap_uninit: EthBlockies<MaybeUninit<ColorClass>> =
            unsafe { MaybeUninit::uninit().assume_init() };

        bitmap_uninit
            .iter_mut()
            .map(|row| (row.len() / 2, row))
            .map(|(mid_idx, row)| row.split_at_mut(mid_idx))
            .for_each(|(left, right)| {
                left.iter_mut()
                    .chain(
                        // dummy chain on left, in case of odd width
                        [MaybeUninit::uninit()].iter_mut(),
                    )
                    .zip(right.iter_mut().rev())
                    .for_each(|(l, r)| {
                        let colorclass = keygen.next_colorclass();
                        l.write(colorclass);
                        r.write(colorclass);
                    });
            });

        unsafe { transmute(bitmap_uninit) }
    };

    (palette, bitmap)
}

/// Get Ethereum blockies data in indexed png format
///
/// * For image file
/// ```
/// use eth_blockies::*;
///
/// let addr = String::from("0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC")
///     .addr_canonicalize();
/// let img_png_data = eth_blockies_png_data(addr, (128, 128));
///
/// // use std::io::Write;
/// // std::fs::File::create("test.png").unwrap().write_all(&img_png_data);
/// ```
pub fn eth_blockies_png_data<W: EthAddr>(eth_addr: W, dimension: (u32, u32)) -> Vec<u8> {
    indexed_data_to_png(eth_blockies_indexed_data(eth_addr), dimension)
}

/// Get Ethereum blockies data in base64 format of indexed png
///
/// ```
/// use eth_blockies::*;
///
/// let addr = String::from("0xe686c14FF9C11038F2B1c9aD617F2346CFB817dC")
///     .addr_canonicalize();
/// let img_png_data = eth_blockies_png_data_base64(addr, (8, 8));
///
/// // use std::io::Write;
/// // let mut f = std::fs::File::create("test.png.base64").unwrap();
/// // f.write_all(b"data:image/png;base64,");
/// // f.write_all(&img_png_data);
/// ```
pub fn eth_blockies_png_data_base64<W: EthAddr>(eth_addr: W, dimension: (u32, u32)) -> Vec<u8> {
    indexed_data_to_png_base64(eth_blockies_indexed_data(eth_addr), dimension)
}

/// Ethereum blockies generator, which stores necessary seeds for creating blockies
struct BlockiesGenerator {
    /// Seeds for generating ethereum blockies  
    /// (Named as "randseed" in original implementation)
    key_seeds: [i32; BlockiesGenerator::KEY_SEEDS_LEN],
    /// Current index of key_seeds to update when next_key runs
    key_seed_curidx: usize,
}

impl BlockiesGenerator {
    const KEY_SEEDS_LEN: usize = 4;

    /// Initialize new ethereum blockies generator using a given seed byte sequences
    fn new(seed: &[u8]) -> Self {
        Self {
            key_seeds: (seed.chunks(BlockiesGenerator::KEY_SEEDS_LEN).fold(
                [0_i32; BlockiesGenerator::KEY_SEEDS_LEN],
                |mut key_seeds_acc, seed_chunks| {
                    key_seeds_acc.iter_mut().zip(seed_chunks.iter()).for_each(
                        |(key_seed_cur, seed_char_cur)| {
                            *key_seed_cur = Self::key_seed_init(*key_seed_cur, *seed_char_cur)
                        },
                    );

                    key_seeds_acc
                },
            )),
            key_seed_curidx: 0,
        }
    }

    /// Update single element in key_seeds for initialization
    fn key_seed_init(key_seed_cur: i32, seed_char_cur: u8) -> i32 {
        (key_seed_cur << 5)
            .overflowing_sub(key_seed_cur)
            .0
            .overflowing_add(seed_char_cur as i32)
            .0
    }

    /// Get previous index of key_seeds
    fn idx_prev(idx: usize) -> usize {
        idx.overflowing_sub(1).0 % BlockiesGenerator::KEY_SEEDS_LEN
    }

    /// Get next index of key_seeds
    fn idx_next(idx: usize) -> usize {
        idx.overflowing_add(1).0 % BlockiesGenerator::KEY_SEEDS_LEN
    }

    /// Get next computed key using key_seeds, which is used for blockies generation
    /// Returns f64 in range: [0, 1]
    fn next_key(&mut self) -> f64 {
        self.key_seeds
            .get(Self::idx_prev(self.key_seed_curidx))
            .zip(self.key_seeds.get(self.key_seed_curidx))
            // calc new cur val
            .map(|(key_seed_prev, key_seed_cur)| {
                let tmp = *key_seed_cur ^ (*key_seed_cur << 11);
                *key_seed_prev ^ (*key_seed_prev >> 19) ^ tmp ^ (tmp >> 8)
            })
            // update self members
            .and_then(|key_seed_new_cur| {
                self.key_seeds
                    .get_mut(self.key_seed_curidx)
                    .map(|key_seed_cur_mut| {
                        self.key_seed_curidx = Self::idx_next(self.key_seed_curidx);

                        *key_seed_cur_mut = key_seed_new_cur;
                        key_seed_new_cur
                    })
            })
            // map to return val: map key_seed_new_cur in [0, 1] range
            .map(|key_seed_new_cur| {
                key_seed_new_cur.unsigned_abs() as f64 / ((i32::MAX as u32 + 1) as f64)
            })
            .expect("next_key")
    }

    /// Get next RGB pixel for palette using key_seeds
    fn next_rgb(&mut self) -> RgbPixel {
        fn hsl_to_rgb(hue: u32, saturation: f64, lightness: f64) -> RgbPixel {
            fn hue_to_rgb(p: f64, q: f64, t: u32) -> f64 {
                let t = match t {
                    0..=359 => t,
                    _ => t % 360,
                };

                return match t {
                    0..=60 => p + (q - p) * t as f64 / 60_f64,
                    0..=180 => q,
                    0..=240 => p + (q - p) * (4_f64 - t as f64 / 60_f64),
                    _ => p,
                };
            }

            let rgb_frac = match saturation == 0_f64 {
                true => (lightness, lightness, lightness),
                false => {
                    let q = match lightness < 0.5 {
                        true => lightness * (1_f64 + saturation),
                        false => lightness + saturation - lightness * saturation,
                    };
                    let p = 2_f64 * lightness - q;
                    (
                        hue_to_rgb(p, q, hue.overflowing_add(120).0),
                        hue_to_rgb(p, q, hue),
                        hue_to_rgb(p, q, hue.overflowing_add(240).0),
                    )
                }
            };

            (
                ((rgb_frac.0 * 255_f64) + 0.5_f64) as u8,
                ((rgb_frac.1 * 255_f64) + 0.5_f64) as u8,
                ((rgb_frac.2 * 255_f64) + 0.5_f64) as u8,
            )
        }

        hsl_to_rgb(
            (self.next_key() * 360_f64) as u32,
            self.next_key() * 0.6_f64 + 0.4_f64,
            (self.next_key() + self.next_key() + self.next_key() + self.next_key()) * 0.25_f64,
        )
    }

    /// Get next color class for current pixel using key_seeds
    fn next_colorclass(&mut self) -> ColorClass {
        ((self.next_key() * 2.3_f64) as u8).try_into().unwrap()
    }
}