@@ -48,6 +48,8 @@ This function accepts strings such as
48
48
* "5."
49
49
* ".5", or, equivalently, "0.5"
50
50
51
+ Leading and trailing whitespace are ignored.
52
+
51
53
Parameters:
52
54
53
55
num - A string, possibly empty.
@@ -58,6 +60,8 @@ Returns:
58
60
Otherwise, the floating-point number represented [num].
59
61
*/
60
62
fn from_str ( num : str ) -> float {
63
+ num = str:: trim ( num) ;
64
+
61
65
let pos = 0 u; //Current byte position in the string.
62
66
//Used to walk the string in O(n).
63
67
let len = str:: byte_len ( num) ; //Length of the string, in bytes.
@@ -66,6 +70,12 @@ fn from_str(num: str) -> float {
66
70
let total = 0 f; //Accumulated result
67
71
let c = 'z' ; //Latest char.
68
72
73
+ //The string must start with one of the following characters.
74
+ alt str:: char_at ( num, 0 u) {
75
+ '-' | '+' | '0' to '9' | '.' { }
76
+ _ { ret NaN ( ) ; }
77
+ }
78
+
69
79
//Determine if first char is '-'/'+'. Set [pos] and [neg] accordingly.
70
80
let neg = false ; //Sign of the result
71
81
alt str:: char_at ( num, 0 u) {
@@ -89,9 +99,12 @@ fn from_str(num: str) -> float {
89
99
total = total * 10 f;
90
100
total += ( ( c as int ) - ( '0' as int ) ) as float ;
91
101
}
92
- _ {
102
+ '.' | 'e' | 'E' {
93
103
break ;
94
104
}
105
+ _ {
106
+ ret NaN ( ) ;
107
+ }
95
108
}
96
109
}
97
110
@@ -106,9 +119,12 @@ fn from_str(num: str) -> float {
106
119
decimal /= 10 . f ;
107
120
total += ( ( ( c as int ) - ( '0' as int ) ) as float ) * decimal;
108
121
}
109
- _ {
122
+ 'e' | 'E' {
110
123
break ;
111
124
}
125
+ _ {
126
+ ret NaN ( ) ;
127
+ }
112
128
}
113
129
}
114
130
}
@@ -132,7 +148,6 @@ fn from_str(num: str) -> float {
132
148
while ( pos < len) {
133
149
let char_range = str:: char_range_at ( num, pos) ;
134
150
c = char_range. ch ;
135
- pos = char_range. next ;
136
151
alt c {
137
152
'0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' {
138
153
exponent *= 10 u;
@@ -142,6 +157,7 @@ fn from_str(num: str) -> float {
142
157
break;
143
158
}
144
159
}
160
+ pos = char_range. next ;
145
161
}
146
162
let multiplier = pow_uint_to_uint_as_float ( 10 u, exponent) ;
147
163
//Note: not [int::pow], otherwise, we'll quickly
@@ -151,6 +167,8 @@ fn from_str(num: str) -> float {
151
167
} else {
152
168
total = total * multiplier;
153
169
}
170
+ } else {
171
+ ret NaN ( ) ;
154
172
}
155
173
}
156
174
0 commit comments