@@ -2,11 +2,20 @@ use bencher_valid::BASE_36;
2
2
use uuid:: Uuid ;
3
3
4
4
pub fn encode_uuid ( uuid : Uuid ) -> String {
5
+ const ENCODED_LEN : usize = 26 ;
6
+
5
7
let base = BASE_36 . len ( ) as u128 ;
6
8
let chars = BASE_36 . chars ( ) . collect :: < Vec < _ > > ( ) ;
7
9
8
- let mut num = uuid. as_u128 ( ) ;
10
+ // Treat the bytes as a single large number to preserve entropy
11
+ let bytes = uuid. as_bytes ( ) ;
12
+ let mut num = 0u128 ;
13
+ for & byte in bytes {
14
+ num = ( num << 8 ) | u128:: from ( byte) ;
15
+ }
16
+
9
17
let mut result = String :: new ( ) ;
18
+ #[ allow( clippy:: cast_possible_truncation) ]
10
19
while num > 0 {
11
20
let remainder = ( num % base) as usize ;
12
21
if let Some ( c) = chars. get ( remainder) {
@@ -15,7 +24,11 @@ pub fn encode_uuid(uuid: Uuid) -> String {
15
24
num /= base;
16
25
}
17
26
18
- result. chars ( ) . rev ( ) . collect ( )
27
+ result
28
+ . chars ( )
29
+ . chain ( std:: iter:: repeat ( '0' ) )
30
+ . take ( ENCODED_LEN )
31
+ . collect ( )
19
32
}
20
33
21
34
#[ cfg( test) ]
@@ -26,12 +39,12 @@ mod tests {
26
39
#[ test]
27
40
fn test_encode_uuid ( ) {
28
41
let uuid = Uuid :: parse_str ( "00000000-0000-0000-0000-000000000000" ) . unwrap ( ) ;
29
- assert_eq ! ( encode_uuid( uuid) , "" ) ;
42
+ assert_eq ! ( encode_uuid( uuid) , "00000000000000000000000000 " ) ;
30
43
31
44
let uuid = Uuid :: parse_str ( "ffffffff-ffff-ffff-ffff-ffffffffffff" ) . unwrap ( ) ;
32
- assert_eq ! ( encode_uuid( uuid) , "f5lxx1zz5pnorynqglhzmsp33 " ) ;
45
+ assert_eq ! ( encode_uuid( uuid) , "33psmzhlgqnyronp5zz1xxl5f0 " ) ;
33
46
34
47
let uuid = Uuid :: parse_str ( "12345678-1234-5678-1234-567812345678" ) . unwrap ( ) ;
35
- assert_eq ! ( encode_uuid( uuid) , "12srddy53kndus0lmbgjgy7i0 " ) ;
48
+ assert_eq ! ( encode_uuid( uuid) , "0i7ygjgbml0sudnk35yddrs210 " ) ;
36
49
}
37
50
}
0 commit comments