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
// Copyright (c) 2020-2022 Weird Constructor <weirdconstructor@gmail.com>
// This is a part of WLambda. See README.md and COPYING for details.

/*!

  Implements utilitiy functions that are used by the WLambda
  standard library. For instance a SplitMix64 random number
  generator.

*/

//- splitmix64 (http://xoroshiro.di.unimi.it/splitmix64.c) 
//"""
//  Written in 2015 by Sebastiano Vigna (vigna@acm.org)
//
//  To the extent possible under law, the author has dedicated all copyright
//  and related and neighboring rights to this software to the public domain
//  worldwide. This software is distributed without any warranty.
//
//  See <http://creativecommons.org/publicdomain/zero/1.0/>. 
//"""
//
// Written by Alexander Stocko <as@coder.gg>
//
// To the extent possible under law, the author has dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// See <LICENSE or http://creativecommons.org/publicdomain/zero/1.0/>


use std::num::Wrapping as w;
use std::cell::RefCell;

thread_local! {
    static RAND_STATE: RefCell<SplitMix64> =
        RefCell::new(SplitMix64::new(1_234_567_890));
}

pub fn srand(seed: i64) {
    RAND_STATE.with(|si| {
        *si.borrow_mut() = SplitMix64::new(seed as u64);
    })
}

pub fn rand_closed_open01() -> f64 {
    RAND_STATE.with(|si| {
        u64_to_closed_open01(si.borrow_mut().next_u64())
    })
}

pub fn rand_i(max: u64) -> i64 {
    RAND_STATE.with(|si| {
        (si.borrow_mut().next_u64() % max) as i64
    })
}

pub fn rand_full_i() -> i64 {
    RAND_STATE.with(|si| {
        si.borrow_mut().next_i64()
    })
}

/// The `SplitMix64` random number generator.
#[derive(Copy, Clone)]
pub struct SplitMix64(pub u64);

impl SplitMix64 {
    pub fn new(seed: u64) -> Self { Self(seed) }
    pub fn new_from_i64(seed: i64) -> Self {
        Self::new(u64::from_be_bytes(seed.to_be_bytes()))
    }

    #[inline]
    pub fn next_u64(&mut self) -> u64 {
        let mut z = w(self.0) + w(0x9E37_79B9_7F4A_7C15_u64);
        self.0 = z.0;
        z = (z ^ (z >> 30)) * w(0xBF58_476D_1CE4_E5B9_u64);
        z = (z ^ (z >> 27)) * w(0x94D0_49BB_1331_11EB_u64);
        (z ^ (z >> 31)).0
    }

    #[inline]
    pub fn next_i64(&mut self) -> i64 {
        i64::from_be_bytes(
            self.next_u64().to_be_bytes())
    }
}

// Taken from rand::distributions
// Licensed under the Apache License, Version 2.0
// Copyright 2018 Developers of the Rand project.
pub fn u64_to_open01(u: u64) -> f64 {
    use core::f64::EPSILON;
    let float_size         = std::mem::size_of::<f64>() as u32 * 8;
    let fraction           = u >> (float_size - 52);
    let exponent_bits: u64 = 1023_u64 << 52;
    f64::from_bits(fraction | exponent_bits) - (1.0 - EPSILON / 2.0)
}

// Taken from rand::distributions
// Licensed under the Apache License, Version 2.0
// Copyright 2018 Developers of the Rand project.
pub fn u64_to_closed_open01(u: u64) -> f64 {
    // Multiply-based method; 24/53 random bits; [0, 1) interval.
    // We use the most significant bits because for simple RNGs
    // those are usually more random.
    let float_size = std::mem::size_of::<f64>() as u32 * 8;
    let precision = 52 + 1;
    let scale = 1.0 / ((1_u64 << precision) as f64);

    let value = u >> (float_size - precision);
    scale * (value as f64)
}

// Taken from rand::distributions
// Licensed under the Apache License, Version 2.0
// Copyright 2018 Developers of the Rand project.
pub fn u64_to_open_closed01(u: u64) -> f64 {
    // Multiply-based method; 24/53 random bits; [0, 1) interval.
    // We use the most significant bits because for simple RNGs
    // those are usually more random.
    let float_size = std::mem::size_of::<f64>() as u32 * 8;
    let precision = 52 + 1;
    let scale = 1.0 / ((1_u64 << precision) as f64);

    let value = u >> (float_size - precision);
    scale * ((value + 1) as f64)
}

/// Original FNV Rust implementation taken from fnv crate on
/// crates.io by Alex Crichton <alex@alexcrichton.com>
/// under Apache-2.0 / MIT license Copyright 2018.
///
/// An implementation of the Fowler–Noll–Vo hash function.
///
/// See the [crate documentation](index.html) for more details.
#[derive(Copy, Clone, Debug)]
pub struct FnvHasher(u64);

impl Default for FnvHasher {
    #[inline]
    fn default() -> FnvHasher {
        FnvHasher(0xcbf2_9ce4_8422_2325)
    }
}

impl FnvHasher {
    #[inline]
    #[allow(dead_code)]
    pub fn with_key(key: u64) -> FnvHasher {
        FnvHasher(key)
    }

    #[inline]
    fn finish(self) -> u64 {
        self.0
    }

    #[inline]
    pub fn finish_i64(self) -> i64 {
        i64::from_be_bytes(
            self.finish().to_be_bytes())
    }

    #[inline]
    pub fn write_f64(&mut self, f: f64) {
            self.write(&f.to_bits().to_be_bytes());
    }

    #[inline]
    pub fn write_i64(&mut self, i: i64) {
        self.write(&i.to_be_bytes());
    }

    #[inline]
    #[allow(clippy::cast_lossless)]
    pub fn write(&mut self, bytes: &[u8]) {
        let FnvHasher(mut hash) = *self;

        for byte in bytes.iter() {
            hash ^= *byte as u64;
            hash = hash.wrapping_mul(0x0100_0000_01b3);
        }

        *self = FnvHasher(hash);
    }
}

pub fn now_timestamp() -> u64 {
    std::time::SystemTime::now()
    .duration_since(std::time::SystemTime::UNIX_EPOCH)
    .unwrap()
    .as_secs() as u64
}

pub fn rgba2hsvaf(rgba: (f64, f64, f64, f64)) -> (f64, f64, f64, f64) {
    let (h, s, v) = rgb2hsv(rgba.0, rgba.1, rgba.2);
    (h, s, v, rgba.3)
}

pub fn rgb2hsv(r: f64, g: f64, b: f64) -> (f64, f64, f64) {
    let c_max = r.max(g.max(b));
    let c_min = r.min(g.min(b));
    let delta = c_max - c_min;
    let mut hue =
        if delta < 0.000_001 { 0.0 }
        else if (r - c_max).abs() < 0.000_001  { 60.0 * (((g - b) / delta) % 6.0) }
        else if (g - c_max).abs() < 0.000_001  { 60.0 * (((b - r) / delta) + 2.0) }
        else                                   { 60.0 * (((r - g) / delta) + 4.0) };
    if hue < 0.0   { hue += 360.0 }
    if hue > 360.0 { hue -= 360.0 }
    let sat = if c_max < 0.000_001 { 0.0 } else { delta / c_max };
    let val = c_max;
    (hue, sat, val)
}

pub fn hsva2rgba(hsva: (f64, f64, f64, f64)) -> (f64, f64, f64, f64) {
    let (r, g, b) = hsv2rgb(hsva.0, hsva.1, hsva.2);
    (r, g, b, hsva.3)
}

pub fn hsv2rgb(hue: f64, sat: f64, val: f64) -> (f64, f64, f64) {
    let c = val * sat;
    let x = c * (1.0 - ((hue / 60.0) % 2.0 - 1.0).abs());
    let m = val - c;
    let (r_, g_, b_) =
        if        (0.0..60.0).contains(&hue) {
            (c, x, 0.0)
        } else if (60.0..120.0).contains(&hue) {
            (x, c, 0.0)
        } else if (120.0..180.0).contains(&hue) {
            (0.0, c, x)
        } else if (180.0..240.0).contains(&hue) {
            (0.0, x, c)
        } else if (240.0..300.0).contains(&hue) {
            (x, 0.0, c)
        } else { // if hue >= 300.0 && hue < 360.0 {
            (c, 0.0, x)
        };
//    println!("in: h={}, s={}, v={}, r:{}, g:{}, b: {}", hue, sat, val,
//        (r_ + m) * 255.0,
//        (g_ + m) * 255.0,
//        (b_ + m) * 255.0);
    (r_ + m, g_ + m, b_ + m)
}

pub fn rgba2hexf(rgba: (f64, f64, f64, f64)) -> String {
    format!("{:02x}{:02x}{:02x}{:02x}",
        (rgba.0 * 255.0).round() as u8,
        (rgba.1 * 255.0).round() as u8,
        (rgba.2 * 255.0).round() as u8,
        (rgba.3 * 255.0).round() as u8)
}

pub fn rgba2hex(rgba: (u8, u8, u8, u8)) -> String {
    format!("{:02x}{:02x}{:02x}{:02x}",
        rgba.0, rgba.1, rgba.2, rgba.3)
}

pub fn hex2hsvaf(s: &str) -> (f64, f64, f64, f64) {
    let (h, s, v, a) = hex2rgbaf(s);
    (h * 360.0, s * 100.0, v * 100.0, a * 100.0)
}

pub fn hsva2hexf(hsva: (f64, f64, f64, f64)) -> String {
    format!("{:02x}{:02x}{:02x}{:02x}",
        ((hsva.0 / 360.0) * 255.0).round() as u8,
        (hsva.1 * 255.0).round() as u8,
        (hsva.2 * 255.0).round() as u8,
        (hsva.3 * 255.0).round() as u8)
}

pub fn hex2rgbaf(hex_str: &str) -> (f64, f64, f64, f64) {
    let (r, g, b, a) = hex2rgba(hex_str);
    (r as f64 / 255.0,
     g as f64 / 255.0,
     b as f64 / 255.0,
     a as f64 / 255.0)
}

fn shiftaddup4(u: u8) -> u8 { (u << 4) | u }

pub fn hex2rgba(s: &str) -> (u8, u8, u8, u8) {
    match s.len() {
        8 => (
            u8::from_str_radix(&s[0..2], 16).unwrap_or(0),
            u8::from_str_radix(&s[2..4], 16).unwrap_or(0),
            u8::from_str_radix(&s[4..6], 16).unwrap_or(0),
            u8::from_str_radix(&s[6..8], 16).unwrap_or(255)
        ),
        6 => (
            u8::from_str_radix(&s[0..2], 16).unwrap_or(0),
            u8::from_str_radix(&s[2..4], 16).unwrap_or(0),
            u8::from_str_radix(&s[4..6], 16).unwrap_or(0),
            255
        ),
        4 => (
            shiftaddup4(u8::from_str_radix(&s[0..1], 16).unwrap_or(0)),
            shiftaddup4(u8::from_str_radix(&s[1..2], 16).unwrap_or(0)),
            shiftaddup4(u8::from_str_radix(&s[2..3], 16).unwrap_or(0)),
            shiftaddup4(u8::from_str_radix(&s[3..4], 16).unwrap_or(0xFF)),
        ),
        3 => (
            shiftaddup4(u8::from_str_radix(&s[0..1], 16).unwrap_or(0)),
            shiftaddup4(u8::from_str_radix(&s[1..2], 16).unwrap_or(0)),
            shiftaddup4(u8::from_str_radix(&s[2..3], 16).unwrap_or(0)),
            255
        ),
        2 => (
            shiftaddup4(u8::from_str_radix(&s[0..1], 16).unwrap_or(0)),
            shiftaddup4(u8::from_str_radix(&s[0..1], 16).unwrap_or(0)),
            shiftaddup4(u8::from_str_radix(&s[0..1], 16).unwrap_or(0)),
            255
        ),
        _ => (255, 0, 255, 255),
    }
}


// Taken from https://github.com/febeling/edit-distance/blob/master/src/lib.rs
// Apache-2.0 License
/// Returns the edit distance between strings `a` and `b`.
///
/// The runtime complexity is `O(m*n)`, where `m` and `n` are the
/// strings' lengths.
#[allow(clippy::needless_range_loop)]
pub fn edit_distance(a: &str, b: &str) -> usize {
    let len_a = a.chars().count();
    let len_b = b.chars().count();
    if len_a < len_b {
        return edit_distance(b, a);
    }
    // handle special case of 0 length
    if len_a == 0 {
        return len_b;
    } else if len_b == 0 {
        return len_a;
    }

    let len_b = len_b + 1;

    let mut pre;
    let mut tmp;
    let mut cur = vec![0; len_b];

    // initialize string b
    for i in 1..len_b {
        cur[i] = i;
    }

    // calculate edit distance
    for (i, ca) in a.chars().enumerate() {
        // get first column for this row
        pre = cur[0];
        cur[0] = i + 1;
        for (j, cb) in b.chars().enumerate() {
            tmp = cur[j + 1];
            cur[j + 1] = std::cmp::min(
                // deletion
                tmp + 1,
                std::cmp::min(
                    // insertion
                    cur[j] + 1,
                    // match or substitution
                    pre + if ca == cb { 0 } else { 1 },
                ),
            );
            pre = tmp;
        }
    }
    cur[len_b - 1]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn util_rgb2hsv() {
        assert_eq!(
            hsva2hexf(rgba2hsvaf(hex2rgbaf("FF0000FF"))),
            "00ffffff");
        assert_eq!(
            hsva2hexf(rgba2hsvaf(hex2rgbaf("00FF00FF"))),
            "55ffffff");
        assert_eq!(
            hsva2hexf(rgba2hsvaf(hex2rgbaf("0000FFFF"))),
            "aaffffff");
        assert_eq!(
            rgba2hsvaf(hex2rgbaf("FF00FFFF")),
            (300.0, 1.0, 1.0, 1.0));
        assert_eq!(
            rgba2hsvaf(hex2rgbaf("00FFFFFF")),
            (180.0, 1.0, 1.0, 1.0));
        assert_eq!(
            rgba2hsvaf(hex2rgbaf("FFFF00FF")),
            (60.0, 1.0, 1.0, 1.0));

        assert_eq!(
            rgba2hexf(hsva2rgba((300.0, 1.0, 1.0, 1.0))),
            "ff00ffff");
        assert_eq!(
            rgba2hexf(hsva2rgba((180.0, 1.0, 1.0, 1.0))),
            "00ffffff");
        assert_eq!(
            rgba2hexf(hsva2rgba((60.0, 1.0, 1.0, 1.0))),
            "ffff00ff");
        assert_eq!(
            rgba2hexf(hsva2rgba((100.0, 0.5, 0.25, 1.0))),
            "2b4020ff");
    }
}