Skip to content

Remove {uint,int,u64,i64,...}::from_str,from_str_radix #9209

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions doc/tutorial-conditions.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ fn read_int_pairs() -> ~[(int,int)] {
[a, b] => {

// 5. Try parsing both fields as ints.
match (int::from_str(a), int::from_str(b)) {
match (from_str::<int>(a), from_str::<int>(b)) {

// 6. If parsing succeeded for both, push both.
(Some(a), Some(b)) => pairs.push((a,b)),
Expand Down Expand Up @@ -124,7 +124,7 @@ for conveying a value of type `T`, represented as `Some(T)`
_or_ the sentinel `None`, to indicate the absence of a `T` value.
For simple APIs, it may be sufficient to encode errors as `Option<T>`,
returning `Some(T)` on success and `None` on error.
In the example program, the call to `int::from_str` returns `Option<int>`
In the example program, the call to `from_str::<int>` returns `Option<int>`
with the understanding that "all parse errors" result in `None`.
The resulting `Option<int>` values are matched against the pattern `(Some(a), Some(b))`
in steps 5 and 6 in the example program,
Expand Down Expand Up @@ -161,7 +161,7 @@ This second mechanism for indicating an error is called a `Result`.
The type `std::result::Result<T,E>` is another simple `enum` type with two forms, `Ok(T)` and `Err(E)`.
The `Result` type is not substantially different from the `Option` type in terms of its ergonomics.
Its main advantage is that the error constructor `Err(E)` can convey _more detail_ about the error.
For example, the `int::from_str` API could be reformed
For example, the `from_str` API could be reformed
to return a `Result` carrying an informative description of a parse error,
like this:

Expand All @@ -172,7 +172,7 @@ enum IntParseErr {
BadChar(char)
}

fn int::from_str(&str) -> Result<int,IntParseErr> {
fn from_str(&str) -> Result<int,IntParseErr> {
// ...
}
~~~~
Expand Down Expand Up @@ -297,8 +297,8 @@ fn read_int_pairs() -> ~[(int,int)] {
let line = fi.read_line();
let fields = line.word_iter().to_owned_vec();
match fields {
[a, b] => pairs.push((int::from_str(a).unwrap(),
int::from_str(b).unwrap())),
[a, b] => pairs.push((from_str::<int>(a).unwrap(),
from_str::<int>(b).unwrap())),

// Explicitly fail on malformed lines.
_ => fail!()
Expand Down Expand Up @@ -398,8 +398,8 @@ fn read_int_pairs() -> ~[(int,int)] {
let line = fi.read_line();
let fields = line.word_iter().to_owned_vec();
match fields {
[a, b] => pairs.push((int::from_str(a).unwrap(),
int::from_str(b).unwrap())),
[a, b] => pairs.push((from_str::<int>(a).unwrap(),
from_str::<int>(b).unwrap())),

// On malformed lines, call the condition handler and
// push whatever the condition handler returns.
Expand Down Expand Up @@ -475,8 +475,8 @@ fn read_int_pairs() -> ~[(int,int)] {
let line = fi.read_line();
let fields = line.word_iter().to_owned_vec();
match fields {
[a, b] => pairs.push((int::from_str(a).unwrap(),
int::from_str(b).unwrap())),
[a, b] => pairs.push((from_str::<int>(a).unwrap(),
from_str::<int>(b).unwrap())),
_ => pairs.push(malformed_line::cond.raise(line.clone()))
}
}
Expand Down Expand Up @@ -553,8 +553,8 @@ fn read_int_pairs() -> ~[(int,int)] {
let line = fi.read_line();
let fields = line.word_iter().to_owned_vec();
match fields {
[a, b] => pairs.push((int::from_str(a).unwrap(),
int::from_str(b).unwrap())),
[a, b] => pairs.push((from_str::<int>(a).unwrap(),
from_str::<int>(b).unwrap())),

// On malformed lines, call the condition handler and
// either ignore the line (if the handler returns `None`)
Expand Down Expand Up @@ -649,8 +649,8 @@ fn read_int_pairs() -> ~[(int,int)] {
let line = fi.read_line();
let fields = line.word_iter().to_owned_vec();
match fields {
[a, b] => pairs.push((int::from_str(a).unwrap(),
int::from_str(b).unwrap())),
[a, b] => pairs.push((from_str::<int>(a).unwrap(),
from_str::<int>(b).unwrap())),

// On malformed lines, call the condition handler and
// take action appropriate to the enum value returned.
Expand Down Expand Up @@ -776,7 +776,7 @@ fn main() {
// Parse an int; if parsing fails, call the condition handler and
// return whatever it returns.
fn parse_int(x: &str) -> int {
match int::from_str(x) {
match from_str::<int>(x) {
Some(v) => v,
None => malformed_int::cond.raise(x.to_owned())
}
Expand Down Expand Up @@ -833,8 +833,8 @@ There are three other things to note in this variant of the example program:
so long as the `raise` occurs within a callee (of any depth) of the logic protected by the `trap` call,
it will invoke the handler.

- This variant insulates callers from a design choice in the `int` library:
the `int::from_str` function was designed to return an `Option<int>`,
- This variant insulates callers from a design choice in the library:
the `from_str` function was designed to return an `Option<int>`,
but this program insulates callers from that choice,
routing all `None` values that arise from parsing integers in this file into the condition.

Expand Down Expand Up @@ -873,4 +873,4 @@ To compensate for this risk, correct C++ and Java code must program in an extrem
or else risk introducing silent and very difficult-to-debug errors due to control resuming in a corrupted heap after a caught exception.
These errors are frequently memory-safety errors, which Rust strives to eliminate,
and so Rust unwinding is unrecoverable within a single task:
once unwinding starts, the entire local heap of a task is destroyed and the task is terminated.
once unwinding starts, the entire local heap of a task is destroyed and the task is terminated.
4 changes: 2 additions & 2 deletions src/libextra/fileinput.rs
Original file line number Diff line number Diff line change
Expand Up @@ -538,8 +538,8 @@ mod test {

do input_vec_state(filenames) |line, state| {
let nums: ~[&str] = line.split_iter(' ').collect();
let file_num = uint::from_str(nums[0]).unwrap();
let line_num = uint::from_str(nums[1]).unwrap();
let file_num = from_str::<uint>(nums[0]).unwrap();
let line_num = from_str::<uint>(nums[1]).unwrap();
assert_eq!(line_num, state.line_num_file);
assert_eq!(file_num * 3 + line_num, state.line_num);
true
Expand Down
5 changes: 2 additions & 3 deletions src/libextra/semver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use std::io::{ReaderUtil};
use std::io;
use std::option::{Option, Some, None};
use std::to_str::ToStr;
use std::uint;

#[deriving(Clone, Eq)]
pub enum Identifier {
Expand Down Expand Up @@ -140,7 +139,7 @@ fn take_nonempty_prefix(rdr: @io::Reader,

fn take_num(rdr: @io::Reader, ch: char) -> (uint, char) {
let (s, ch) = take_nonempty_prefix(rdr, ch, char::is_digit);
match uint::from_str(s) {
match from_str::<uint>(s) {
None => { bad_parse::cond.raise(()); (0, ch) },
Some(i) => (i, ch)
}
Expand All @@ -149,7 +148,7 @@ fn take_num(rdr: @io::Reader, ch: char) -> (uint, char) {
fn take_ident(rdr: @io::Reader, ch: char) -> (Identifier, char) {
let (s,ch) = take_nonempty_prefix(rdr, ch, char::is_alphanumeric);
if s.iter().all(char::is_digit) {
match uint::from_str(s) {
match from_str::<uint>(s) {
None => { bad_parse::cond.raise(()); (Numeric(0), ch) },
Some(i) => (Numeric(i), ch)
}
Expand Down
5 changes: 2 additions & 3 deletions src/libextra/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ use std::task;
use std::to_str::ToStr;
use std::f64;
use std::os;
use std::uint;


// The name of a test. By convention this follows the rules for rust
Expand Down Expand Up @@ -253,7 +252,7 @@ pub fn parse_opts(args: &[~str]) -> OptRes {
let ratchet_metrics = ratchet_metrics.map_move(|s| Path(s));

let ratchet_noise_percent = getopts::opt_maybe_str(&matches, "ratchet-noise-percent");
let ratchet_noise_percent = ratchet_noise_percent.map_move(|s| f64::from_str(s).unwrap());
let ratchet_noise_percent = ratchet_noise_percent.map_move(|s| from_str::<f64>(s).unwrap());

let save_metrics = getopts::opt_maybe_str(&matches, "save-metrics");
let save_metrics = save_metrics.map_move(|s| Path(s));
Expand Down Expand Up @@ -281,7 +280,7 @@ pub fn opt_shard(maybestr: Option<~str>) -> Option<(uint,uint)> {
None => None,
Some(s) => {
match s.split_iter('.').to_owned_vec() {
[a, b] => match (uint::from_str(a), uint::from_str(b)) {
[a, b] => match (from_str::<uint>(a), from_str::<uint>(b)) {
(Some(a), Some(b)) => Some((a,b)),
_ => None
},
Expand Down
79 changes: 32 additions & 47 deletions src/libstd/num/int_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,20 +383,6 @@ impl Primitive for $T {

// String conversion functions and impl str -> num

/// Parse a string as a number in base 10.
#[inline]
pub fn from_str(s: &str) -> Option<$T> {
strconv::from_str_common(s, 10u, true, false, false,
strconv::ExpNone, false, false)
}

/// Parse a string as a number in the given base.
#[inline]
pub fn from_str_radix(s: &str, radix: uint) -> Option<$T> {
strconv::from_str_common(s, radix, true, false, false,
strconv::ExpNone, false, false)
}

/// Parse a byte slice as a number in the given base.
#[inline]
pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<$T> {
Expand All @@ -407,14 +393,16 @@ pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<$T> {
impl FromStr for $T {
#[inline]
fn from_str(s: &str) -> Option<$T> {
from_str(s)
strconv::from_str_common(s, 10u, true, false, false,
strconv::ExpNone, false, false)
}
}

impl FromStrRadix for $T {
#[inline]
fn from_str_radix(s: &str, radix: uint) -> Option<$T> {
from_str_radix(s, radix)
strconv::from_str_common(s, radix, true, false, false,
strconv::ExpNone, false, false)
}
}

Expand Down Expand Up @@ -462,10 +450,7 @@ mod tests {
use super::*;

use int;
use i16;
use i32;
use i64;
use i8;
use num;
use sys;

Expand Down Expand Up @@ -670,20 +655,20 @@ mod tests {

#[test]
fn test_from_str() {
assert_eq!(from_str("0"), Some(0 as $T));
assert_eq!(from_str("3"), Some(3 as $T));
assert_eq!(from_str("10"), Some(10 as $T));
assert_eq!(i32::from_str("123456789"), Some(123456789 as i32));
assert_eq!(from_str("00100"), Some(100 as $T));
assert_eq!(from_str::<$T>("0"), Some(0 as $T));
assert_eq!(from_str::<$T>("3"), Some(3 as $T));
assert_eq!(from_str::<$T>("10"), Some(10 as $T));
assert_eq!(from_str::<i32>("123456789"), Some(123456789 as i32));
assert_eq!(from_str::<$T>("00100"), Some(100 as $T));

assert_eq!(from_str("-1"), Some(-1 as $T));
assert_eq!(from_str("-3"), Some(-3 as $T));
assert_eq!(from_str("-10"), Some(-10 as $T));
assert_eq!(i32::from_str("-123456789"), Some(-123456789 as i32));
assert_eq!(from_str("-00100"), Some(-100 as $T));
assert_eq!(from_str::<$T>("-1"), Some(-1 as $T));
assert_eq!(from_str::<$T>("-3"), Some(-3 as $T));
assert_eq!(from_str::<$T>("-10"), Some(-10 as $T));
assert_eq!(from_str::<i32>("-123456789"), Some(-123456789 as i32));
assert_eq!(from_str::<$T>("-00100"), Some(-100 as $T));

assert!(from_str(" ").is_none());
assert!(from_str("x").is_none());
assert!(from_str::<$T>(" ").is_none());
assert!(from_str::<$T>("x").is_none());
}

#[test]
Expand Down Expand Up @@ -751,36 +736,36 @@ mod tests {
#[test]
fn test_int_from_str_overflow() {
let mut i8_val: i8 = 127_i8;
assert_eq!(i8::from_str("127"), Some(i8_val));
assert!(i8::from_str("128").is_none());
assert_eq!(from_str::<i8>("127"), Some(i8_val));
assert!(from_str::<i8>("128").is_none());

i8_val += 1 as i8;
assert_eq!(i8::from_str("-128"), Some(i8_val));
assert!(i8::from_str("-129").is_none());
assert_eq!(from_str::<i8>("-128"), Some(i8_val));
assert!(from_str::<i8>("-129").is_none());

let mut i16_val: i16 = 32_767_i16;
assert_eq!(i16::from_str("32767"), Some(i16_val));
assert!(i16::from_str("32768").is_none());
assert_eq!(from_str::<i16>("32767"), Some(i16_val));
assert!(from_str::<i16>("32768").is_none());

i16_val += 1 as i16;
assert_eq!(i16::from_str("-32768"), Some(i16_val));
assert!(i16::from_str("-32769").is_none());
assert_eq!(from_str::<i16>("-32768"), Some(i16_val));
assert!(from_str::<i16>("-32769").is_none());

let mut i32_val: i32 = 2_147_483_647_i32;
assert_eq!(i32::from_str("2147483647"), Some(i32_val));
assert!(i32::from_str("2147483648").is_none());
assert_eq!(from_str::<i32>("2147483647"), Some(i32_val));
assert!(from_str::<i32>("2147483648").is_none());

i32_val += 1 as i32;
assert_eq!(i32::from_str("-2147483648"), Some(i32_val));
assert!(i32::from_str("-2147483649").is_none());
assert_eq!(from_str::<i32>("-2147483648"), Some(i32_val));
assert!(from_str::<i32>("-2147483649").is_none());

let mut i64_val: i64 = 9_223_372_036_854_775_807_i64;
assert_eq!(i64::from_str("9223372036854775807"), Some(i64_val));
assert!(i64::from_str("9223372036854775808").is_none());
assert_eq!(from_str::<i64>("9223372036854775807"), Some(i64_val));
assert!(from_str::<i64>("9223372036854775808").is_none());

i64_val += 1 as i64;
assert_eq!(i64::from_str("-9223372036854775808"), Some(i64_val));
assert!(i64::from_str("-9223372036854775809").is_none());
assert_eq!(from_str::<i64>("-9223372036854775808"), Some(i64_val));
assert!(from_str::<i64>("-9223372036854775809").is_none());
}

#[test]
Expand Down
5 changes: 5 additions & 0 deletions src/libstd/num/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,11 @@ pub trait FromStrRadix {
fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
}

/// A utility function that just calls FromStrRadix::from_str_radix
pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> {
FromStrRadix::from_str_radix(str, radix)
}

/// Calculates a power to a given radix, optimized for uint `pow` and `radix`.
///
/// Returns `radix^pow` as `T`.
Expand Down
Loading