diff options
| author | Marijn Haverbeke <marijnh@gmail.com> | 2011-12-07 21:06:12 +0100 |
|---|---|---|
| committer | Marijn Haverbeke <marijnh@gmail.com> | 2011-12-07 21:08:28 +0100 |
| commit | e3eca9174b9dc186de4ad44f80f7537f2e9e4c60 (patch) | |
| tree | ff9c8c7fd97f0cb8daecc002b1855412846f7757 /src/libstd | |
| parent | 6daa233a73541c4daf135ac5dd9e339289fdfbfd (diff) | |
| download | rust-e3eca9174b9dc186de4ad44f80f7537f2e9e4c60.tar.gz rust-e3eca9174b9dc186de4ad44f80f7537f2e9e4c60.zip | |
Change literal representation to not truncate
Also shuffles around the organization of numeric literals and types, separating by int/uint/float instead of machine-vs-non-machine types. This simplifies some code. Closes #974 Closes #1252
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/char.rs | 23 | ||||
| -rw-r--r-- | src/libstd/u64.rs | 23 |
2 files changed, 41 insertions, 5 deletions
diff --git a/src/libstd/char.rs b/src/libstd/char.rs index bc8e74355c6..5ff7681ae8a 100644 --- a/src/libstd/char.rs +++ b/src/libstd/char.rs @@ -109,12 +109,25 @@ pure fn is_whitespace(c: char) -> bool { Safety note: This function fails if `c` is not a valid char */ -pure fn to_digit(c: char) -> u8 { +pure fn to_digit(c: char) -> u8 unsafe { + alt maybe_digit(c) { + option::some(x) { x } + option::none. { fail; } + } +} + +/* + Function: to_digit + + Convert a char to the corresponding digit. Returns none when the + character is not a valid hexadecimal digit. +*/ +fn maybe_digit(c: char) -> option::t<u8> { alt c { - '0' to '9' { c as u8 - ('0' as u8) } - 'a' to 'z' { c as u8 + 10u8 - ('a' as u8) } - 'A' to 'Z' { c as u8 + 10u8 - ('A' as u8) } - _ { fail; } + '0' to '9' { option::some(c as u8 - ('0' as u8)) } + 'a' to 'z' { option::some(c as u8 + 10u8 - ('a' as u8)) } + 'A' to 'Z' { option::some(c as u8 + 10u8 - ('A' as u8)) } + _ { option::none } } } diff --git a/src/libstd/u64.rs b/src/libstd/u64.rs index aacc35a827d..0e1a330c663 100644 --- a/src/libstd/u64.rs +++ b/src/libstd/u64.rs @@ -63,3 +63,26 @@ Function: str Convert to a string */ fn str(n: u64) -> str { ret to_str(n, 10u); } + +/* +Function: parse_buf + +Parse a string as an unsigned integer. +*/ +fn from_str(buf: str, radix: u64) -> u64 { + if str::byte_len(buf) == 0u { + log_err "parse_buf(): buf is empty"; + fail; + } + let i = str::byte_len(buf) - 1u; + let power = 1u64, n = 0u64; + while true { + let digit = char::to_digit(buf[i] as char) as u64; + if digit >= radix { fail; } + n += digit * power; + power *= radix; + if i == 0u { ret n; } + i -= 1u; + } + fail; +} |
