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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
/*
 * This file is part of ids_service
 *
 * ids_service is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * ids_service is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ids_service.  If not, see <http://www.gnu.org/licenses/>
 */

//! Library that allows generating unique ids. It tried to keep cache filled using background threads
//! to fill it.
//! If the cache is empty (the number of requests is too high) an id is calculated on the fly.
//! This will slow down obtaining the id but there is no error when the cache is empty.
//! To generate unique ids the library uses an array of bytes with values from a random number generator
//! and a timestamp as nanoseconds since January 1, 1970 UTC and finally create an hash from both data's.
//! The size of random block is equal to 2 * the size of hash sha512 = 128 bytes.
//! The size of data block to calculate an unique id using sha512 equal 128 bytes random + 8 bytes timestamp.
//!
//! The hash algorithm can be one from crypto::sha3::Sha3Mode
//! The id can be:
//! * Vec<u8>
//! * String encoded hexadecimal lower case
//! * String as Base64
//! * String as Base32
//!
//! # Quick Start
//! ```
//! extern crate ids_service;
//!
//! use crate::ids_service::crypto_hash::{Encode,IdsService};
//!
//! fn main() {
//!
//!     /*
//!      * Create an ids service with:
//!      * Cache size = 10'000
//!      * hash algo. = sha512
//!      * A pool of 20 threads
//!      */
//!     let mut ids = IdsService::default();
//!     ids.start();
//!     println!("Get an id: {}", ids.get_id().as_hex());
//!     println!("Get another id: {}", ids.get_id().as_base64());
//!     println!("Current numbers of items in cache: {}", ids.get_cache_len());
//!     // Graceful Shutdown and Cleanup
//!     ids.stop();
//!
//! }
//! ```
//!
//! ```
//! extern crate ids_service;
//!
//! use crate::ids_service::crypto_hash::*;
//!
//! fn main() {
//!
//!     println!("Create an id sha512 without the service: {}", create_id_as_sha512());
//!     println!("Create an id sha256 without the service: {}", create_id_as_sha256());
//!
//! }
//! ```
//! The lib use simplelog see for configuration:
//! [crates.io Rust Package Registry SimpleLog ](https://crates.io/crates/simplelog).
extern crate chrono;
extern crate crypto;
extern crate data_encoding;
extern crate log;
extern crate rand;
extern crate simplelog;

/// Module using crypto. hash
pub mod crypto_hash {
    use chrono::prelude::*;
    use crypto::digest::Digest;
    use crypto::sha3::Sha3;
    use crypto::sha3::Sha3Mode;
    use data_encoding::{BASE32, BASE64, BASE64URL, HEXLOWER};
    use log::*;
    use rand::prelude::*;
    use std::collections::VecDeque;
    use std::fmt;
    use std::str::FromStr;
    use std::sync::{mpsc,Arc, Mutex};
    use std::thread;
    use std::time::Duration;
    use std::thread::JoinHandle;
    use std::sync::atomic::{AtomicBool,Ordering};

    const NUMBER_OF_FILL_THREAD: usize = 20;

    /// Struct for internal use of IdsService
    pub struct IdsService {
        ids_cache: Arc<Mutex<VecDeque<Vec<u8>>>>,
        cache_size: usize,
        rand_length: usize,
        mode: Sha3Mode,
        number_of_threads: usize,
        threads_pool: Vec<Option<JoinHandle<()>>>,
        stop_state: Arc<AtomicBool>
    }

    ///
    /// Allow to create an instance using default parameters:
    /// * hash algorithm : Sha3_256
    /// * cache size: 100'000 items
    /// * number of threads: 20
    impl Default for IdsService {
        fn default() -> Self {
            let mode = Sha3Mode::Sha3_256;
            let cache_size = 100_000 as usize;
            IdsService {
                ids_cache: Arc::new(Mutex::new(VecDeque::with_capacity(cache_size))),
                // * 2 ? see https://en.m.wikipedia.org/wiki/Birthday_problem#Probability_table
                rand_length: length_for(mode) * 2,
                cache_size,
                mode,
                number_of_threads: NUMBER_OF_FILL_THREAD,
                threads_pool: Vec::with_capacity(NUMBER_OF_FILL_THREAD),
                stop_state: Arc::new(AtomicBool::new(false)),
            }
        }
    }

    impl fmt::Debug for IdsService {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "IdsService {{ ids_cache nb. ids: {}, cache_size: {}, rand_length : {}, mode : {:?}, number_of_threads : {} }}", self.ids_cache.lock().unwrap().len(), self.cache_size, self.rand_length,self.mode, self.number_of_threads)
        }
    }

    /// Trait to define possible encoding output.
    pub trait Encode: Sized {
        fn as_hex(&self) -> String {
            unimplemented!()
        }
        fn as_base64(&self) -> String {
            unimplemented!()
        }
        fn as_base64_url(&self) -> String {
            unimplemented!()
        }
        fn as_base32(&self) -> String {
            unimplemented!()
        }

        fn as_json(&self) -> String {
            unimplemented!()
        }
    }

    /// Implementation for Vec<u8>
    impl Encode for Vec<u8> {
        fn as_hex(&self) -> String {
            HEXLOWER.encode(self)
        }
        fn as_base64(&self) -> String {
            BASE64.encode(self)
        }

        fn as_base64_url(&self) -> String {
            BASE64URL.encode(self)
        }

        fn as_base32(&self) -> String {
            BASE32.encode(self)
        }

        fn as_json(&self) -> String {
            let mut message : String = String::new();
            message.push_str(format!("{{\n\"bytes\" : \"{:?}\",",self).as_str());
            message.push_str(format!("\n\"base64\" : \"{}\",",self.as_base64()).as_str());
            message.push_str(format!("\n\"base32\" : \"{}\",",self.as_base32()).as_str());
            message.push_str(format!("\n\"hex\" : \"0x{}\"\n}}",self.as_hex()).as_str());
            message
        }
    }

    /// Implementation Iterator
    /// # Example
    /// ```
    ///
    /// extern crate ids_service;
    ///
    /// use crate::ids_service::crypto_hash::{Encode,IdsService};
    ///
    /// fn main() {
    ///
    ///     /*
    ///      * Create an ids service with:
    ///      * Cache size = 100'000
    ///      * hash algo. = sha256
    ///      * A pool of 20 threads
    ///      */
    ///     let mut ids = IdsService::default();
    ///     ids.start();
    ///     for id in ids.take(10) {
    ///         println!("Get an id: {}", id.as_base64());
    ///     }
    ///
    /// }
    /// ```
    impl Iterator for IdsService {
        type Item = Vec<u8>;

        fn next(&mut self) -> Option<Self::Item> {
            Some(self.get_id())
        }
    }

    /// Main implementation during creation a thread to fill in cache is started
    /// # Examples
    ///
    /// ```
    /// extern crate ids_service;
    /// extern crate simplelog;
    /// extern crate crypto;
    ///
    /// use crate::ids_service::crypto_hash::{Encode,IdsService};
    /// use crate::simplelog::*;
    /// use crypto::sha3::Sha3Mode;
    /// use std::time::Duration;
    /// use std::thread;
    /// use log::*;
    ///
    /// fn main() {
    ///
    ///     let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
    ///
    ///     /*
    ///      * Create an ids service with:
    ///      * Cache size = 10'000
    ///      * hash algo. = Keccak256
    ///      * A pool of 100 threads
    ///      */
    ///     let mut ids = IdsService::new(10000, Sha3Mode::Keccak256,Some(100 as usize));
    ///     ids.start();
    ///     // Optional: Wait cache is filled
    ///     ids.filled_event().recv().is_ok();
    ///     info!("Current numbers of items in cache: {}", ids.get_cache_len());
    ///     info!("Get an id: {}", ids.get_id().as_hex());
    ///     info!("Get another id: {}", ids.get_id().as_base64());
    ///     info!("Current numbers of items in cache: {}", ids.get_cache_len());
    ///
    /// }
    /// ```
    impl IdsService {
        pub fn new(
            cache_size: usize,
            mode: Sha3Mode,
            number_of_threads: Option<usize>,
        ) -> IdsService {
            // * 2 ? see https://en.m.wikipedia.org/wiki/Birthday_problem#Probability_table
            let rand_length = length_for(mode) * 2;
            let threads = match number_of_threads {
                Some(n) => n,
                None => NUMBER_OF_FILL_THREAD,
            };
            IdsService {
                ids_cache: Arc::new(Mutex::new(VecDeque::with_capacity(cache_size))),
                rand_length,
                cache_size,
                mode,
                number_of_threads: threads,
                threads_pool: Vec::with_capacity(NUMBER_OF_FILL_THREAD),
                stop_state: Arc::new(AtomicBool::new(false)),
            }
        }


        /// Start the background threads to keep cache filled.
        pub fn start(&mut self) {
            info!("Start ids_service!");
            let mut rng = rand::thread_rng();

            self.stop_state.store(false,Ordering::Relaxed);

            // Create all workers
            for i in 0..self.number_of_threads {
                // Create builder
                let builder = thread::Builder::new().name(format!("{}", i));

                // Clone cache ids
                let ids_cache_clone = self.ids_cache.clone();

                // Length of random data
                let rand_length = self.rand_length;

                let cache_size = self.cache_size;

                //crypto mode
                let mode = self.mode;

                // Waiting delay
                let delay_ms: u64 = rng.gen_range(50, 200);

                let stop_state_clone = self.stop_state.clone();

                // create the thread
                let handler = builder
                    .spawn(move || {
                        let thread_id: usize =
                            usize::from_str(thread::current().name().unwrap()).unwrap();
                        trace!("Thread id {}: is up", thread_id);
                        loop {
                            if ids_cache_clone.lock().unwrap().len() < cache_size {
                                let mut id: Vec<u8> = vec![0u8; length_for(mode)];
                                create_id(mode, rand_length, id.as_mut());
                                ids_cache_clone.lock().unwrap().push_back(id);
                            } else {
                                trace!("Thread id {}: wait for {} ms", thread_id, delay_ms);
                                thread::sleep(Duration::from_millis(delay_ms));
                            }
                            if stop_state_clone.load(Ordering::Relaxed) {
                                trace!("Thread id {}: stopped", thread_id);
                                break;
                            }
                        }
                    })
                    .unwrap_or_else(|_| panic!("Expect no error from thread {}", i));
                self.threads_pool.push(Some(handler));
            }
        }

        /// Stop the background threads to Graceful Shutdown and Cleanup
        pub fn stop(&mut self) {
            info!("Stop ids_service!");
            self.stop_state.store(true,Ordering::Relaxed);
            for handle in &mut self.threads_pool {
                if let Some(handle) = handle.take() {
                    handle.join().unwrap();
                }
            }
            self.ids_cache.lock().unwrap().clear();

        }

        // Create an id based on function create_id
        fn create_id(&mut self, out: &mut Vec<u8>) {
            if out.len() < length_for(self.mode) {
                warn!("Create an id with vec param out not initialized. out len = {}, out expected len {}",out.len(),length_for(self.mode));
                out.clear();
                for _ in 0..length_for(self.mode) {
                    out.push(0u8);
                }
            }
            create_id(self.mode, self.rand_length, out);
        }

        ///
        /// Get an id. It may never failed even if cache is empty.
        /// If cache is empty it create an id on fly.
        /// # Examples
        /// ```
        /// extern crate ids_service;
        ///
        /// use crate::ids_service::crypto_hash::{Encode,IdsService};
        ///
        /// fn main() {
        ///
        ///     let mut ids = IdsService::default();
        ///     ids.start();
        ///     println!("Get an id: {}", ids.get_id().as_hex());
        /// }
        /// ```
        pub fn get_id(&mut self) -> Vec<u8> {
            let id = self.ids_cache.lock().unwrap().pop_front();
            match id {
                Some(i) => i,
                None => {
                    info!("The ids_cache is empty, create on fly an id");
                    let mut id: Vec<u8> = vec![0u8; length_for(self.mode)];
                    self.create_id(id.as_mut());
                    id
                }
            }
        }

        ///
        /// Get an id from the cache. If the cache is empty
        /// It return None
        /// # Examples
        /// ```
        /// extern crate ids_service;
        ///
        /// use crate::ids_service::crypto_hash::{Encode,IdsService};
        ///
        /// fn main() {
        ///
        ///     let mut ids = IdsService::default();
        ///     ids.start();
        ///     ids.filled_event().recv().is_ok();
        ///     println!("Get an id from cache: {}", ids.get_id_from_cache().expect("Expect an id").as_hex());
        /// }
        /// ```
        pub fn get_id_from_cache(&mut self) -> Option<Vec<u8>> {
            self.ids_cache.lock().unwrap().pop_front()
        }

        /// Get the internal cache size.
        pub fn get_cache_len(&mut self) -> usize {
            self.ids_cache.lock().unwrap().len()
        }

        /// Set an cache size.
        /// If the new size is smaller it don't remove already created item.
        /// It will wait to refill the cache to be smaller of the new size.
        /// It restart the service to take the new size
        /// # Examples
        ///
        /// ```
        /// extern crate ids_service;
        /// extern crate simplelog;
        /// extern crate crypto;
        ///
        /// use crate::ids_service::crypto_hash::{Encode,IdsService};
        /// use crate::simplelog::*;
        /// use crypto::sha3::Sha3Mode;
        /// use std::time::Duration;
        /// use std::thread;
        /// use log::*;
        ///
        /// fn main() {
        ///
        ///     let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
        ///
        ///    let mut ids3 = IdsService::default();
        ///    ids3.start();
        ///
        ///    //Wait the cache is filled
        ///    loop{
        ///        thread::sleep(Duration::from_millis(100));
        ///        if !ids3.is_filled(){
        ///            break;
        ///        }
        ///    }
        ///    info!("Current numbers of items in cache ids3: {}", ids3.get_cache_len());
        ///
        ///    ids3.set_cache_size(20000);
        ///    ids3.filled_event().recv().is_ok();
        ///
        ///    info!("Current numbers of items in cache ids3: {}", ids3.get_cache_len());
        ///
        /// }
        /// ```
        pub fn set_cache_size(&mut self, new_size: usize) {
            self.cache_size = new_size;
            info!("Restart ids_service!");
            self.stop();
            self.start();
        }

        ///
        /// True if the cash length >= cash size needed
        pub fn is_filled(&self) -> bool {
            let len = self.ids_cache.lock().unwrap().len();
            len >= self.cache_size
        }

        ///
        /// Send an event when cache is filled
        ///
        /// # Examples
        ///
        /// ```
        /// extern crate ids_service;
        ///
        /// use crate::ids_service::crypto_hash::{Encode,IdsService};
        ///
        /// fn main() {
        ///
        ///     let mut ids = IdsService::default();
        ///     ids.start();
        ///     // Optional: Wait cache is filled
        ///     ids.filled_event().recv().is_ok();
        /// }
        /// ```
        ///
        pub fn filled_event(&mut self) -> mpsc::Receiver<bool> {

            let mut rng = rand::thread_rng();

            let filled_chn:(mpsc::Sender<bool>, mpsc::Receiver<bool>) = mpsc::channel();
            let sender = filled_chn.0.clone();

            let name = format!("filled_event {}", self.threads_pool.len() + 1);
            // Create builder
            let builder = thread::Builder::new().name(name.clone());

            let stop_state_clone = self.stop_state.clone();

            // Clone cache ids
            let ids_cache_clone = self.ids_cache.clone();

            let cache_size = self.cache_size;



            // Waiting delay
            let delay_ms: u64 = rng.gen_range(20, 50);

            // create the thread
            let handler = builder
                .spawn(move || {
                    trace!("Thread id {}: is up", thread::current().name().unwrap());
                    loop{
                        if ids_cache_clone.lock().unwrap().len() >= cache_size {
                            sender.send(true).unwrap();
                            break
                        }
                        if stop_state_clone.load(Ordering::Relaxed) {
                            sender.send(false).unwrap();
                            break;
                        }
                        thread::sleep(Duration::from_millis(delay_ms));
                    }
                    trace!("Thread id {}: stopped", thread::current().name().unwrap());
                }).unwrap_or_else(|_| panic!("Expect no error from thread {}", name));
            self.threads_pool.push(Some(handler));
            filled_chn.1
        }
    }

    // Function that create an ID
    fn create_id(mode: Sha3Mode, rand_length: usize, out: &mut Vec<u8>) {
        let ts = Utc::now().timestamp_nanos();
        //Note add 8 due to timestamp first block
        let mut rand_data = vec![0u8; rand_length + 8];
        rand_data.extend(ts.to_ne_bytes().iter());
        for _i in 0..rand_length {
            rand_data.push(thread_rng().gen());
        }
        let mut hasher = Sha3::new(mode);
        hasher.input(rand_data.as_slice());
        hasher.result(out.as_mut());
    }

    /// Single function to create an id without IdsService
    /// It use sha512 hash algorithm and it encode output as hexadecimal lower case
    /// # example:
    /// ```
    /// extern crate ids_service;
    ///
    /// use crate::ids_service::crypto_hash::*;
    ///
    /// fn main() {
    ///
    ///     println!("Create an id sha512 without the service: {}", create_id_as_sha512());
    ///
    /// }
    /// ```
    pub fn create_id_as_sha512() -> String {
        let mut id = vec![0u8; Sha3Mode::Sha3_512.digest_length()];
        create_id(
            Sha3Mode::Sha3_512,
            Sha3Mode::Sha3_512.digest_length(),
            id.as_mut(),
        );
        HEXLOWER.encode(id.as_slice())
    }

    /// Single function to create an id without IdsService
    /// It use sha256 hash algorithm and it encode output as hexadecimal lower case
    /// # example:
    /// ```
    /// extern crate ids_service;
    ///
    /// use crate::ids_service::crypto_hash::*;
    ///
    /// fn main() {
    ///
    ///     println!("Create an id sha256 without the service: {}", create_id_as_sha256());
    ///
    /// }
    /// ```
    pub fn create_id_as_sha256() -> String {
        let mut id = vec![0u8; Sha3Mode::Sha3_256.digest_length()];
        create_id(
            Sha3Mode::Sha3_256,
            Sha3Mode::Sha3_256.digest_length(),
            id.as_mut(),
        );
        HEXLOWER.encode(id.as_slice())
    }

    // Get length fo ShaMode due to Sha3Mode::Shake256 and Sha3Mode::Shake128 return 0
    fn length_for(mode: Sha3Mode) -> usize {
        match mode {
            Sha3Mode::Shake256 => 32,
            Sha3Mode::Shake128 => 16,
            _ => mode.digest_length(),
        }
    }

    ///
    /// Tests
    ///
    #[cfg(test)]
    mod tests {
        use crate::crypto_hash::Encode;
        use crate::crypto_hash::*;
        use crypto::sha3::Sha3Mode;
        use simplelog::*;
        use std::collections::HashSet;
        use std::thread;
        use std::time::Duration;

        #[test]
        fn test_start() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let mut service = IdsService::new(1000, Sha3Mode::Sha3_512, None);
            service.start();
            loop {
                thread::sleep(Duration::from_millis(10));
                if service.is_filled() {
                    break;
                }
            }
            assert!(service.get_cache_len() >= 1000);
        }

        #[test]
        fn test_stop() {
            let _ = SimpleLogger::init(LevelFilter::Trace, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_512, None);
            ids01.start();
            ids01.filled_event().recv().is_ok();
            debug!("Filled");
            ids01.stop();
            assert!(true);
        }

        #[test]
        fn test_create_id_512() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let id1 = create_id_as_sha512();
            let id2 = create_id_as_sha512();
            assert!(!id1.eq(&id2));
        }

        #[test]
        fn test_create_id_256() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let id1 = create_id_as_sha256();
            let id2 = create_id_as_sha256();
            assert!(!id1.eq(&id2));
        }

        #[test]
        fn test_get_id() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_256, None);
            ids01.start();
            let r1 = ids01.get_id();
            debug!("r1: {:?}", r1);
            assert_eq!(r1.len(), Sha3Mode::Sha3_256.digest_length());
            let r2 = ids01.get_id();
            debug!("r2: {:?}", r2);
            assert_eq!(r2.len(), Sha3Mode::Sha3_256.digest_length());
            assert!(!r1.eq(&r2));
        }

        #[test]
        fn test_filled() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_256, None);
            ids01.start();
            ids01.filled_event().recv().is_ok();
            debug!("len: {}",ids01.get_cache_len());
            assert!(ids01.is_filled());
        }

        #[test]
        fn test_get_id_from_cache() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_256, None);
            assert!(ids01.get_id_from_cache().is_none());
            ids01.start();
            ids01.filled_event().recv().is_ok();
            debug!("len: {}", ids01.get_cache_len());
            let r1 = ids01.get_id_from_cache().expect("Expect an id");
            debug!("r1: {:?}", r1);
            assert_eq!(r1.len(), Sha3Mode::Sha3_256.digest_length());
            let r2 = ids01.get_id_from_cache().expect("Expect an id");
            debug!("r2: {:?}", r2);
            assert_eq!(r2.len(), Sha3Mode::Sha3_256.digest_length());
            assert!(!r1.eq(&r2));
        }

        #[test]
        fn test_get_id_all() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let do_test = |m: Sha3Mode| {
                debug!("mode: {:?}", m);
                let mut ids01 = IdsService::new(1000, m, None);
                ids01.start();
                ids01.filled_event().recv().is_ok();
                let r1 = ids01.get_id();
                debug!("r1: {:?}", r1);
                assert!(r1.len() > 0);
                let r2 = ids01.get_id();
                debug!("r2: {:?}", r2);
                assert!(r2.len() > 0);
                assert!(!r1.eq(&r2));
            };

            do_test(Sha3Mode::Keccak224);
            do_test(Sha3Mode::Keccak256);
            do_test(Sha3Mode::Keccak384);
            do_test(Sha3Mode::Keccak512);
            do_test(Sha3Mode::Sha3_224);
            do_test(Sha3Mode::Sha3_256);
            do_test(Sha3Mode::Sha3_384);
            do_test(Sha3Mode::Sha3_512);
            do_test(Sha3Mode::Shake128);
            do_test(Sha3Mode::Shake256);
        }

        #[test]
        fn test_get_id_as_hex() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_256, None);
            ids01.start();
            let result = ids01.get_id().as_hex();
            debug!("Id {} / len {}", result, result.len());
            assert_eq!(result.len(), 64);
        }

        #[test]
        fn test_get_id_as_base64() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_256, None);
            ids01.start();
            let result = ids01.get_id().as_base64();
            debug!("Id {} / len {}", result, result.len());
            assert_eq!(result.len(), 44);
        }

        #[test]
        fn test_get_id_as_base64_url() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_256, None);
            ids01.start();
            let result = ids01.get_id().as_base64_url();
            debug!("Id {} / len {}", result, result.len());
            assert_eq!(result.len(), 44);
        }

        #[test]
        fn test_get_id_as_base32() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_256, None);
            ids01.start();
            let result = ids01.get_id().as_base32();
            debug!("Id {} / len {}", result, result.len());
            assert_eq!(result.len(), 56);
        }

        #[test]
        fn test_get_id_as_json() {
            let _ = SimpleLogger::init(LevelFilter::Info, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_256, None);
            ids01.start();
            let result = ids01.get_id().as_json();
            info!("{}", result);
            assert!(result.contains("\"bytes\""));
            assert!(result.contains("\"base64\""));
            assert!(result.contains("\"base32\""));
            assert!(result.contains("\"hex\""));
        }

        #[test]
        fn test_iterator() {
            let _ = SimpleLogger::init(LevelFilter::Warn, Config::default());
            let mut ids01 = IdsService::new(1000, Sha3Mode::Sha3_512, Some(100 as usize));
            ids01.start();
            ids01.filled_event().recv().is_ok();
            let number = 500;
            let mut ids = HashSet::with_capacity(number);
            for _ in 0..number {
                ids.insert(ids01.get_id().as_hex());
            }
            assert_eq!(ids.len(), number);
            ids.clear();
            for x in ids01.take(number) {
                ids.insert(x.as_hex());
            }
            assert_eq!(ids.len(), number);
        }
    }
}