@@ -21,6 +21,71 @@ macro_rules! is_enabled {
21
21
} ;
22
22
}
23
23
24
+ // ————————————————————————————— String Parsing ————————————————————————————— //
25
+ // Required to parse environment variables at compile time.
26
+ // Can be removed once usize::from_str_radix stabilized as const, hopefully soon.
27
+ // See https://github.com/rust-lang/rust/pull/124941
28
+ //
29
+ // Source (and license), adapted for Mirage:
30
+ // https://gist.github.com/DutchGhost/d8604a3c796479777fe9f5e25d855cfd
31
+ // —————————————————————————————————————————————————————————————————————————— //
32
+
33
+ const fn parse_byte ( b : u8 , pow10 : usize ) -> usize {
34
+ let r = b - 48 ; // Remove ascii offset
35
+
36
+ if r > 9 {
37
+ panic ! ( "Failed to parse config: expected usize" )
38
+ } else {
39
+ ( r as usize ) * pow10
40
+ }
41
+ }
42
+
43
+ const POW10 : [ usize ; 20 ] = {
44
+ let mut array = [ 0 ; 20 ] ;
45
+ let mut current = 1 ;
46
+
47
+ let mut index = 20 ;
48
+
49
+ loop {
50
+ index -= 1 ;
51
+ array[ index] = current;
52
+
53
+ if index == 0 {
54
+ break ;
55
+ }
56
+
57
+ current *= 10 ;
58
+ }
59
+
60
+ array
61
+ } ;
62
+
63
+ const fn parse ( env_var : Option < & str > ) -> Option < usize > {
64
+ let Some ( env_var) = env_var else {
65
+ return None ;
66
+ } ;
67
+
68
+ let bytes = env_var. as_bytes ( ) ;
69
+ let mut result: usize = 0 ;
70
+
71
+ let len = bytes. len ( ) ;
72
+
73
+ // Start at the correct index of the table,
74
+ // (skip the power's that are too large)
75
+ let mut index_const_table = POW10 . len ( ) . wrapping_sub ( len) ;
76
+ let mut index = 0 ;
77
+
78
+ while index < env_var. len ( ) {
79
+ let pow = POW10 [ index_const_table] ;
80
+ result += parse_byte ( bytes[ index] , pow) ;
81
+
82
+ index += 1 ;
83
+ index_const_table += 1 ;
84
+ }
85
+
86
+ Some ( result)
87
+ }
88
+
24
89
// ———————————————————————— Configuration Parameters ———————————————————————— //
25
90
26
91
/// Weather the platform supports S mode.
@@ -30,4 +95,4 @@ pub const HAS_S_MODE: bool = is_enabled!("MIRAGE_PLATFORM_S_MODE");
30
95
pub const LOG_LEVEL : Option < & ' static str > = option_env ! ( "MIRAGE_LOG_LEVEL" ) ;
31
96
32
97
/// The maximum number of firmware exits before quitting.
33
- pub const MAX_FIRMWARE_EXIT : Option < & ' static str > = option_env ! ( "MIRAGE_DEBUG_MAX_FIRMWARE_EXITS" ) ;
98
+ pub const MAX_FIRMWARE_EXIT : Option < usize > = parse ( option_env ! ( "MIRAGE_DEBUG_MAX_FIRMWARE_EXITS" ) ) ;
0 commit comments