@@ -58,9 +58,13 @@ use std::{
5858 cell:: RefCell ,
5959 collections:: hash_map:: DefaultHasher ,
6060 hash:: { Hash , Hasher } ,
61- time:: { SystemTime , UNIX_EPOCH } ,
6261} ;
6362
63+ #[ cfg( not( target_family = "wasm" ) ) ]
64+ use std:: time:: { SystemTime , UNIX_EPOCH } ;
65+ #[ cfg( target_family = "wasm" ) ]
66+ use web_time:: { SystemTime , UNIX_EPOCH } ;
67+
6468use cuid_util:: ToBase36 ;
6569use num:: bigint;
6670use rand:: { seq:: SliceRandom , thread_rng, Rng } ;
@@ -85,6 +89,21 @@ const STARTING_CHARS: &str = "abcdefghijklmnopqrstuvwxyz";
8589// - fingerprint, a hash with added entropy, derived from a random number between
8690// 2063 and 4125, inclusive, the process ID, and the thread ID
8791
92+ fn fingerprint ( ) -> String {
93+ hash (
94+ [
95+ thread_rng ( ) . gen :: < u128 > ( ) . to_be_bytes ( ) ,
96+ thread_rng ( ) . gen :: < u128 > ( ) . to_be_bytes ( ) ,
97+ #[ cfg( not( target_family = "wasm" ) ) ]
98+ u128:: from ( std:: process:: id ( ) ) . to_be_bytes ( ) ,
99+ #[ cfg( target_family = "wasm" ) ]
100+ thread_rng ( ) . gen :: < u128 > ( ) . to_be_bytes ( ) ,
101+ u128:: from ( get_thread_id ( ) ) . to_be_bytes ( ) ,
102+ ] ,
103+ BIG_LENGTH . into ( ) ,
104+ )
105+ }
106+
88107thread_local ! {
89108 /// Value used to initialize the counter. After the counter hits u64::MAX, it
90109 /// will roll back to this value.
@@ -109,15 +128,7 @@ thread_local! {
109128 ///
110129 /// This is pretty non-language, non-system dependent, so it allows us to
111130 /// compile to wasm and so on.
112- static FINGERPRINT : String = hash(
113- [
114- thread_rng( ) . gen :: <u128 >( ) . to_be_bytes( ) ,
115- thread_rng( ) . gen :: <u128 >( ) . to_be_bytes( ) ,
116- u128 :: from( std:: process:: id( ) ) . to_be_bytes( ) ,
117- u128 :: from( get_thread_id( ) ) . to_be_bytes( ) ,
118- ] ,
119- BIG_LENGTH . into( ) ,
120- ) ;
131+ static FINGERPRINT : String = fingerprint( ) ;
121132}
122133
123134// Hashing
@@ -462,6 +473,12 @@ mod test {
462473 assert ! ( next > start) ;
463474 }
464475
476+ #[ wasm_bindgen_test:: wasm_bindgen_test]
477+ fn wasm_cuid_does_not_panic ( ) {
478+ cuid ( ) ;
479+ }
480+
481+ #[ cfg( not( target_family = "wasm" ) ) ]
465482 #[ test]
466483 #[ ignore] // slow: run explicitly when desired
467484 fn collisions ( ) {
0 commit comments