Skip to content

Commit 4063802

Browse files
committed
Merge pull request #2205 from grahame/floatstrfixes
add inf/-inf/NaN parsing to float::from_str
2 parents 658b6a7 + 6b5731e commit 4063802

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/libcore/float.rs

+18
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ This function accepts strings such as
110110
* '', or, equivalently, '.' (understood as 0)
111111
* '5.'
112112
* '.5', or, equivalently, '0.5'
113+
* 'inf', '-inf', 'NaN'
113114
114115
Leading and trailing whitespace are ignored.
115116
@@ -123,6 +124,14 @@ Leading and trailing whitespace are ignored.
123124
where `n` is the floating-point number represented by `[num]`.
124125
"]
125126
fn from_str(num: str) -> option<float> {
127+
if num == "inf" {
128+
ret some(infinity);
129+
} else if num == "-inf" {
130+
ret some(neg_infinity);
131+
} else if num == "NaN" {
132+
ret some(NaN);
133+
}
134+
126135
let mut pos = 0u; //Current byte position in the string.
127136
//Used to walk the string in O(n).
128137
let len = str::len(num); //Length of the string, in bytes.
@@ -301,6 +310,15 @@ fn test_from_str() {
301310
assert from_str("-.5") == some(-0.5);
302311
assert from_str("-.5") == some(-0.5);
303312
assert from_str("-5") == some(-5.);
313+
assert from_str("-0") == some(-0.);
314+
assert from_str("0") == some(0.);
315+
assert from_str("inf") == some(infinity);
316+
assert from_str("-inf") == some(neg_infinity);
317+
// note: NaN != NaN, hence this slightly complex test
318+
alt from_str("NaN") {
319+
some(f) { assert is_NaN(f); }
320+
none { fail; }
321+
}
304322

305323
assert from_str("") == none;
306324
assert from_str("x") == none;

0 commit comments

Comments
 (0)