1
+ //!
2
+ //! Algorithm of finding out tag width:
3
+ //! 1. Rust `repr(...)` and `borsh(tag_width = ...) attributes are read
4
+ //! 2. If repr is signed, transparent or variable with *size, borsh errors with unsupported
5
+ //! 2.1. NOTE: signed to be supported
1
6
use core:: convert:: TryInto ;
2
7
use std:: collections:: HashMap ;
3
8
use std:: convert:: TryFrom ;
@@ -17,26 +22,11 @@ impl Discriminants {
17
22
let mut map = HashMap :: new ( ) ;
18
23
let mut next_discriminant_if_not_specified = quote ! { 0 } ;
19
24
20
- fn bytes_needed ( value : usize ) -> usize {
21
- let bits_needed = std:: mem:: size_of :: < usize > ( ) * 8 - value. leading_zeros ( ) as usize ;
22
- ( bits_needed + 7 ) / 8
23
- }
24
-
25
25
let min_tag_width: u8 = bytes_needed ( variants. len ( ) )
26
26
. try_into ( )
27
27
. expect ( "variants cannot be bigger u64" ) ;
28
28
29
- let mut min = 0 ;
30
- let mut max = 0 ;
31
-
32
29
for variant in variants {
33
- if let Some ( discriminant) = & variant. discriminant {
34
- let value = discriminant. 1 . to_token_stream ( ) . to_string ( ) ;
35
- let value = value. parse :: < i128 > ( ) . unwrap ( ) ;
36
- min = value. min ( min) ;
37
- max = value. max ( max) ;
38
- }
39
-
40
30
let this_discriminant = variant. discriminant . clone ( ) . map_or_else (
41
31
|| quote ! { #next_discriminant_if_not_specified } ,
42
32
|( _, e) | quote ! { #e } ,
@@ -46,15 +36,6 @@ impl Discriminants {
46
36
map. insert ( variant. ident . clone ( ) , this_discriminant) ;
47
37
}
48
38
49
- let min: u64 = min. abs ( ) . try_into ( ) . expect ( "variants cannot be bigger u64" ) ;
50
- let max: u64 = max. try_into ( ) . expect ( "variants cannot be bigger u64" ) ;
51
- if min > 0 {
52
- return Err ( syn:: Error :: new (
53
- variants. span ( ) ,
54
- "negative variants are not supported, please write manual impl" ,
55
- ) ) ;
56
- }
57
- let max_bytes: u8 = bytes_needed ( max as usize ) . try_into ( ) . expect ( "" ) ;
58
39
if let Some ( ( borsh_tag_width, span) ) = maybe_borsh_tag_width {
59
40
if borsh_tag_width < min_tag_width {
60
41
return Err ( syn:: Error :: new (
@@ -68,17 +49,17 @@ impl Discriminants {
68
49
}
69
50
}
70
51
71
- let tag_with = maybe_borsh_tag_width
52
+ let tag_width = maybe_borsh_tag_width
72
53
. map ( |( tag_width, _) | tag_width)
73
- . unwrap_or_else ( || ( max_bytes ) . max ( min_tag_width) ) ;
54
+ . unwrap_or_else ( || ( 1 ) . max ( min_tag_width) ) ;
74
55
75
- let tag_width_type = if tag_with <= 1 {
56
+ let tag_width_type = if tag_width <= 1 {
76
57
"u8"
77
- } else if tag_with <= 2 {
58
+ } else if tag_width <= 2 {
78
59
"u16"
79
- } else if tag_with <= 4 {
60
+ } else if tag_width <= 4 {
80
61
"u32"
81
- } else if tag_with <= 8 {
62
+ } else if tag_width <= 8 {
82
63
"u64"
83
64
} else {
84
65
unreachable ! ( "we eliminated such error earlier" )
0 commit comments