@@ -2,11 +2,20 @@ use bencher_valid::BASE_36;
22use uuid:: Uuid ;
33
44pub fn encode_uuid ( uuid : Uuid ) -> String {
5+ const ENCODED_LEN : usize = 26 ;
6+
57 let base = BASE_36 . len ( ) as u128 ;
68 let chars = BASE_36 . chars ( ) . collect :: < Vec < _ > > ( ) ;
79
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+
917 let mut result = String :: new ( ) ;
18+ #[ allow( clippy:: cast_possible_truncation) ]
1019 while num > 0 {
1120 let remainder = ( num % base) as usize ;
1221 if let Some ( c) = chars. get ( remainder) {
@@ -15,7 +24,11 @@ pub fn encode_uuid(uuid: Uuid) -> String {
1524 num /= base;
1625 }
1726
18- result. chars ( ) . rev ( ) . collect ( )
27+ result
28+ . chars ( )
29+ . chain ( std:: iter:: repeat ( '0' ) )
30+ . take ( ENCODED_LEN )
31+ . collect ( )
1932}
2033
2134#[ cfg( test) ]
@@ -26,12 +39,12 @@ mod tests {
2639 #[ test]
2740 fn test_encode_uuid ( ) {
2841 let uuid = Uuid :: parse_str ( "00000000-0000-0000-0000-000000000000" ) . unwrap ( ) ;
29- assert_eq ! ( encode_uuid( uuid) , "" ) ;
42+ assert_eq ! ( encode_uuid( uuid) , "00000000000000000000000000 " ) ;
3043
3144 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 " ) ;
3346
3447 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 " ) ;
3649 }
3750}
0 commit comments