Converts `StrBuf` to `String` throughout rustc and the standard library.
Tests all pass locally, but usual caveats about platforms that aren't OSX apply since I don't have a test environment handy.
@alexcritchon mentioned that @pcwalton may have a patch incoming that should block this?
closes #14312
#[deriving(Clone)]
pub struct Config {
// The library paths required for running the compiler
- pub compile_lib_path: StrBuf,
+ pub compile_lib_path: String,
// The library paths required for running compiled programs
- pub run_lib_path: StrBuf,
+ pub run_lib_path: String,
// The rustc executable
pub rustc_path: Path,
pub aux_base: Path,
// The name of the stage being built (stage1, etc)
- pub stage_id: StrBuf,
+ pub stage_id: String,
// The test mode, compile-fail, run-fail, run-pass
pub mode: Mode,
// A command line to prefix program execution with,
// for running under valgrind
- pub runtool: Option<StrBuf>,
+ pub runtool: Option<String>,
// Flags to pass to the compiler when building for the host
- pub host_rustcflags: Option<StrBuf>,
+ pub host_rustcflags: Option<String>,
// Flags to pass to the compiler when building for the target
- pub target_rustcflags: Option<StrBuf>,
+ pub target_rustcflags: Option<String>,
// Run tests using the JIT
pub jit: bool,
// Target system to be tested
- pub target: StrBuf,
+ pub target: String,
// Host triple for the compiler being invoked
- pub host: StrBuf,
+ pub host: String,
// Path to the android tools
pub android_cross_path: Path,
// Extra parameter to run adb on arm-linux-androideabi
- pub adb_path: StrBuf,
+ pub adb_path: String,
// Extra parameter to run test sute on arm-linux-androideabi
- pub adb_test_dir: StrBuf,
+ pub adb_test_dir: String,
// status whether android device available or not
pub adb_device_status: bool,
// the path containing LLDB's Python module
- pub lldb_python_dir: Option<StrBuf>,
+ pub lldb_python_dir: Option<String>,
// Explain what's going on
pub verbose: bool
run_tests(&config);
}
-pub fn parse_config(args: Vec<StrBuf> ) -> Config {
+pub fn parse_config(args: Vec<String> ) -> Config {
let groups : Vec<getopts::OptGroup> =
vec!(reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"),
logv(c, format_strbuf!("\n"));
}
-pub fn opt_str<'a>(maybestr: &'a Option<StrBuf>) -> &'a str {
+pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
None => "(none)",
Some(ref s) => s.as_slice(),
}
}
-pub fn opt_str2(maybestr: Option<StrBuf>) -> StrBuf {
+pub fn opt_str2(maybestr: Option<String>) -> String {
match maybestr {
None => "(none)".to_strbuf(),
Some(s) => s,
pub fn make_test_name(config: &Config, testfile: &Path) -> test::TestName {
// Try to elide redundant long paths
- fn shorten(path: &Path) -> StrBuf {
+ fn shorten(path: &Path) -> String {
let filename = path.filename_str();
let p = path.dir_path();
let dir = p.filename_str();
pub struct ExpectedError {
pub line: uint,
- pub kind: StrBuf,
- pub msg: StrBuf,
+ pub kind: String,
+ pub msg: String,
}
pub static EXPECTED_PATTERN : &'static str = r"//~(?P<adjusts>\^*)\s*(?P<kind>\S*)\s*(?P<msg>.*)";
pub struct TestProps {
// Lines that should be expected, in order, on standard out
- pub error_patterns: Vec<StrBuf> ,
+ pub error_patterns: Vec<String> ,
// Extra flags to pass to the compiler
- pub compile_flags: Option<StrBuf>,
+ pub compile_flags: Option<String>,
// Extra flags to pass when the compiled code is run (such as --bench)
- pub run_flags: Option<StrBuf>,
+ pub run_flags: Option<String>,
// If present, the name of a file that this test should match when
// pretty-printed
pub pp_exact: Option<Path>,
// Modules from aux directory that should be compiled
- pub aux_builds: Vec<StrBuf> ,
+ pub aux_builds: Vec<String> ,
// Environment settings to use during execution
- pub exec_env: Vec<(StrBuf,StrBuf)> ,
+ pub exec_env: Vec<(String,String)> ,
// Lines to check if they appear in the expected debugger output
- pub check_lines: Vec<StrBuf> ,
+ pub check_lines: Vec<String> ,
// Flag to force a crate to be built with the host architecture
pub force_host: bool,
// Check stdout for error-pattern output as well as stderr
}
pub fn is_test_ignored(config: &Config, testfile: &Path) -> bool {
- fn ignore_target(config: &Config) -> StrBuf {
+ fn ignore_target(config: &Config) -> String {
format_strbuf!("ignore-{}", util::get_os(config.target.as_slice()))
}
- fn ignore_stage(config: &Config) -> StrBuf {
+ fn ignore_stage(config: &Config) -> String {
format_strbuf!("ignore-{}",
config.stage_id.as_slice().split('-').next().unwrap())
}
return true;
}
-fn parse_error_pattern(line: &str) -> Option<StrBuf> {
+fn parse_error_pattern(line: &str) -> Option<String> {
parse_name_value_directive(line, "error-pattern".to_strbuf())
}
-fn parse_aux_build(line: &str) -> Option<StrBuf> {
+fn parse_aux_build(line: &str) -> Option<String> {
parse_name_value_directive(line, "aux-build".to_strbuf())
}
-fn parse_compile_flags(line: &str) -> Option<StrBuf> {
+fn parse_compile_flags(line: &str) -> Option<String> {
parse_name_value_directive(line, "compile-flags".to_strbuf())
}
-fn parse_run_flags(line: &str) -> Option<StrBuf> {
+fn parse_run_flags(line: &str) -> Option<String> {
parse_name_value_directive(line, "run-flags".to_strbuf())
}
-fn parse_check_line(line: &str) -> Option<StrBuf> {
+fn parse_check_line(line: &str) -> Option<String> {
parse_name_value_directive(line, "check".to_strbuf())
}
parse_name_directive(line, "no-pretty-expanded")
}
-fn parse_exec_env(line: &str) -> Option<(StrBuf, StrBuf)> {
+fn parse_exec_env(line: &str) -> Option<(String, String)> {
parse_name_value_directive(line, "exec-env".to_strbuf()).map(|nv| {
// nv is either FOO or FOO=BAR
- let mut strs: Vec<StrBuf> = nv.as_slice()
+ let mut strs: Vec<String> = nv.as_slice()
.splitn('=', 1)
.map(|s| s.to_strbuf())
.collect();
line.contains(directive)
}
-pub fn parse_name_value_directive(line: &str, directive: StrBuf)
- -> Option<StrBuf> {
+pub fn parse_name_value_directive(line: &str, directive: String)
+ -> Option<String> {
let keycolon = format_strbuf!("{}:", directive);
match line.find_str(keycolon.as_slice()) {
Some(colon) => {
use std::io::process::{ProcessExit, Command, Process, ProcessOutput};
use std::unstable::dynamic_lib::DynamicLibrary;
-fn target_env(lib_path: &str, prog: &str) -> Vec<(StrBuf, StrBuf)> {
+fn target_env(lib_path: &str, prog: &str) -> Vec<(String, String)> {
let prog = if cfg!(windows) {prog.slice_to(prog.len() - 4)} else {prog};
let mut aux_path = prog.to_strbuf();
aux_path.push_str(".libaux");
// Remove the previous dylib search path var
let var = DynamicLibrary::envvar();
- let mut env: Vec<(StrBuf,StrBuf)> =
+ let mut env: Vec<(String,String)> =
os::env().move_iter().map(|(a,b)|(a.to_strbuf(), b.to_strbuf())).collect();
match env.iter().position(|&(ref k, _)| k.as_slice() == var) {
Some(i) => { env.remove(i); }
return env;
}
-pub struct Result {pub status: ProcessExit, pub out: StrBuf, pub err: StrBuf}
+pub struct Result {pub status: ProcessExit, pub out: String, pub err: String}
pub fn run(lib_path: &str,
prog: &str,
- args: &[StrBuf],
- env: Vec<(StrBuf, StrBuf)> ,
- input: Option<StrBuf>) -> Option<Result> {
+ args: &[String],
+ env: Vec<(String, String)> ,
+ input: Option<String>) -> Option<Result> {
let env = env.clone().append(target_env(lib_path, prog).as_slice());
match Command::new(prog).args(args).env(env.as_slice()).spawn() {
pub fn run_background(lib_path: &str,
prog: &str,
- args: &[StrBuf],
- env: Vec<(StrBuf, StrBuf)> ,
- input: Option<StrBuf>) -> Option<Process> {
+ args: &[String],
+ env: Vec<(String, String)> ,
+ input: Option<String>) -> Option<Process> {
let env = env.clone().append(target_env(lib_path, prog).as_slice());
match Command::new(prog).args(args).env(env.as_slice()).spawn() {
use std::io;
use std::os;
use std::str;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::task;
use test::MetricMap;
-pub fn run(config: Config, testfile: StrBuf) {
+pub fn run(config: Config, testfile: String) {
match config.target.as_slice() {
run_metrics(config, testfile, &mut _mm);
}
-pub fn run_metrics(config: Config, testfile: StrBuf, mm: &mut MetricMap) {
+pub fn run_metrics(config: Config, testfile: String, mm: &mut MetricMap) {
if config.verbose {
// We're going to be dumping a lot of info. Start on a new line.
print!("\n\n");
fn print_source(config: &Config,
props: &TestProps,
testfile: &Path,
- src: StrBuf,
+ src: String,
pretty_type: &str) -> ProcRes {
compose_and_run(config,
testfile,
fn make_pp_args(config: &Config,
props: &TestProps,
testfile: &Path,
- pretty_type: StrBuf) -> ProcArgs {
+ pretty_type: String) -> ProcArgs {
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
let mut args = vec!("-".to_strbuf(),
}
fn typecheck_source(config: &Config, props: &TestProps,
- testfile: &Path, src: StrBuf) -> ProcRes {
+ testfile: &Path, src: String) -> ProcRes {
let args = make_typecheck_args(config, props, testfile);
compose_and_run_compiler(config, props, testfile, args, Some(src))
}
// run debugger script with gdb
#[cfg(windows)]
- fn debugger() -> StrBuf {
+ fn debugger() -> String {
"gdb.exe".to_strbuf()
}
#[cfg(unix)]
- fn debugger() -> StrBuf {
+ fn debugger() -> String {
"gdb".to_strbuf()
}
// Write debugger script:
// We don't want to hang when calling `quit` while the process is still running
- let mut script_str = StrBuf::from_str("settings set auto-confirm true\n");
+ let mut script_str = String::from_str("settings set auto-confirm true\n");
// Set breakpoints on every line that contains the string "#break"
for line in breakpoint_lines.iter() {
}
struct DebuggerCommands {
- commands: Vec<StrBuf>,
- check_lines: Vec<StrBuf>,
+ commands: Vec<String>,
+ check_lines: Vec<String>,
breakpoint_lines: Vec<uint>,
}
}
}
-fn cleanup_debug_info_options(options: &Option<StrBuf>) -> Option<StrBuf> {
+fn cleanup_debug_info_options(options: &Option<String>) -> Option<String> {
if options.is_none() {
return None;
}
let new_options =
split_maybe_args(options).move_iter()
.filter(|x| !options_to_remove.contains(x))
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.connect(" ")
.to_strbuf();
Some(new_options)
}
-fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[StrBuf]) {
+fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String]) {
let num_check_lines = check_lines.len();
if num_check_lines > 0 {
// Allow check lines to leave parts unspecified (e.g., uninitialized
// bits in the wrong case of an enum) with the notation "[...]".
- let check_fragments: Vec<Vec<StrBuf>> =
+ let check_fragments: Vec<Vec<String>> =
check_lines.iter().map(|s| {
s.as_slice()
.trim()
let prefixes = expected_errors.iter().map(|ee| {
format_strbuf!("{}:{}:", testfile.display(), ee.line)
- }).collect::<Vec<StrBuf> >();
+ }).collect::<Vec<String> >();
#[cfg(target_os = "win32")]
- fn to_lower( s : &str ) -> StrBuf {
+ fn to_lower( s : &str ) -> String {
let i = s.chars();
let c : Vec<char> = i.map( |c| {
if c.is_ascii() {
}
struct ProcArgs {
- prog: StrBuf,
- args: Vec<StrBuf>,
+ prog: String,
+ args: Vec<String>,
}
struct ProcRes {
status: ProcessExit,
- stdout: StrBuf,
- stderr: StrBuf,
- cmdline: StrBuf,
+ stdout: String,
+ stderr: String,
+ cmdline: String,
}
fn compile_test(config: &Config, props: &TestProps,
}
fn compile_test_(config: &Config, props: &TestProps,
- testfile: &Path, extra_args: &[StrBuf]) -> ProcRes {
+ testfile: &Path, extra_args: &[String]) -> ProcRes {
let aux_dir = aux_output_dir_name(config, testfile);
// FIXME (#9639): This needs to handle non-utf8 paths
let link_args = vec!("-L".to_strbuf(),
props: &TestProps,
testfile: &Path,
args: ProcArgs,
- input: Option<StrBuf>) -> ProcRes {
+ input: Option<String>) -> ProcRes {
if !props.aux_builds.is_empty() {
ensure_dir(&aux_output_dir_name(config, testfile));
fn compose_and_run(config: &Config, testfile: &Path,
ProcArgs{ args, prog }: ProcArgs,
- procenv: Vec<(StrBuf, StrBuf)> ,
+ procenv: Vec<(String, String)> ,
lib_path: &str,
- input: Option<StrBuf>) -> ProcRes {
+ input: Option<String>) -> ProcRes {
return program_output(config, testfile, lib_path,
prog, args, procenv, input);
}
fn make_compile_args(config: &Config,
props: &TestProps,
- extras: Vec<StrBuf> ,
+ extras: Vec<String> ,
xform: |&Config, &Path| -> TargetLocation,
testfile: &Path)
-> ProcArgs {
};
}
-fn split_maybe_args(argstr: &Option<StrBuf>) -> Vec<StrBuf> {
+fn split_maybe_args(argstr: &Option<String>) -> Vec<String> {
match *argstr {
Some(ref s) => {
s.as_slice()
}
}
-fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: StrBuf,
- args: Vec<StrBuf> , env: Vec<(StrBuf, StrBuf)> ,
- input: Option<StrBuf>) -> ProcRes {
+fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: String,
+ args: Vec<String> , env: Vec<(String, String)> ,
+ input: Option<String>) -> ProcRes {
let cmdline =
{
let cmdline = make_cmdline(lib_path,
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
-fn make_cmdline(_libpath: &str, prog: &str, args: &[StrBuf]) -> StrBuf {
+fn make_cmdline(_libpath: &str, prog: &str, args: &[String]) -> String {
format_strbuf!("{} {}", prog, args.connect(" "))
}
#[cfg(target_os = "win32")]
-fn make_cmdline(libpath: &str, prog: &str, args: &[StrBuf]) -> StrBuf {
+fn make_cmdline(libpath: &str, prog: &str, args: &[String]) -> String {
format_strbuf!("{} {} {}",
lib_path_cmd_prefix(libpath),
prog,
// Build the LD_LIBRARY_PATH variable as it would be seen on the command line
// for diagnostic purposes
#[cfg(target_os = "win32")]
-fn lib_path_cmd_prefix(path: &str) -> StrBuf {
+fn lib_path_cmd_prefix(path: &str) -> String {
format_strbuf!("{}=\"{}\"",
util::lib_path_env_var(),
util::make_new_path(path))
}
}
-fn error(err: StrBuf) { println!("\nerror: {}", err); }
+fn error(err: String) { println!("\nerror: {}", err); }
-fn fatal(err: StrBuf) -> ! { error(err); fail!(); }
+fn fatal(err: String) -> ! { error(err); fail!(); }
-fn fatal_ProcRes(err: StrBuf, proc_res: &ProcRes) -> ! {
+fn fatal_ProcRes(err: String, proc_res: &ProcRes) -> ! {
print!("\n\
error: {}\n\
status: {}\n\
fn _arm_exec_compiled_test(config: &Config,
props: &TestProps,
testfile: &Path,
- env: Vec<(StrBuf, StrBuf)>)
+ env: Vec<(String, String)>)
-> ProcRes {
let args = make_run_args(config, props, testfile);
let cmdline = make_cmdline("",
args.args.as_slice());
// get bare program string
- let mut tvec: Vec<StrBuf> = args.prog
+ let mut tvec: Vec<String> = args.prog
.as_slice()
.split('/')
.map(|ts| ts.to_strbuf())
}
#[cfg(target_os = "win32")]
-pub fn make_new_path(path: &str) -> StrBuf {
+pub fn make_new_path(path: &str) -> String {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
}
#[cfg(target_os = "win32")]
-pub fn lib_path_env_var() -> StrBuf { "PATH".to_strbuf() }
+pub fn lib_path_env_var() -> String { "PATH".to_strbuf() }
#[cfg(target_os = "win32")]
-pub fn path_div() -> StrBuf { ";".to_strbuf() }
+pub fn path_div() -> String { ";".to_strbuf() }
-pub fn logv(config: &Config, s: StrBuf) {
+pub fn logv(config: &Config, s: String) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
~~~
let x: int = 42;
-let y: StrBuf = x.to_str().to_strbuf();
+let y: String = x.to_str().to_strbuf();
~~~
**String to int**
~~~
let x: int = 42;
-let y: StrBuf = format_strbuf!("{:t}", x); // binary
-let y: StrBuf = format_strbuf!("{:o}", x); // octal
-let y: StrBuf = format_strbuf!("{:x}", x); // lowercase hexadecimal
-let y: StrBuf = format_strbuf!("{:X}", x); // uppercase hexadecimal
+let y: String = format_strbuf!("{:t}", x); // binary
+let y: String = format_strbuf!("{:o}", x); // octal
+let y: String = format_strbuf!("{:x}", x); // lowercase hexadecimal
+let y: String = format_strbuf!("{:X}", x); // uppercase hexadecimal
~~~
**String to int, in non-base-10**
let y: &str = x.unwrap();
~~~
-To return an Owned String (StrBuf) use the str helper function
+To return an Owned String use the str helper function
[`from_utf8_owned`](../std/str/fn.from_utf8_owned.html).
~~~
use std::str;
-let x: Option<StrBuf> =
+let x: Option<String> =
str::from_utf8([ 104u8, 105u8 ]).map(|x| x.to_strbuf());
-let y: StrBuf = x.unwrap();
+let y: String = x.unwrap();
~~~
To return a [`MaybeOwned`](../std/str/enum.MaybeOwned.html) use the str helper
Phantom types are useful for enforcing state at compile time. For example:
~~~
-struct Door<State>(StrBuf);
+struct Door<State>(String);
struct Open;
struct Closed;
<link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">
<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:400'
- rel='stylesheet' type='text/css'>
\ No newline at end of file
+ rel='stylesheet' type='text/css'>
`foo`.)
* `expr` (an expression. Examples: `2 + 2`; `if true then { 1 } else { 2 }`;
`f(42)`.)
-* `ty` (a type. Examples: `int`, `~[(char, StrBuf)]`, `&T`.)
+* `ty` (a type. Examples: `int`, `~[(char, String)]`, `&T`.)
* `pat` (a pattern, usually appearing in a `match` or on the left-hand side of
a declaration. Examples: `Some(t)`; `(17, 'a')`; `_`.)
* `block` (a sequence of actions. Example: `{ log(error, "hi"); return 12; }`)
~~~
extern crate sync;
# fn main() {
-fn stringifier(channel: &sync::DuplexStream<StrBuf, uint>) {
+fn stringifier(channel: &sync::DuplexStream<String, uint>) {
let mut value: uint;
loop {
value = channel.recv();
extern crate sync;
# use std::task::spawn;
# use sync::DuplexStream;
-# fn stringifier(channel: &sync::DuplexStream<StrBuf, uint>) {
+# fn stringifier(channel: &sync::DuplexStream<String, uint>) {
# let mut value: uint;
# loop {
# value = channel.recv();
#, fuzzy
#| msgid ""
#| "~~~~ let x: f64 = 4.0; let y: uint = x as uint; assert!(y == 4u); ~~~~"
-msgid "~~~ let x: int = 42; let y: StrBuf = x.to_str(); ~~~"
+msgid "~~~ let x: int = 42; let y: String = x.to_str(); ~~~"
msgstr ""
"~~~~\n"
"let x: f64 = 4.0;\n"
#, fuzzy
#| msgid ""
#| "~~~~ let x: f64 = 4.0; let y: uint = x as uint; assert!(y == 4u); ~~~~"
-msgid "let x: int = 42; let y: StrBuf = x.to_str_radix(16); ~~~"
+msgid "let x: int = 42; let y: String = x.to_str_radix(16); ~~~"
msgstr ""
"~~~~\n"
"let x: f64 = 4.0;\n"
msgid ""
"~~~~\n"
"trait Printable {\n"
-" fn to_string(&self) -> StrBuf;\n"
+" fn to_string(&self) -> String;\n"
"}\n"
msgstr ""
"~~~~ {.ignore}\n"
#| msgid "~~~~ {.ignore} // main.rs extern crate world; fn main() { println(~\"hello \" + world::explore()); } ~~~~"
msgid ""
"impl Printable for int {\n"
-" fn to_string(&self) -> StrBuf { self.to_str() }\n"
+" fn to_string(&self) -> String { self.to_str() }\n"
"}\n"
msgstr ""
"~~~~ {.ignore}\n"
msgid ""
"~~~~\n"
"trait Printable {\n"
-" fn make_string(&self) -> StrBuf;\n"
+" fn make_string(&self) -> String;\n"
"}\n"
msgstr ""
"~~~~ {.ignore}\n"
#, fuzzy, no-wrap
#| msgid "~~~~ {.ignore} // main.rs extern crate world; fn main() { println(~\"hello \" + world::explore()); } ~~~~"
msgid ""
-"impl Printable for StrBuf {\n"
-" fn make_string(&self) -> StrBuf {\n"
+"impl Printable for String {\n"
+" fn make_string(&self) -> String {\n"
" (*self).clone()\n"
" }\n"
"}\n"
#| msgid ""
#| "Traits may be implemented for specific types with [impls]. An impl that "
#| "implements a trait includes the name of the trait at the start of the "
-#| "definition, as in the following impls of `Printable` for `int` and `StrBuf`."
+#| "definition, as in the following impls of `Printable` for `int` and `String`."
msgid ""
"Traits may be implemented for specific types with [impls]. An impl for a "
"particular trait gives an implementation of the methods that trait "
"provides. For instance, the following impls of `Printable` for `int` and "
-"`StrBuf` give implementations of the `print` method."
+"`String` give implementations of the `print` method."
msgstr ""
"[impl][impls] により特定の型にトレイトを実装することができます。トレイトを実"
-"装する impl は、以下の `Printable` の `int` と `StrBuf` に対する実装のように、"
+"装する impl は、以下の `Printable` の `int` と `String` に対する実装のように、"
"定義の先頭にトレイトの名前を含みます。"
#. type: Plain text
#, fuzzy, no-wrap
#| msgid "~~~~ {.ignore} // main.rs extern crate world; fn main() { println(~\"hello \" + world::explore()); } ~~~~"
msgid ""
-"impl Printable for StrBuf {\n"
+"impl Printable for String {\n"
" fn print(&self) { println!(\"{}\", *self) }\n"
"}\n"
msgstr ""
# struct HashMap<K, V>;
# fn f() {
# fn id<T>(t: T) -> T { t }
-type T = HashMap<int,StrBuf>; // Type arguments used in a type expression
+type T = HashMap<int,String>; // Type arguments used in a type expression
let x = id::<int>(10); // Type arguments used in a call expression
# }
~~~~
~~~~
enum Animal {
- Dog (StrBuf, f64),
- Cat { name: StrBuf, weight: f64 }
+ Dog (String, f64),
+ Cat { name: String, weight: f64 }
}
let mut a: Animal = Dog("Cocoa".to_strbuf(), 37.2);
* `str_eq`
: Compare two strings (`&str`) for equality.
* `uniq_str_eq`
- : Compare two owned strings (`StrBuf`) for equality.
+ : Compare two owned strings (`String`) for equality.
* `strdup_uniq`
: Return a new unique string
containing a copy of the contents of a unique string.
represented as a vector of 8-bit unsigned bytes holding a sequence of UTF-8 codepoints.
Since `str` is of unknown size, it is not a _first class_ type,
but can only be instantiated through a pointer type,
-such as `&str` or `StrBuf`.
+such as `&str` or `String`.
### Tuple types
~~~~
trait Printable {
- fn to_string(&self) -> StrBuf;
+ fn to_string(&self) -> String;
}
impl Printable for int {
- fn to_string(&self) -> StrBuf { self.to_str().to_strbuf() }
+ fn to_string(&self) -> String { self.to_str().to_strbuf() }
}
fn print(a: Box<Printable>) {
~~~~
trait Printable {
- fn make_string(&self) -> StrBuf;
+ fn make_string(&self) -> String;
}
-impl Printable for StrBuf {
- fn make_string(&self) -> StrBuf {
+impl Printable for String {
+ fn make_string(&self) -> String {
(*self).clone()
}
}
~~~~
-`self` refers to the value of type `StrBuf` that is the receiver for a
+`self` refers to the value of type `String` that is the receiver for a
call to the method `make_string`.
## Type kinds
pub struct Widget {
/// All widgets have a purpose (this is a doc comment, and will show up
/// the field's documentation).
- purpose: StrBuf,
+ purpose: String,
/// Humans are not allowed to understand some widgets
understandable: bool
}
the elements are mutable if the vector is mutable.
~~~
-use std::strbuf::StrBuf;
+use std::string::String;
// A dynamically sized vector (unique vector)
let mut numbers = vec![1, 2, 3];
// The original `numbers` value can no longer be used, due to move semantics.
-let mut string = StrBuf::from_str("fo");
+let mut string = String::from_str("fo");
string.push_char('o');
~~~
Traits may be implemented for specific types with [impls]. An impl for
a particular trait gives an implementation of the methods that
trait provides. For instance, the following impls of
-`Printable` for `int` and `StrBuf` give implementations of the `print`
+`Printable` for `int` and `String` give implementations of the `print`
method.
[impls]: #methods
fn print(&self) { println!("{:?}", *self) }
}
-impl Printable for StrBuf {
+impl Printable for String {
fn print(&self) { println!("{}", *self) }
}
impl Printable for int {}
-impl Printable for StrBuf {
+impl Printable for String {
fn print(&self) { println!("{}", *self) }
}
methods can save a great deal of boilerplate code from having to be
written in impls. Of course, individual impls can still override the
default method for `print`, as is being done above in the impl for
-`StrBuf`.
+`String`.
## Type-parameterized traits
UnInstallOldVersion();
end;
end;
-end;
\ No newline at end of file
+end;
syn keyword rustTrait ImmutableVector MutableVector
syn keyword rustTrait ImmutableEqVector ImmutableTotalOrdVector MutableTotalOrdVector
syn keyword rustTrait Vector VectorVector OwnedVector MutableVectorAllocating
-syn keyword rustTrait StrBuf
+syn keyword rustTrait String
syn keyword rustTrait Vec
"syn keyword rustFunction sync_channel channel
fun:uv__loop_init
fun:uv_loop_new
...
-}
\ No newline at end of file
+}
}
struct Noncopy {
- string: StrBuf,
+ string: String,
array: Vec<int> ,
}
use std::iter::{Enumerate, Repeat, Map, Zip};
use std::ops;
use std::slice;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::uint;
#[deriving(Clone)]
* The resulting string has the same length as `self`, and each
* character is either '0' or '1'.
*/
- pub fn to_str(&self) -> StrBuf {
- let mut rs = StrBuf::new();
+ pub fn to_str(&self) -> String {
+ let mut rs = String::new();
for i in self.iter() {
if i {
rs.push_char('1');
#[test]
fn test_put_update() {
- let mut cache: LruCache<StrBuf, Vec<u8>> = LruCache::new(1);
+ let mut cache: LruCache<String, Vec<u8>> = LruCache::new(1);
cache.put("1".to_strbuf(), vec![10, 10]);
cache.put("1".to_strbuf(), vec![10, 19]);
assert_opt_eq(cache.get(&"1".to_strbuf()), vec![10, 19]);
#[test]
fn test_expire_lru() {
- let mut cache: LruCache<StrBuf, StrBuf> = LruCache::new(2);
+ let mut cache: LruCache<String, String> = LruCache::new(2);
cache.put("foo1".to_strbuf(), "bar1".to_strbuf());
cache.put("foo2".to_strbuf(), "bar2".to_strbuf());
cache.put("foo3".to_strbuf(), "bar3".to_strbuf());
use char::Char;
use slice::ImmutableVector;
use option::{Some, None};
- use realstd::strbuf::StrBuf;
+ use realstd::string::String;
use realstd::str::{Str, StrAllocating};
#[test]
#[test]
fn test_escape_default() {
- fn string(c: char) -> StrBuf {
- let mut result = StrBuf::new();
+ fn string(c: char) -> String {
+ let mut result = String::new();
escape_default(c, |c| { result.push_char(c); });
return result;
}
#[test]
fn test_escape_unicode() {
- fn string(c: char) -> StrBuf {
- let mut result = StrBuf::new();
+ fn string(c: char) -> String {
+ let mut result = String::new();
escape_unicode(c, |c| { result.push_char(c); });
return result;
}
/// The equivalence relation. Two values may be equivalent even if they are
/// of different types. The most common use case for this relation is
/// container types; e.g. it is often desirable to be able to use `&str`
-/// values to look up entries in a container with `StrBuf` keys.
+/// values to look up entries in a container with `String` keys.
pub trait Equiv<T> {
/// Implement this function to decide equivalent values.
fn equiv(&self, other: &T) -> bool;
}
#[cfg(test)]
-pub fn format(args: &Arguments) -> ::realstd::strbuf::StrBuf {
+pub fn format(args: &Arguments) -> ::realstd::string::String {
use str;
use realstd::str::StrAllocating;
use realstd::io::MemWriter;
let mut i = MemWriter::new();
let _ = write(&mut i, args);
- let mut result = ::realstd::strbuf::StrBuf::new();
+ let mut result = ::realstd::string::String::new();
result.push_str(str::from_utf8(i.get_ref()).unwrap());
result
}
///
/// # Example
///
- /// Convert an `Option<StrBuf>` into an `Option<int>`, preserving the original.
+ /// Convert an `Option<String>` into an `Option<int>`, preserving the original.
/// The `map` method takes the `self` argument by value, consuming the original,
/// so this technique uses `as_ref` to first take an `Option` to a reference
/// to the value inside the original.
///
/// ```
- /// let num_as_str: Option<StrBuf> = Some("10".to_strbuf());
- /// // First, cast `Option<StrBuf>` to `Option<&StrBuf>` with `as_ref`,
+ /// let num_as_str: Option<String> = Some("10".to_strbuf());
+ /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
/// // then consume *that* with `map`, leaving `num_as_str` on the stack.
/// let num_as_int: Option<uint> = num_as_str.as_ref().map(|n| n.len());
/// println!("still can print num_as_str: {}", num_as_str);
///
/// # Example
///
- /// Convert an `Option<StrBuf>` into an `Option<uint>`, consuming the original:
+ /// Convert an `Option<String>` into an `Option<uint>`, consuming the original:
///
/// ```
- /// let num_as_str: Option<StrBuf> = Some("10".to_strbuf());
+ /// let num_as_str: Option<String> = Some("10".to_strbuf());
/// // `Option::map` takes self *by value*, consuming `num_as_str`
/// let num_as_int: Option<uint> = num_as_str.map(|n| n.len());
/// ```
#[cfg(test)]
mod tests {
use realstd::vec::Vec;
- use realstd::strbuf::StrBuf;
+ use realstd::string::String;
use option::collect;
use prelude::*;
use realstd::str::{Str, StrAllocating};
#[test]
#[should_fail]
fn test_unwrap_fail2() {
- let x: Option<StrBuf> = None;
+ let x: Option<String> = None;
x.unwrap();
}
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info {
-//! name: StrBuf,
+//! name: String,
//! age: int,
//! rating: int
//! }
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info {
-//! name: StrBuf,
+//! name: String,
//! age: int,
//! rating: int
//! }
/// let mut sum = 0;
///
/// while !reader.eof() {
- /// let line: IoResult<StrBuf> = reader.read_line();
+ /// let line: IoResult<String> = reader.read_line();
/// // Convert the string line to a number using `map` and `from_str`
/// let val: IoResult<int> = line.map(|line| {
/// from_str::<int>(line.as_slice()).unwrap_or(0)
#[cfg(test)]
mod tests {
use realstd::vec::Vec;
- use realstd::strbuf::StrBuf;
+ use realstd::string::String;
use result::{collect, fold, fold_};
use prelude::*;
cur: str::CharOffsets<'a>,
depth: uint,
/// Error messages accumulated during parsing
- pub errors: Vec<StrBuf>,
+ pub errors: Vec<String>,
}
impl<'a> Iterator<Piece<'a>> for Parser<'a> {
}
/// Notifies of an error. The message doesn't actually need to be of type
- /// StrBuf, but I think it does when this eventually uses conditions so it
+ /// String, but I think it does when this eventually uses conditions so it
/// might as well start using it now.
fn err(&mut self, msg: &str) {
self.errors.push(msg.to_strbuf());
//! use getopts::{optopt,optflag,getopts,OptGroup};
//! use std::os;
//!
-//! fn do_work(inp: &str, out: Option<StrBuf>) {
+//! fn do_work(inp: &str, out: Option<String>) {
//! println!("{}", inp);
//! match out {
//! Some(x) => println!("{}", x),
//! }
//!
//! fn main() {
-//! let args: Vec<StrBuf> = os::args().iter()
+//! let args: Vec<String> = os::args().iter()
//! .map(|x| x.to_strbuf())
//! .collect();
//!
use std::cmp::Eq;
use std::result::{Err, Ok};
use std::result;
-use std::strbuf::StrBuf;
+use std::string::String;
/// Name of an option. Either a string or a single char.
#[deriving(Clone, Eq)]
pub enum Name {
/// A string representing the long name of an option.
/// For example: "help"
- Long(StrBuf),
+ Long(String),
/// A char representing the short name of an option.
/// For example: 'h'
Short(char),
#[deriving(Clone, Eq)]
pub struct OptGroup {
/// Short Name of the `OptGroup`
- pub short_name: StrBuf,
+ pub short_name: String,
/// Long Name of the `OptGroup`
- pub long_name: StrBuf,
+ pub long_name: String,
/// Hint
- pub hint: StrBuf,
+ pub hint: String,
/// Description
- pub desc: StrBuf,
+ pub desc: String,
/// Whether it has an argument
pub hasarg: HasArg,
/// How often it can occur
/// Describes wether an option is given at all or has a value.
#[deriving(Clone, Eq)]
enum Optval {
- Val(StrBuf),
+ Val(String),
Given,
}
/// Values of the Options that matched
vals: Vec<Vec<Optval> > ,
/// Free string fragments
- pub free: Vec<StrBuf>,
+ pub free: Vec<String>,
}
/// The type returned when the command line does not conform to the
#[deriving(Clone, Eq, Show)]
pub enum Fail_ {
/// The option requires an argument but none was passed.
- ArgumentMissing(StrBuf),
+ ArgumentMissing(String),
/// The passed option is not declared among the possible options.
- UnrecognizedOption(StrBuf),
+ UnrecognizedOption(String),
/// A required option is not present.
- OptionMissing(StrBuf),
+ OptionMissing(String),
/// A single occurrence option is being used multiple times.
- OptionDuplicated(StrBuf),
+ OptionDuplicated(String),
/// There's an argument being passed to a non-argument option.
- UnexpectedArgument(StrBuf),
+ UnexpectedArgument(String),
}
/// The type of failure that occurred.
}
}
- fn to_str(&self) -> StrBuf {
+ fn to_str(&self) -> String {
match *self {
Short(ch) => ch.to_str().to_strbuf(),
Long(ref s) => s.to_strbuf()
}
/// Returns true if any of several options were matched.
- pub fn opts_present(&self, names: &[StrBuf]) -> bool {
+ pub fn opts_present(&self, names: &[String]) -> bool {
for nm in names.iter() {
match find_opt(self.opts.as_slice(),
Name::from_str(nm.as_slice())) {
}
/// Returns the string argument supplied to one of several matching options or `None`.
- pub fn opts_str(&self, names: &[StrBuf]) -> Option<StrBuf> {
+ pub fn opts_str(&self, names: &[String]) -> Option<String> {
for nm in names.iter() {
match self.opt_val(nm.as_slice()) {
Some(Val(ref s)) => return Some(s.clone()),
/// option.
///
/// Used when an option accepts multiple values.
- pub fn opt_strs(&self, nm: &str) -> Vec<StrBuf> {
- let mut acc: Vec<StrBuf> = Vec::new();
+ pub fn opt_strs(&self, nm: &str) -> Vec<String> {
+ let mut acc: Vec<String> = Vec::new();
let r = self.opt_vals(nm);
for v in r.iter() {
match *v {
}
/// Returns the string argument supplied to a matching option or `None`.
- pub fn opt_str(&self, nm: &str) -> Option<StrBuf> {
+ pub fn opt_str(&self, nm: &str) -> Option<String> {
let vals = self.opt_vals(nm);
if vals.is_empty() {
- return None::<StrBuf>;
+ return None::<String>;
}
match vals.get(0) {
&Val(ref s) => Some((*s).clone()),
/// Returns none if the option was not present, `def` if the option was
/// present but no argument was provided, and the argument if the option was
/// present and an argument was provided.
- pub fn opt_default(&self, nm: &str, def: &str) -> Option<StrBuf> {
+ pub fn opt_default(&self, nm: &str, def: &str) -> Option<String> {
let vals = self.opt_vals(nm);
if vals.is_empty() {
return None;
impl Fail_ {
/// Convert a `Fail_` enum into an error string.
- pub fn to_err_msg(self) -> StrBuf {
+ pub fn to_err_msg(self) -> String {
match self {
ArgumentMissing(ref nm) => {
format_strbuf!("Argument to option '{}' missing.", *nm)
/// On success returns `Ok(Opt)`. Use methods such as `opt_present`
/// `opt_str`, etc. to interrogate results. Returns `Err(Fail_)` on failure.
/// Use `to_err_msg` to get an error message.
-pub fn getopts(args: &[StrBuf], optgrps: &[OptGroup]) -> Result {
+pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
let opts: Vec<Opt> = optgrps.iter().map(|x| x.long_to_short()).collect();
let n_opts = opts.len();
fn f(_x: uint) -> Vec<Optval> { return Vec::new(); }
let mut vals = Vec::from_fn(n_opts, f);
- let mut free: Vec<StrBuf> = Vec::new();
+ let mut free: Vec<String> = Vec::new();
let l = args.len();
let mut i = 0;
while i < l {
}
/// Derive a usage message from a set of long options.
-pub fn usage(brief: &str, opts: &[OptGroup]) -> StrBuf {
+pub fn usage(brief: &str, opts: &[OptGroup]) -> String {
let desc_sep = format!("\n{}", " ".repeat(24));
hasarg: hasarg,
..} = (*optref).clone();
- let mut row = StrBuf::from_owned_str(" ".repeat(4));
+ let mut row = String::from_owned_str(" ".repeat(4));
// short option
match short_name.len() {
}
// Normalize desc to contain words separated by one space character
- let mut desc_normalized_whitespace = StrBuf::new();
+ let mut desc_normalized_whitespace = String::new();
for word in desc.as_slice().words() {
desc_normalized_whitespace.push_str(word);
desc_normalized_whitespace.push_char(' ');
format_strbuf!("{}\n\nOptions:\n{}\n",
brief,
- rows.collect::<Vec<StrBuf>>().connect("\n"))
+ rows.collect::<Vec<String>>().connect("\n"))
}
-fn format_option(opt: &OptGroup) -> StrBuf {
- let mut line = StrBuf::new();
+fn format_option(opt: &OptGroup) -> String {
+ let mut line = String::new();
if opt.occur != Req {
line.push_char('[');
}
/// Derive a short one-line usage summary from a set of long options.
-pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> StrBuf {
+pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> String {
let mut line = format_strbuf!("Usage: {} ", program_name);
line.push_str(opts.iter()
.map(format_option)
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.connect(" ")
.as_slice());
line
#[test]
fn test_split_within() {
- fn t(s: &str, i: uint, u: &[StrBuf]) {
+ fn t(s: &str, i: uint, u: &[String]) {
let mut v = Vec::new();
each_split_within(s, i, |s| { v.push(s.to_strbuf()); true });
assert!(v.iter().zip(u.iter()).all(|(a,b)| a == b));
use std::{cmp, os, path};
use std::io::fs;
use std::path::is_sep;
-use std::strbuf::StrBuf;
+use std::string::String;
/**
* An iterator that yields Paths from the filesystem that match a particular
* brackets. The resulting string will, when compiled into a `Pattern`,
* match the input string and nothing else.
*/
- pub fn escape(s: &str) -> StrBuf {
- let mut escaped = StrBuf::new();
+ pub fn escape(s: &str) -> String {
+ let mut escaped = String::new();
for c in s.chars() {
match c {
// note that ! does not need escaping because it is only special inside brackets
fn fill_todo(todo: &mut Vec<(Path, uint)>, patterns: &[Pattern], idx: uint, path: &Path,
options: MatchOptions) {
// convert a pattern that's just many Char(_) to a string
- fn pattern_as_str(pattern: &Pattern) -> Option<StrBuf> {
- let mut s = StrBuf::new();
+ fn pattern_as_str(pattern: &Pattern) -> Option<String> {
+ let mut s = String::new();
for token in pattern.tokens.iter() {
match *token {
Char(c) => s.push_char(c),
_ => c.escape_default(f)
}
}
- fn escape_str(s: &str) -> StrBuf {
- let mut out = StrBuf::with_capacity(s.len());
+ fn escape_str(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
for c in s.chars() {
LabelText::escape_char(c, |c| out.push_char(c));
}
}
/// Renders text as string suitable for a label in a .dot file.
- pub fn escape(&self) -> StrBuf {
+ pub fn escape(&self) -> String {
match self {
&LabelStr(ref s) => s.as_slice().escape_default().to_strbuf(),
&EscStr(ref s) => LabelText::escape_str(s.as_slice()).to_strbuf(),
}
}
- fn test_input(g: LabelledGraph) -> IoResult<StrBuf> {
+ fn test_input(g: LabelledGraph) -> IoResult<String> {
let mut writer = MemWriter::new();
render(&g, &mut writer).unwrap();
let mut r = BufReader::new(writer.get_ref());
//Check if the literal is valid (as LLVM expects),
//and return a descriptive error if not.
-fn hex_float_lit_err(s: &str) -> Option<(uint, StrBuf)> {
+fn hex_float_lit_err(s: &str) -> Option<(uint, String)> {
let mut chars = s.chars().peekable();
let mut i = 0;
if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
#[deriving(Show, Clone)]
pub struct LogDirective {
- pub name: Option<StrBuf>,
+ pub name: Option<String>,
pub level: u32,
}
use super::file;
use super::util;
-#[cfg(windows)] use std::strbuf::StrBuf;
+#[cfg(windows)] use std::string::String;
#[cfg(unix)] use super::c;
#[cfg(unix)] use super::retry;
#[cfg(unix)] use io::helper_thread::Helper;
}
#[cfg(windows)]
-fn make_command_line(prog: &CString, args: &[CString]) -> StrBuf {
- let mut cmd = StrBuf::new();
+fn make_command_line(prog: &CString, args: &[CString]) -> String {
+ let mut cmd = String::new();
append_arg(&mut cmd, prog.as_str()
.expect("expected program name to be utf-8 encoded"));
for arg in args.iter() {
}
return cmd;
- fn append_arg(cmd: &mut StrBuf, arg: &str) {
+ fn append_arg(cmd: &mut String, arg: &str) {
let quote = arg.chars().any(|c| c == ' ' || c == '\t');
if quote {
cmd.push_char('"');
}
}
- fn append_char_at(cmd: &mut StrBuf, arg: &Vec<char>, i: uint) {
+ fn append_char_at(cmd: &mut String, arg: &Vec<char>, i: uint) {
match *arg.get(i) {
'"' => {
// Escape quotes.
use std::c_str::CString;
use super::make_command_line;
- fn test_wrapper(prog: &str, args: &[&str]) -> StrBuf {
+ fn test_wrapper(prog: &str, args: &[&str]) -> String {
make_command_line(&prog.to_c_str(),
args.iter()
.map(|a| a.to_c_str())
use std::num::{Bitwise, ToPrimitive, FromPrimitive};
use std::num::{Zero, One, ToStrRadix, FromStrRadix};
use rand::Rng;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::uint;
use std::{i64, u64};
impl_to_biguint!(u64, FromPrimitive::from_u64)
impl ToStrRadix for BigUint {
- fn to_str_radix(&self, radix: uint) -> StrBuf {
+ fn to_str_radix(&self, radix: uint) -> String {
assert!(1 < radix && radix <= 16);
let (base, max_len) = get_radix_base(radix);
if base == BigDigit::base {
return result;
}
- fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> StrBuf {
+ fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> String {
if v.is_empty() {
return "0".to_strbuf()
}
- let mut s = StrBuf::with_capacity(v.len() * l);
+ let mut s = String::with_capacity(v.len() * l);
for n in v.iter().rev() {
let ss = (*n as uint).to_str_radix(radix);
s.push_str("0".repeat(l - ss.len()).as_slice());
impl ToStrRadix for BigInt {
#[inline]
- fn to_str_radix(&self, radix: uint) -> StrBuf {
+ fn to_str_radix(&self, radix: uint) -> String {
match self.sign {
Plus => self.data.to_str_radix(radix),
Zero => "0".to_strbuf(),
assert!(((one << 64) + one).is_odd());
}
- fn to_str_pairs() -> Vec<(BigUint, Vec<(uint, StrBuf)>)> {
+ fn to_str_pairs() -> Vec<(BigUint, Vec<(uint, String)>)> {
let bits = BigDigit::bits;
vec!(( Zero::zero(), vec!(
(2, "0".to_strbuf()), (3, "0".to_strbuf())
}
impl<T: ToStrRadix + Num + Ord> ToStrRadix for Complex<T> {
- fn to_str_radix(&self, radix: uint) -> StrBuf {
+ fn to_str_radix(&self, radix: uint) -> String {
if self.im < Zero::zero() {
format_strbuf!("{}-{}i",
self.re.to_str_radix(radix),
#[test]
fn test_to_str() {
- fn test(c : Complex64, s: StrBuf) {
+ fn test(c : Complex64, s: String) {
assert_eq!(c.to_str().to_strbuf(), s);
}
test(_0_0i, "0+0i".to_strbuf());
}
impl<T: ToStrRadix> ToStrRadix for Ratio<T> {
/// Renders as `numer/denom` where the numbers are in base `radix`.
- fn to_str_radix(&self, radix: uint) -> StrBuf {
+ fn to_str_radix(&self, radix: uint) -> String {
format_strbuf!("{}/{}",
self.numer.to_str_radix(radix),
self.denom.to_str_radix(radix))
#[test]
fn test_to_from_str() {
- fn test(r: Rational, s: StrBuf) {
+ fn test(r: Rational, s: String) {
assert_eq!(FromStr::from_str(s.as_slice()), Some(r));
assert_eq!(r.to_str().to_strbuf(), s);
}
#[test]
fn test_to_from_str_radix() {
- fn test(r: Rational, s: StrBuf, n: uint) {
+ fn test(r: Rational, s: String, n: uint) {
assert_eq!(FromStrRadix::from_str_radix(s.as_slice(), n),
Some(r));
assert_eq!(r.to_str_radix(n).to_strbuf(), s);
}
- fn test3(r: Rational, s: StrBuf) { test(r, s, 3) }
- fn test16(r: Rational, s: StrBuf) { test(r, s, 16) }
+ fn test3(r: Rational, s: String) { test(r, s, 3) }
+ fn test16(r: Rational, s: String) { test(r, s, 16) }
test3(_1, "1/1".to_strbuf());
test3(_0, "0/1".to_strbuf());
use std::io::IoResult;
use std::kinds::marker;
use std::mem;
-use std::strbuf::StrBuf;
+use std::string::String;
pub use isaac::{IsaacRng, Isaac64Rng};
pub use os::OSRng;
///
/// println!("{}", task_rng().gen_ascii_str(10));
/// ```
- fn gen_ascii_str(&mut self, len: uint) -> StrBuf {
+ fn gen_ascii_str(&mut self, len: uint) -> String {
static GEN_ASCII_STR_CHARSET: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789");
- let mut s = StrBuf::with_capacity(len);
+ let mut s = String::with_capacity(len);
for _ in range(0, len) {
s.push_char(*self.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
}
/// If the regular expression requires a literal prefix in order to have a
/// match, that prefix is stored here. (It's used in the VM to implement
/// an optimization.)
- pub prefix: StrBuf,
+ pub prefix: String,
}
impl Program {
/// Compiles a Regex given its AST.
- pub fn new(ast: parse::Ast) -> (Program, Vec<Option<StrBuf>>) {
+ pub fn new(ast: parse::Ast) -> (Program, Vec<Option<String>>) {
let mut c = Compiler {
insts: Vec::with_capacity(100),
names: Vec::with_capacity(10),
// Try to discover a literal string prefix.
// This is a bit hacky since we have to skip over the initial
// 'Save' instruction.
- let mut pre = StrBuf::with_capacity(5);
+ let mut pre = String::with_capacity(5);
for inst in c.insts.slice_from(1).iter() {
match *inst {
OneChar(c, FLAG_EMPTY) => pre.push_char(c),
struct Compiler<'r> {
insts: Vec<Inst>,
- names: Vec<Option<StrBuf>>,
+ names: Vec<Option<String>>,
}
// The compiler implemented here is extremely simple. Most of the complexity
/// The *approximate* character index of where the error occurred.
pub pos: uint,
/// A message describing the error.
- pub msg: StrBuf,
+ pub msg: String,
}
impl fmt::Show for Error {
Begin(Flags),
End(Flags),
WordBoundary(Flags),
- Capture(uint, Option<StrBuf>, Box<Ast>),
+ Capture(uint, Option<String>, Box<Ast>),
// Represent concatenation as a flat vector to avoid blowing the
// stack in the compiler.
Cat(Vec<Ast>),
#[deriving(Show)]
enum BuildAst {
Ast(Ast),
- Paren(Flags, uint, StrBuf), // '('
+ Paren(Flags, uint, String), // '('
Bar, // '|'
}
}
}
- fn capture_name(&self) -> Option<StrBuf> {
+ fn capture_name(&self) -> Option<String> {
match *self {
Paren(_, 0, _) => None,
Paren(_, _, ref name) => {
// opening a capture group).
caps: uint,
// A set of all capture group names used only to detect duplicates.
- names: Vec<StrBuf>,
+ names: Vec<String>,
}
pub fn parse(s: &str) -> Result<Ast, Error> {
// character).
fn parse_unicode_name(&mut self) -> Result<Ast, Error> {
let negated = if self.cur() == 'P' { FLAG_NEGATED } else { FLAG_EMPTY };
- let mut name: StrBuf;
+ let mut name: String;
if self.peek_is(1, '{') {
try!(self.expect('{'))
let closer =
*self.chars.get(self.chari)
}
- fn slice(&self, start: uint, end: uint) -> StrBuf {
+ fn slice(&self, start: uint, end: uint) -> String {
str::from_chars(self.chars.as_slice().slice(start, end)).to_strbuf()
}
}
/// Escapes all regular expression meta characters in `text` so that it may be
/// safely used in a regular expression as a literal string.
-pub fn quote(text: &str) -> StrBuf {
- let mut quoted = StrBuf::with_capacity(text.len());
+pub fn quote(text: &str) -> String {
+ let mut quoted = String::with_capacity(text.len());
for c in text.chars() {
if parse::is_punct(c) {
quoted.push_char('\\')
/// See the comments for the `program` module in `lib.rs` for a more
/// detailed explanation for what `regex!` requires.
#[doc(hidden)]
- pub original: StrBuf,
+ pub original: String,
#[doc(hidden)]
- pub names: Vec<Option<StrBuf>>,
+ pub names: Vec<Option<String>>,
#[doc(hidden)]
pub p: MaybeNative,
}
/// ```
///
/// But anything satisfying the `Replacer` trait will work. For example,
- /// a closure of type `|&Captures| -> StrBuf` provides direct access to the
+ /// a closure of type `|&Captures| -> String` provides direct access to the
/// captures corresponding to a match. This allows one to access
/// submatches easily:
///
/// assert_eq!(result.as_slice(), "$2 $last");
/// # }
/// ```
- pub fn replace<R: Replacer>(&self, text: &str, rep: R) -> StrBuf {
+ pub fn replace<R: Replacer>(&self, text: &str, rep: R) -> String {
self.replacen(text, 1, rep)
}
///
/// See the documentation for `replace` for details on how to access
/// submatches in the replacement string.
- pub fn replace_all<R: Replacer>(&self, text: &str, rep: R) -> StrBuf {
+ pub fn replace_all<R: Replacer>(&self, text: &str, rep: R) -> String {
self.replacen(text, 0, rep)
}
/// See the documentation for `replace` for details on how to access
/// submatches in the replacement string.
pub fn replacen<R: Replacer>
- (&self, text: &str, limit: uint, mut rep: R) -> StrBuf {
- let mut new = StrBuf::with_capacity(text.len());
+ (&self, text: &str, limit: uint, mut rep: R) -> String {
+ let mut new = String::with_capacity(text.len());
let mut last_match = 0u;
for (i, cap) in self.captures_iter(text).enumerate() {
}
}
-impl<'a> Replacer for |&Captures|: 'a -> StrBuf {
+impl<'a> Replacer for |&Captures|: 'a -> String {
fn reg_replace<'r>(&'r mut self, caps: &Captures) -> MaybeOwned<'r> {
Owned((*self)(caps).into_owned())
}
pub struct Captures<'t> {
text: &'t str,
locs: CaptureLocs,
- named: Option<HashMap<StrBuf, uint>>,
+ named: Option<HashMap<String, uint>>,
}
impl<'t> Captures<'t> {
/// isn't a valid index), then it is replaced with the empty string.
///
/// To write a literal `$` use `$$`.
- pub fn expand(&self, text: &str) -> StrBuf {
+ pub fn expand(&self, text: &str) -> String {
// How evil can you get?
// FIXME: Don't use regexes for this. It's completely unnecessary.
let re = Regex::new(r"(^|[^$]|\b)\$(\w+)").unwrap();
- let text = re.replace_all(text, |refs: &Captures| -> StrBuf {
+ let text = re.replace_all(text, |refs: &Captures| -> String {
let (pre, name) = (refs.at(1), refs.at(2));
format_strbuf!("{}{}",
pre,
fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
#[allow(deprecated_owned_vector)]
-fn gen_text(n: uint) -> StrBuf {
+fn gen_text(n: uint) -> String {
let mut rng = task_rng();
let mut bytes = rng.gen_ascii_str(n).into_bytes();
for (i, b) in bytes.mut_iter().enumerate() {
#[test]
fn $name() {
let re = regex!($re);
- assert_eq!(re.$which($search, $replace), StrBuf::from_str($result));
+ assert_eq!(re.$which($search, $replace), String::from_str($result));
}
);
)
cx: &'a ExtCtxt<'a>,
sp: codemap::Span,
prog: Program,
- names: Vec<Option<StrBuf>>,
- original: StrBuf,
+ names: Vec<Option<String>>,
+ original: String,
}
impl<'a> NfaGen<'a> {
/// Looks for a single string literal and returns it.
/// Otherwise, logs an error with cx.span_err and returns None.
-fn parse(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Option<StrBuf> {
+fn parse(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Option<String> {
let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(),
Vec::from_slice(tts));
let entry = cx.expand_expr(parser.parse_expr());
}
/// Lists all files in an archive
- pub fn files(&self) -> Vec<StrBuf> {
+ pub fn files(&self) -> Vec<String> {
let output = run_ar(self.sess, "t", None, [&self.dst]);
let output = str::from_utf8(output.output.as_slice()).unwrap();
// use lines_any because windows delimits output with `\r\n` instead of
use metadata::loader::meta_section_name;
use syntax::abi;
-pub fn get_target_strs(target_triple: StrBuf, target_os: abi::Os) -> target_strs::t {
+pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t {
let cc_args = if target_triple.as_slice().contains("thumb") {
vec!("-mthumb".to_strbuf())
} else {
use std::io;
use std::ptr;
use std::str;
-use std::strbuf::StrBuf;
+use std::string::String;
use flate;
use serialize::hex::ToHex;
use syntax::abi;
OutputTypeExe,
}
-pub fn llvm_err(sess: &Session, msg: StrBuf) -> ! {
+pub fn llvm_err(sess: &Session, msg: String) -> ! {
unsafe {
let cstr = llvm::LLVMRustGetLastError();
if cstr == ptr::null() {
match attr::find_crateid(attrs) {
None => from_str(out_filestem).unwrap_or_else(|| {
let mut s = out_filestem.chars().filter(|c| c.is_XID_continue());
- from_str(s.collect::<StrBuf>().as_slice())
+ from_str(s.collect::<String>().as_slice())
.or(from_str("rust-out")).unwrap()
}),
Some(s) => s,
}
}
-pub fn crate_id_hash(crate_id: &CrateId) -> StrBuf {
+pub fn crate_id_hash(crate_id: &CrateId) -> String {
// This calculates CMH as defined above. Note that we don't use the path of
// the crate id in the hash because lookups are only done by (name/vers),
// not by path.
return r;
}
-fn truncated_hash_result(symbol_hasher: &mut Sha256) -> StrBuf {
+fn truncated_hash_result(symbol_hasher: &mut Sha256) -> String {
let output = symbol_hasher.result_bytes();
// 64 bits should be enough to avoid collisions.
output.slice_to(8).to_hex().to_strbuf()
symbol_hasher: &mut Sha256,
t: ty::t,
link_meta: &LinkMeta)
- -> StrBuf {
+ -> String {
// NB: do *not* use abbrevs here as we want the symbol names
// to be independent of one another in the crate.
symbol_hasher.input_str("-");
symbol_hasher.input_str(encoder::encoded_ty(tcx, t).as_slice());
// Prefix with 'h' so that it never blends into adjacent digits
- let mut hash = StrBuf::from_str("h");
+ let mut hash = String::from_str("h");
hash.push_str(truncated_hash_result(symbol_hasher).as_slice());
hash
}
-fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> StrBuf {
+fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> String {
match ccx.type_hashcodes.borrow().find(&t) {
Some(h) => return h.to_strbuf(),
None => {}
// Name sanitation. LLVM will happily accept identifiers with weird names, but
// gas doesn't!
// gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
-pub fn sanitize(s: &str) -> StrBuf {
- let mut result = StrBuf::new();
+pub fn sanitize(s: &str) -> String {
+ let mut result = String::new();
for c in s.chars() {
match c {
// Escape these with $ sequences
| '_' | '.' | '$' => result.push_char(c),
_ => {
- let mut tstr = StrBuf::new();
+ let mut tstr = String::new();
char::escape_unicode(c, |c| tstr.push_char(c));
result.push_char('$');
result.push_str(tstr.as_slice().slice_from(1));
pub fn mangle<PI: Iterator<PathElem>>(mut path: PI,
hash: Option<&str>,
- vers: Option<&str>) -> StrBuf {
+ vers: Option<&str>) -> String {
// Follow C++ namespace-mangling style, see
// http://en.wikipedia.org/wiki/Name_mangling for more info.
//
// To be able to work on all platforms and get *some* reasonable output, we
// use C++ name-mangling.
- let mut n = StrBuf::from_str("_ZN"); // _Z == Begin name-sequence, N == nested
+ let mut n = String::from_str("_ZN"); // _Z == Begin name-sequence, N == nested
- fn push(n: &mut StrBuf, s: &str) {
+ fn push(n: &mut String, s: &str) {
let sani = sanitize(s);
n.push_str(format!("{}{}", sani.len(), sani).as_slice());
}
n
}
-pub fn exported_name(path: PathElems, hash: &str, vers: &str) -> StrBuf {
+pub fn exported_name(path: PathElems, hash: &str, vers: &str) -> String {
// The version will get mangled to have a leading '_', but it makes more
// sense to lead with a 'v' b/c this is a version...
let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
}
pub fn mangle_exported_name(ccx: &CrateContext, path: PathElems,
- t: ty::t, id: ast::NodeId) -> StrBuf {
+ t: ty::t, id: ast::NodeId) -> String {
let mut hash = get_symbol_hash(ccx, t);
// Paths can be completely identical for different nodes,
pub fn mangle_internal_name_by_type_and_seq(ccx: &CrateContext,
t: ty::t,
- name: &str) -> StrBuf {
+ name: &str) -> String {
let s = ppaux::ty_to_str(ccx.tcx(), t);
let path = [PathName(token::intern(s.as_slice())),
gensym_name(name)];
mangle(ast_map::Values(path.iter()), Some(hash.as_slice()), None)
}
-pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> StrBuf {
+pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> String {
mangle(path.chain(Some(gensym_name(flav)).move_iter()), None, None)
}
-pub fn output_lib_filename(id: &CrateId) -> StrBuf {
+pub fn output_lib_filename(id: &CrateId) -> String {
format_strbuf!("{}-{}-{}",
id.name,
crate_id_hash(id),
id.version_or_default())
}
-pub fn get_cc_prog(sess: &Session) -> StrBuf {
+pub fn get_cc_prog(sess: &Session) -> String {
match sess.opts.cg.linker {
Some(ref linker) => return linker.to_strbuf(),
None => {}
}.to_strbuf()
}
-pub fn get_ar_prog(sess: &Session) -> StrBuf {
+pub fn get_ar_prog(sess: &Session) -> String {
match sess.opts.cg.ar {
Some(ref ar) => (*ar).clone(),
None => "ar".to_strbuf()
use flate;
pub fn run(sess: &session::Session, llmod: ModuleRef,
- tm: TargetMachineRef, reachable: &[StrBuf]) {
+ tm: TargetMachineRef, reachable: &[String]) {
if sess.opts.cg.prefer_dynamic {
sess.err("cannot prefer dynamic linking when performing LTO");
sess.note("only 'staticlib' and 'bin' outputs are supported with LTO");
use metadata::loader::meta_section_name;
use syntax::abi;
-pub fn get_target_strs(target_triple: StrBuf, target_os: abi::Os) -> target_strs::t {
+pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: "".to_strbuf(),
os != abi::OsWin32
}
-pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<StrBuf> {
+pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<String> {
let os = sess.targ_cfg.os;
// No rpath on windows
flags
}
-pub fn rpaths_to_flags(rpaths: &[StrBuf]) -> Vec<StrBuf> {
+pub fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> {
let mut ret = Vec::new();
for rpath in rpaths.iter() {
ret.push(format!("-Wl,-rpath,{}", (*rpath).as_slice()));
sysroot: &Path,
output: &Path,
libs: &[Path],
- target_triple: &str) -> Vec<StrBuf> {
+ target_triple: &str) -> Vec<String> {
debug!("sysroot: {}", sysroot.display());
debug!("output: {}", output.display());
debug!("libs:");
// And a final backup rpath to the global library location.
let fallback_rpaths = vec!(get_install_prefix_rpath(sysroot, target_triple));
- fn log_rpaths(desc: &str, rpaths: &[StrBuf]) {
+ fn log_rpaths(desc: &str, rpaths: &[String]) {
debug!("{} rpaths:", desc);
for rpath in rpaths.iter() {
debug!(" {}", *rpath);
fn get_rpaths_relative_to_output(os: abi::Os,
output: &Path,
- libs: &[Path]) -> Vec<StrBuf> {
+ libs: &[Path]) -> Vec<String> {
libs.iter().map(|a| get_rpath_relative_to_output(os, output, a)).collect()
}
pub fn get_rpath_relative_to_output(os: abi::Os,
output: &Path,
lib: &Path)
- -> StrBuf {
+ -> String {
use std::os;
assert!(not_win32(os));
relative.as_str().expect("non-utf8 component in path"))
}
-pub fn get_install_prefix_rpath(sysroot: &Path, target_triple: &str) -> StrBuf {
+pub fn get_install_prefix_rpath(sysroot: &Path, target_triple: &str) -> String {
let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
path.as_str().expect("non-utf8 component in rpath").to_strbuf()
}
-pub fn minimize_rpaths(rpaths: &[StrBuf]) -> Vec<StrBuf> {
+pub fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
let mut set = HashSet::new();
let mut minimized = Vec::new();
for rpath in rpaths.iter() {
#[deriving(Clone, Eq)]
pub struct Svh {
- hash: StrBuf,
+ hash: String,
}
impl Svh {
#![allow(non_camel_case_types)]
pub struct t {
- pub module_asm: StrBuf,
- pub meta_sect_name: StrBuf,
- pub data_layout: StrBuf,
- pub target_triple: StrBuf,
- pub cc_args: Vec<StrBuf> ,
+ pub module_asm: String,
+ pub meta_sect_name: String,
+ pub data_layout: String,
+ pub target_triple: String,
+ pub cc_args: Vec<String> ,
}
use metadata::loader::meta_section_name;
use syntax::abi;
-pub fn get_target_strs(target_triple: StrBuf, target_os: abi::Os)
+pub fn get_target_strs(target_triple: String, target_os: abi::Os)
-> target_strs::t {
return target_strs::t {
module_asm: "".to_strbuf(),
use metadata::loader::meta_section_name;
use syntax::abi;
-pub fn get_target_strs(target_triple: StrBuf, target_os: abi::Os) -> target_strs::t {
+pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: "".to_strbuf(),
// this.
pub addl_lib_search_paths: RefCell<HashSet<Path>>,
pub maybe_sysroot: Option<Path>,
- pub target_triple: StrBuf,
+ pub target_triple: String,
// User-specified cfg meta items. The compiler itself will add additional
// items to the crate config, and during parsing the entire crate config
// will be added to the crate AST node. This should not be used for
}
}
- fn parse_opt_string(slot: &mut Option<StrBuf>, v: Option<&str>) -> bool {
+ fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
match v {
Some(s) => { *slot = Some(s.to_strbuf()); true },
None => false,
}
}
- fn parse_string(slot: &mut StrBuf, v: Option<&str>) -> bool {
+ fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
match v {
Some(s) => { *slot = s.to_strbuf(); true },
None => false,
}
}
- fn parse_list(slot: &mut Vec<StrBuf>, v: Option<&str>)
+ fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
-> bool {
match v {
Some(s) => {
) )
cgoptions!(
- ar: Option<StrBuf> = (None, parse_opt_string,
+ ar: Option<String> = (None, parse_opt_string,
"tool to assemble archives with"),
- linker: Option<StrBuf> = (None, parse_opt_string,
+ linker: Option<String> = (None, parse_opt_string,
"system linker to link outputs with"),
- link_args: Vec<StrBuf> = (Vec::new(), parse_list,
+ link_args: Vec<String> = (Vec::new(), parse_list,
"extra arguments to pass to the linker (space separated)"),
- target_cpu: StrBuf = ("generic".to_strbuf(), parse_string,
+ target_cpu: String = ("generic".to_strbuf(), parse_string,
"select target processor (llc -mcpu=help for details)"),
- target_feature: StrBuf = ("".to_strbuf(), parse_string,
+ target_feature: String = ("".to_strbuf(), parse_string,
"target specific attributes (llc -mattr=help for details)"),
- passes: Vec<StrBuf> = (Vec::new(), parse_list,
+ passes: Vec<String> = (Vec::new(), parse_list,
"a list of extra LLVM passes to run (space separated)"),
- llvm_args: Vec<StrBuf> = (Vec::new(), parse_list,
+ llvm_args: Vec<String> = (Vec::new(), parse_list,
"a list of arguments to pass to llvm (space separated)"),
save_temps: bool = (false, parse_bool,
"save all temporary output files during compilation"),
"prefer dynamic linking to static linking"),
no_integrated_as: bool = (false, parse_bool,
"use an external assembler rather than LLVM's integrated one"),
- relocation_model: StrBuf = ("pic".to_strbuf(), parse_string,
+ relocation_model: String = ("pic".to_strbuf(), parse_string,
"choose the relocation model to use (llc -relocation-model for details)"),
)
// Convert strings provided as --cfg [cfgspec] into a crate_cfg
-fn parse_cfgspecs(cfgspecs: Vec<StrBuf> ) -> ast::CrateConfig {
+fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
cfgspecs.move_iter().map(|s| {
parse::parse_meta_from_source_str("cfgspec".to_strbuf(),
s.to_strbuf(),
* The name used for source code that doesn't originate in a file
* (e.g. source from stdin or a string)
*/
-pub fn anon_src() -> StrBuf {
+pub fn anon_src() -> String {
"<anon>".to_strbuf()
}
-pub fn source_name(input: &Input) -> StrBuf {
+pub fn source_name(input: &Input) -> String {
match *input {
// FIXME (#9639): This needs to handle non-utf8 paths
FileInput(ref ifile) => ifile.as_str().unwrap().to_strbuf(),
/// Load source from file
FileInput(Path),
/// The string is the source
- StrInput(StrBuf)
+ StrInput(String)
}
impl Input {
- fn filestem(&self) -> StrBuf {
+ fn filestem(&self) -> String {
match *self {
FileInput(ref ifile) => ifile.filestem_str().unwrap().to_strbuf(),
StrInput(_) => "rust_out".to_strbuf(),
pub metadata_module: ModuleRef,
pub link: LinkMeta,
pub metadata: Vec<u8>,
- pub reachable: Vec<StrBuf>,
+ pub reachable: Vec<String>,
pub crate_formats: dependency_format::Dependencies,
pub no_builtins: bool,
}
let result = (|| {
// Build a list of files used to compile the output and
// write Makefile-compatible dependency rules
- let files: Vec<StrBuf> = sess.codemap().files.borrow()
+ let files: Vec<String> = sess.codemap().files.borrow()
.iter().filter(|fmap| fmap.is_real_file())
.map(|fmap| fmap.name.to_strbuf())
.collect();
pub struct OutputFilenames {
pub out_directory: Path,
- pub out_filestem: StrBuf,
+ pub out_filestem: String,
pub single_output_file: Option<Path>,
}
pub mod config;
-pub fn main_args(args: &[StrBuf]) -> int {
+pub fn main_args(args: &[String]) -> int {
let owned_args = args.to_owned();
monitor(proc() run_compiler(owned_args));
0
static BUG_REPORT_URL: &'static str =
"http://doc.rust-lang.org/complement-bugreport.html";
-fn run_compiler(args: &[StrBuf]) {
+fn run_compiler(args: &[String]) {
let matches = match handle_options(Vec::from_slice(args)) {
Some(matches) => matches,
None => return
for &(_, name) in lint_dict.iter() {
max_key = cmp::max(name.len(), max_key);
}
- fn padded(max: uint, s: &str) -> StrBuf {
+ fn padded(max: uint, s: &str) -> String {
format!("{}{}", " ".repeat(max - s.len()), s)
}
println!("\nAvailable lint checks:\n");
/// Process command line options. Emits messages as appropirate.If compilation
/// should continue, returns a getopts::Matches object parsed from args, otherwise
/// returns None.
-pub fn handle_options(mut args: Vec<StrBuf>) -> Option<getopts::Matches> {
+pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.shift().unwrap();
// expected to be absolute. `None` means that there is no source file.
pub local_crate_source_file: Option<Path>,
pub working_dir: Path,
- pub lints: RefCell<NodeMap<Vec<(lint::Lint, codemap::Span, StrBuf)>>>,
+ pub lints: RefCell<NodeMap<Vec<(lint::Lint, codemap::Span, String)>>>,
pub node_id: Cell<ast::NodeId>,
pub crate_types: RefCell<Vec<config::CrateType>>,
pub features: front::feature_gate::Features,
lint: lint::Lint,
id: ast::NodeId,
sp: Span,
- msg: StrBuf) {
+ msg: String) {
let mut lints = self.lints.borrow_mut();
match lints.find_mut(&id) {
Some(arr) => { arr.push((lint, sp, msg)); return; }
}
// Seems out of place, but it uses session, so I'm putting it here
-pub fn expect<T:Clone>(sess: &Session, opt: Option<T>, msg: || -> StrBuf)
+pub fn expect<T:Clone>(sess: &Session, opt: Option<T>, msg: || -> String)
-> T {
diagnostic::expect(sess.diagnostic(), opt, msg)
}
/* Memory-managed object interface to type handles. */
pub struct TypeNames {
- named_types: RefCell<HashMap<StrBuf, TypeRef>>,
+ named_types: RefCell<HashMap<String, TypeRef>>,
}
impl TypeNames {
self.named_types.borrow().find_equiv(&s).map(|x| Type::from_ref(*x))
}
- pub fn type_to_str(&self, ty: Type) -> StrBuf {
+ pub fn type_to_str(&self, ty: Type) -> String {
unsafe {
let s = llvm::LLVMTypeToString(ty.to_ref());
let ret = from_c_str(s);
}
}
- pub fn types_to_str(&self, tys: &[Type]) -> StrBuf {
- let strs: Vec<StrBuf> = tys.iter().map(|t| self.type_to_str(*t)).collect();
+ pub fn types_to_str(&self, tys: &[Type]) -> String {
+ let strs: Vec<String> = tys.iter().map(|t| self.type_to_str(*t)).collect();
format_strbuf!("[{}]", strs.connect(",").to_strbuf())
}
- pub fn val_to_str(&self, val: ValueRef) -> StrBuf {
+ pub fn val_to_str(&self, val: ValueRef) -> String {
unsafe {
let s = llvm::LLVMValueToString(val);
let ret = from_c_str(s);
}
struct CrateInfo {
- ident: StrBuf,
+ ident: String,
crate_id: CrateId,
id: ast::NodeId,
should_link: bool,
pub vis: ast::Visibility,
}
-pub fn get_symbol(cstore: &cstore::CStore, def: ast::DefId) -> StrBuf {
+pub fn get_symbol(cstore: &cstore::CStore, def: ast::DefId) -> String {
let cdata = cstore.get_crate_data(def.krate);
decoder::get_symbol(cdata.data(), def.node)
}
pub fn get_native_libraries(cstore: &cstore::CStore,
crate_num: ast::CrateNum)
- -> Vec<(cstore::NativeLibaryKind, StrBuf)> {
+ -> Vec<(cstore::NativeLibaryKind, String)> {
let cdata = cstore.get_crate_data(crate_num);
decoder::get_native_libraries(&*cdata)
}
}
pub struct crate_metadata {
- pub name: StrBuf,
+ pub name: String,
pub data: MetadataBlob,
pub cnum_map: cnum_map,
pub cnum: ast::CrateNum,
metas: RefCell<HashMap<ast::CrateNum, Rc<crate_metadata>>>,
extern_mod_crate_map: RefCell<extern_mod_crate_map>,
used_crate_sources: RefCell<Vec<CrateSource>>,
- used_libraries: RefCell<Vec<(StrBuf, NativeLibaryKind)>>,
- used_link_args: RefCell<Vec<StrBuf>>,
+ used_libraries: RefCell<Vec<(String, NativeLibaryKind)>>,
+ used_link_args: RefCell<Vec<String>>,
pub intr: Rc<IdentInterner>,
}
libs
}
- pub fn add_used_library(&self, lib: StrBuf, kind: NativeLibaryKind) {
+ pub fn add_used_library(&self, lib: String, kind: NativeLibaryKind) {
assert!(!lib.is_empty());
self.used_libraries.borrow_mut().push((lib, kind));
}
pub fn get_used_libraries<'a>(&'a self)
- -> &'a RefCell<Vec<(StrBuf, NativeLibaryKind)> > {
+ -> &'a RefCell<Vec<(String, NativeLibaryKind)> > {
&self.used_libraries
}
}
}
- pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<StrBuf> > {
+ pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String> > {
&self.used_link_args
}
ret
}
-fn item_symbol(item: ebml::Doc) -> StrBuf {
+fn item_symbol(item: ebml::Doc) -> String {
reader::get_doc(item, tag_items_data_item_symbol).as_str().to_strbuf()
}
}
-pub fn get_symbol(data: &[u8], id: ast::NodeId) -> StrBuf {
+pub fn get_symbol(data: &[u8], id: ast::NodeId) -> String {
return item_symbol(lookup_item(id, data));
}
let cratedoc = reader::Doc(data);
let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
let mut crate_num = 1;
- fn docstr(doc: ebml::Doc, tag_: uint) -> StrBuf {
+ fn docstr(doc: ebml::Doc, tag_: uint) -> String {
let d = reader::get_doc(doc, tag_);
d.as_str_slice().to_strbuf()
}
})
}
-pub fn get_crate_triple(data: &[u8]) -> StrBuf {
+pub fn get_crate_triple(data: &[u8]) -> String {
let cratedoc = reader::Doc(data);
let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
triple_doc.expect("No triple in crate").as_str().to_strbuf()
pub fn get_native_libraries(cdata: Cmd)
- -> Vec<(cstore::NativeLibaryKind, StrBuf)> {
+ -> Vec<(cstore::NativeLibaryKind, String)> {
let libraries = reader::get_doc(reader::Doc(cdata.data()),
tag_native_libraries);
let mut result = Vec::new();
.map(|doc| FromPrimitive::from_u32(reader::doc_as_u32(doc)).unwrap())
}
-pub fn get_exported_macros(data: &[u8]) -> Vec<StrBuf> {
+pub fn get_exported_macros(data: &[u8]) -> Vec<String> {
let macros = reader::get_doc(reader::Doc(data),
tag_exported_macros);
let mut result = Vec::new();
pub diag: &'a SpanHandler,
pub tcx: &'a ty::ctxt,
pub reexports2: &'a middle::resolve::ExportMap2,
- pub item_symbols: &'a RefCell<NodeMap<StrBuf>>,
+ pub item_symbols: &'a RefCell<NodeMap<String>>,
pub non_inlineable_statics: &'a RefCell<NodeSet>,
pub link_meta: &'a LinkMeta,
pub cstore: &'a cstore::CStore,
pub diag: &'a SpanHandler,
pub tcx: &'a ty::ctxt,
pub reexports2: &'a middle::resolve::ExportMap2,
- pub item_symbols: &'a RefCell<NodeMap<StrBuf>>,
+ pub item_symbols: &'a RefCell<NodeMap<String>>,
pub non_inlineable_statics: &'a RefCell<NodeSet>,
pub link_meta: &'a LinkMeta,
pub cstore: &'a cstore::CStore,
ebml_w.end_tag();
}
-pub fn def_to_str(did: DefId) -> StrBuf {
+pub fn def_to_str(did: DefId) -> String {
format_strbuf!("{}:{}", did.krate, did.node)
}
cstore::RequireDynamic => "d",
cstore::RequireStatic => "s",
})).to_strbuf())
- }).collect::<Vec<StrBuf>>();
+ }).collect::<Vec<String>>();
ebml_w.writer.write(s.connect(",").as_bytes());
}
None => {}
}
// Get the encoded string for a type
-pub fn encoded_ty(tcx: &ty::ctxt, t: ty::t) -> StrBuf {
+pub fn encoded_ty(tcx: &ty::ctxt, t: ty::t) -> String {
let mut wr = MemWriter::new();
tyencode::enc_ty(&mut wr, &tyencode::ctxt {
diag: tcx.sess.diagnostic(),
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
-pub fn get_rust_path() -> Option<StrBuf> {
+pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_strbuf())
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
-fn find_libdir(sysroot: &Path) -> StrBuf {
+fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
}
#[cfg(target_word_size = "64")]
- fn primary_libdir_name() -> StrBuf {
+ fn primary_libdir_name() -> String {
"lib64".to_strbuf()
}
#[cfg(target_word_size = "32")]
- fn primary_libdir_name() -> StrBuf {
+ fn primary_libdir_name() -> String {
"lib32".to_strbuf()
}
- fn secondary_libdir_name() -> StrBuf {
+ fn secondary_libdir_name() -> String {
"lib".to_strbuf()
}
}
#[cfg(windows)]
-fn find_libdir(_sysroot: &Path) -> StrBuf {
+fn find_libdir(_sysroot: &Path) -> String {
"bin".to_strbuf()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
-pub fn rustlibdir() -> StrBuf {
+pub fn rustlibdir() -> String {
"rustlib".to_strbuf()
}
pub struct CrateMismatch {
path: Path,
- got: StrBuf,
+ got: String,
}
pub struct Context<'a> {
}
pub struct CratePaths {
- pub ident: StrBuf,
+ pub ident: String,
pub dylib: Option<Path>,
pub rlib: Option<Path>
}
//
// If everything checks out, then `Some(hash)` is returned where `hash` is
// the listed hash in the filename itself.
- fn try_match(&self, file: &str, prefix: &str, suffix: &str) -> Option<StrBuf>{
+ fn try_match(&self, file: &str, prefix: &str, suffix: &str) -> Option<String>{
let middle = file.slice(prefix.len(), file.len() - suffix.len());
debug!("matching -- {}, middle: {}", file, middle);
let mut parts = middle.splitn('-', 1);
}
// Just a small wrapper to time how long reading metadata takes.
-fn get_metadata_section(os: Os, filename: &Path) -> Result<MetadataBlob, StrBuf> {
+fn get_metadata_section(os: Os, filename: &Path) -> Result<MetadataBlob, String> {
let start = time::precise_time_ns();
let ret = get_metadata_section_imp(os, filename);
info!("reading {} => {}ms", filename.filename_display(),
return ret;
}
-fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, StrBuf> {
+fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, String> {
if !filename.exists() {
return Err(format_strbuf!("no such file: '{}'", filename.display()));
}
use std::rc::Rc;
use std::str;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::uint;
use syntax::abi;
use syntax::ast;
}
}
-fn parse_str(st: &mut PState, term: char) -> StrBuf {
- let mut result = StrBuf::new();
+fn parse_str(st: &mut PState, term: char) -> String {
+ let mut result = String::new();
while peek(st) != term {
unsafe {
result.push_bytes([next_byte(st)])
pub struct ctxt<'a> {
pub diag: &'a SpanHandler,
// Def -> str Callback:
- pub ds: fn(DefId) -> StrBuf,
+ pub ds: fn(DefId) -> String,
// The type context.
pub tcx: &'a ty::ctxt,
pub abbrevs: &'a abbrev_map
pub struct ty_abbrev {
pos: uint,
len: uint,
- s: StrBuf
+ s: String
}
pub type abbrev_map = RefCell<HashMap<ty::t, ty_abbrev>>;
use std::io::MemWriter;
use std::mem;
use std::rc::Rc;
-use std::strbuf::StrBuf;
+use std::string::String;
use serialize::ebml::reader;
use serialize::ebml;
Ok(ty)
}).unwrap();
- fn type_string(doc: ebml::Doc) -> StrBuf {
- let mut str = StrBuf::new();
+ fn type_string(doc: ebml::Doc) -> String {
+ let mut str = String::new();
for i in range(doc.start, doc.end) {
str.push_char(doc.data[i] as char);
}
use std::cell::{Cell};
use std::ops::{BitOr, BitAnd};
use std::rc::Rc;
-use std::strbuf::StrBuf;
+use std::string::String;
use syntax::ast;
use syntax::ast_map;
use syntax::ast_util;
make_stat(&bccx, bccx.stats.stable_paths.get()));
}
- fn make_stat(bccx: &BorrowckCtxt, stat: uint) -> StrBuf {
+ fn make_stat(bccx: &BorrowckCtxt, stat: uint) -> String {
let stat_f = stat as f64;
let total = bccx.stats.guaranteed_paths.get() as f64;
format_strbuf!("{} ({:.0f}%)", stat , stat_f * 100.0 / total)
}
impl Repr for RestrictionSet {
- fn repr(&self, _tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ty::ctxt) -> String {
format_strbuf!("RestrictionSet(0x{:x})", self.bits as uint)
}
}
self.tcx.sess.span_end_note(s, m);
}
- pub fn bckerr_to_str(&self, err: &BckError) -> StrBuf {
+ pub fn bckerr_to_str(&self, err: &BckError) -> String {
match err.code {
err_mutbl => {
let descr = match opt_loan_path(&err.cmt) {
pub fn append_loan_path_to_str(&self,
loan_path: &LoanPath,
- out: &mut StrBuf) {
+ out: &mut String) {
match *loan_path {
LpVar(id) => {
out.push_str(ty::local_var_name_str(self.tcx, id).get());
pub fn append_autoderefd_loan_path_to_str(&self,
loan_path: &LoanPath,
- out: &mut StrBuf) {
+ out: &mut String) {
match *loan_path {
LpExtend(ref lp_base, _, LpDeref(_)) => {
// For a path like `(*x).f` or `(*x)[3]`, autoderef
}
}
- pub fn loan_path_to_str(&self, loan_path: &LoanPath) -> StrBuf {
- let mut result = StrBuf::new();
+ pub fn loan_path_to_str(&self, loan_path: &LoanPath) -> String {
+ let mut result = String::new();
self.append_loan_path_to_str(loan_path, &mut result);
result
}
- pub fn cmt_to_str(&self, cmt: &mc::cmt_) -> StrBuf {
+ pub fn cmt_to_str(&self, cmt: &mc::cmt_) -> String {
self.mc().cmt_to_str(cmt)
}
}
}
impl Repr for Loan {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
(format!("Loan_{:?}({}, {:?}, {:?}-{:?}, {})",
self.index,
self.loan_path.repr(tcx),
}
impl Repr for Restriction {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
(format!("Restriction({}, {:x})",
self.loan_path.repr(tcx),
self.set.bits as uint)).to_strbuf()
}
impl Repr for LoanPath {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
match self {
&LpVar(id) => {
(format!("$({})", tcx.map.node_to_str(id))).to_strbuf()
pub struct LabelledCFG<'a>{
pub ast_map: &'a ast_map::Map,
pub cfg: &'a cfg::CFG,
- pub name: StrBuf,
+ pub name: String,
}
-fn replace_newline_with_backslash_l(s: StrBuf) -> StrBuf {
+fn replace_newline_with_backslash_l(s: String) -> String {
// Replacing newlines with \\l causes each line to be left-aligned,
// improving presentation of (long) pretty-printed expressions.
if s.as_slice().contains("\n") {
}
fn edge_label(&self, e: &Edge<'a>) -> dot::LabelText<'a> {
- let mut label = StrBuf::new();
+ let mut label = String::new();
let mut put_one = false;
for (i, &node_id) in e.data.exiting_scopes.iter().enumerate() {
if put_one {
use syntax::print::pprust;
-fn safe_type_for_static_mut(cx: &ty::ctxt, e: &ast::Expr) -> Option<StrBuf> {
+fn safe_type_for_static_mut(cx: &ty::ctxt, e: &ast::Expr) -> Option<String> {
let node_ty = ty::node_id_to_type(cx, e.id);
let tcontents = ty::type_contents(cx, node_ty);
debug!("safe_type_for_static_mut(dtor={}, managed={}, owned={})",
}
impl<'a> CheckStaticVisitor<'a> {
- fn report_error(&self, span: Span, result: Option<StrBuf>) -> bool {
+ fn report_error(&self, span: Span, result: Option<String>) -> bool {
match result {
None => { false }
Some(msg) => {
}
pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
- -> Result<const_val, StrBuf> {
- fn fromb(b: bool) -> Result<const_val, StrBuf> { Ok(const_int(b as i64)) }
+ -> Result<const_val, String> {
+ fn fromb(b: bool) -> Result<const_val, String> { Ok(const_int(b as i64)) }
match e.node {
ExprUnary(UnNeg, inner) => {
match eval_const_expr_partial(tcx, inner) {
use std::io;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::uint;
use syntax::ast;
use syntax::ast_util;
}
}
-fn mut_bits_to_str(words: &mut [uint]) -> StrBuf {
+fn mut_bits_to_str(words: &mut [uint]) -> String {
bits_to_str(words)
}
-fn bits_to_str(words: &[uint]) -> StrBuf {
- let mut result = StrBuf::new();
+fn bits_to_str(words: &[uint]) -> String {
+ let mut result = String::new();
let mut sep = '[';
// Note: this is a little endian printout of bytes.
oldv != newv
}
-fn bit_str(bit: uint) -> StrBuf {
+fn bit_str(bit: uint) -> String {
let byte = bit >> 8;
let lobits = 1 << (bit & 0xFF);
format_strbuf!("[{}:{}-{:02x}]", bit, byte, lobits)
}
// Ensure that `ty` has a statically known size (i.e., it has the `Sized` bound).
-fn check_sized(tcx: &ty::ctxt, ty: ty::t, name: StrBuf, sp: Span) {
+fn check_sized(tcx: &ty::ctxt, ty: ty::t, name: String, sp: Span) {
if !ty::type_is_sized(tcx, ty) {
tcx.sess.span_err(sp,
format!("variable `{}` has dynamically sized type \
}
}
- pub fn require(&self, it: LangItem) -> Result<ast::DefId, StrBuf> {
+ pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> {
match self.items.get(it as uint) {
&Some(id) => Ok(id),
&None => {
ExitNode
}
-fn live_node_kind_to_str(lnk: LiveNodeKind, cx: &ty::ctxt) -> StrBuf {
+fn live_node_kind_to_str(lnk: LiveNodeKind, cx: &ty::ctxt) -> String {
let cm = cx.sess.codemap();
match lnk {
FreeVarNode(s) => {
}
}
- fn variable_name(&self, var: Variable) -> StrBuf {
+ fn variable_name(&self, var: Variable) -> String {
match self.var_kinds.get(var.get()) {
&Local(LocalInfo { ident: nm, .. }) | &Arg(_, nm) => {
token::get_ident(nm).get().to_str().to_strbuf()
}
#[allow(unused_must_use)]
- fn ln_str(&self, ln: LiveNode) -> StrBuf {
+ fn ln_str(&self, ln: LiveNode) -> String {
let mut wr = io::MemWriter::new();
{
let wr = &mut wr as &mut io::Writer;
}
}
- fn should_warn(&self, var: Variable) -> Option<StrBuf> {
+ fn should_warn(&self, var: Variable) -> Option<String> {
let name = self.ir.variable_name(var);
if name.len() == 0 || name.as_slice()[0] == ('_' as u8) {
None
Ok(())
}
- pub fn cmt_to_str(&self, cmt: &cmt_) -> StrBuf {
+ pub fn cmt_to_str(&self, cmt: &cmt_) -> String {
match cmt.cat {
cat_static_item => {
"static item".to_strbuf()
}
impl Repr for cmt_ {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
format_strbuf!("\\{{} id:{} m:{:?} ty:{}\\}",
self.cat.repr(tcx),
self.id,
}
impl Repr for categorization {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
cat_static_item |
cat_rvalue(..) |
}
impl Repr for InteriorKind {
- fn repr(&self, _tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ty::ctxt) -> String {
match *self {
InteriorField(NamedField(fld)) => {
token::get_name(fld).get().to_str().to_strbuf()
/// Result of a checking operation - None => no errors were found. Some => an
/// error and contains the span and message for reporting that error and
/// optionally the same for a note about the error.
-type CheckResult = Option<(Span, StrBuf, Option<(Span, StrBuf)>)>;
+type CheckResult = Option<(Span, String, Option<(Span, String)>)>;
////////////////////////////////////////////////////////////////////////////////
/// The parent visitor, used to determine what's the parent of what (node-wise)
impl<'a> PrivacyVisitor<'a> {
// used when debugging
- fn nodestr(&self, id: ast::NodeId) -> StrBuf {
+ fn nodestr(&self, id: ast::NodeId) -> String {
self.tcx.map.node_to_str(id).to_strbuf()
}
use std::cell::{Cell, RefCell};
use std::mem::replace;
use std::rc::{Rc, Weak};
-use std::strbuf::StrBuf;
+use std::string::String;
use std::uint;
// Definition mapping
pub type ExportMap2 = RefCell<NodeMap<Vec<Export2> >>;
pub struct Export2 {
- pub name: StrBuf, // The name of the target.
+ pub name: String, // The name of the target.
pub def_id: DefId, // The definition of the target.
}
Field,
Method,
TraitMethod,
- StaticMethod(StrBuf),
- StaticTraitMethod(StrBuf),
+ StaticMethod(String),
+ StaticTraitMethod(String),
}
enum TypeParameters<'a> {
}
}
- fn idents_to_str(&self, idents: &[Ident]) -> StrBuf {
+ fn idents_to_str(&self, idents: &[Ident]) -> String {
let mut first = true;
- let mut result = StrBuf::new();
+ let mut result = String::new();
for ident in idents.iter() {
if first {
first = false
result
}
- fn path_idents_to_str(&self, path: &Path) -> StrBuf {
+ fn path_idents_to_str(&self, path: &Path) -> String {
let identifiers: Vec<ast::Ident> = path.segments
.iter()
.map(|seg| seg.identifier)
fn import_directive_subclass_to_str(&mut self,
subclass: ImportDirectiveSubclass)
- -> StrBuf {
+ -> String {
match subclass {
SingleImport(_, source) => {
token::get_ident(source).get().to_strbuf()
fn import_path_to_str(&mut self,
idents: &[Ident],
subclass: ImportDirectiveSubclass)
- -> StrBuf {
+ -> String {
if idents.is_empty() {
self.import_directive_subclass_to_str(subclass)
} else {
}
fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
- -> Option<StrBuf> {
+ -> Option<String> {
let this = &mut *self;
let mut maybes: Vec<token::InternedString> = Vec::new();
//
/// A somewhat inefficient routine to obtain the name of a module.
- fn module_to_str(&mut self, module: &Module) -> StrBuf {
+ fn module_to_str(&mut self, module: &Module) -> String {
let mut idents = Vec::new();
fn collect_mod(idents: &mut Vec<ast::Ident>, module: &Module) {
}
impl<'a, 'b> Repr for Match<'a, 'b> {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
if tcx.sess.verbose() {
// for many programs, this just take too long to serialize
self.pats.repr(tcx)
use middle::trans::type_::Type;
use std::c_str::ToCStr;
-use std::strbuf::StrBuf;
+use std::string::String;
use syntax::ast;
// Take an inline assembly expression and splat it out via LLVM
fcx.pop_custom_cleanup_scope(temp_scope);
let mut constraints =
- StrBuf::from_str(constraints.iter()
+ String::from_str(constraints.iter()
.map(|s| s.get().to_strbuf())
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.connect(",")
.as_slice());
#[cfg(target_arch = "arm")]
#[cfg(target_arch = "mips")]
-fn getClobbers() -> StrBuf {
+fn getClobbers() -> String {
"".to_strbuf()
}
#[cfg(target_arch = "x86")]
#[cfg(target_arch = "x86_64")]
-fn getClobbers() -> StrBuf {
+fn getClobbers() -> String {
"~{dirflag},~{fpsr},~{flags}".to_strbuf()
}
pub struct StatRecorder<'a> {
ccx: &'a CrateContext,
- name: Option<StrBuf>,
+ name: Option<String>,
start: u64,
istart: uint,
}
impl<'a> StatRecorder<'a> {
- pub fn new(ccx: &'a CrateContext, name: StrBuf) -> StatRecorder<'a> {
+ pub fn new(ccx: &'a CrateContext, name: String) -> StatRecorder<'a> {
let start = if ccx.sess().trans_stats() {
time::precise_time_ns()
} else {
// Double-check that we never ask LLVM to declare the same symbol twice. It
// silently mangles such symbols, breaking our linkage model.
-pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: StrBuf) {
+pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
if ccx.all_llvm_symbols.borrow().contains(&sym) {
ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
}
}
}
-fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: StrBuf, node_id: ast::NodeId,
+fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
llfn: ValueRef) {
ccx.item_symbols.borrow_mut().insert(node_id, sym);
fn register_fn(ccx: &CrateContext,
sp: Span,
- sym: StrBuf,
+ sym: String,
node_id: ast::NodeId,
node_type: ty::t)
-> ValueRef {
// only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
pub fn register_fn_llvmty(ccx: &CrateContext,
sp: Span,
- sym: StrBuf,
+ sym: String,
node_id: ast::NodeId,
cc: lib::llvm::CallConv,
llfty: Type) -> ValueRef {
}
fn exported_name(ccx: &CrateContext, id: ast::NodeId,
- ty: ty::t, attrs: &[ast::Attribute]) -> StrBuf {
+ ty: ty::t, attrs: &[ast::Attribute]) -> String {
match attr::first_attr_value_str_by_name(attrs, "export_name") {
// Use provided name
Some(name) => name.get().to_strbuf(),
let link_meta = ccx.link_meta.clone();
let llmod = ccx.llmod;
- let mut reachable: Vec<StrBuf> = ccx.reachable.iter().filter_map(|id| {
+ let mut reachable: Vec<String> = ccx.reachable.iter().filter_map(|id| {
ccx.item_symbols.borrow().find(id).map(|s| s.to_strbuf())
}).collect();
terminate(cx, "Invoke");
debug!("Invoke({} with arguments ({}))",
cx.val_to_str(fn_),
- args.iter().map(|a| cx.val_to_str(*a)).collect::<Vec<StrBuf>>().connect(", "));
+ args.iter().map(|a| cx.val_to_str(*a)).collect::<Vec<String>>().connect(", "));
B(cx).invoke(fn_, args, then, catch, attributes)
}
use middle::trans::type_::Type;
use collections::HashMap;
use libc::{c_uint, c_ulonglong, c_char};
-use std::strbuf::StrBuf;
+use std::string::String;
use syntax::codemap::Span;
pub struct Builder<'a> {
// Pass 2: concat strings for each elt, skipping
// forwards over any cycles by advancing to rightmost
// occurrence of each element in path.
- let mut s = StrBuf::from_str(".");
+ let mut s = String::from_str(".");
i = 0u;
while i < len {
i = *mm.get(&v[i]);
self.ccx.tn.val_to_str(llfn),
args.iter()
.map(|&v| self.ccx.tn.val_to_str(v))
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.connect(", "));
unsafe {
self.cleanups.iter().any(|c| c.clean_on_unwind())
}
- fn block_name(&self, prefix: &str) -> StrBuf {
+ fn block_name(&self, prefix: &str) -> String {
/*!
* Returns a suitable name to use for the basic block that
* handles this cleanup scope
}
impl EnvValue {
- pub fn to_str(&self, ccx: &CrateContext) -> StrBuf {
+ pub fn to_str(&self, ccx: &CrateContext) -> String {
format_strbuf!("{}({})", self.action, self.datum.to_str(ccx))
}
}
}
}
-pub type ExternMap = HashMap<StrBuf, ValueRef>;
+pub type ExternMap = HashMap<String, ValueRef>;
// Here `self_ty` is the real type of the self parameter to this method. It
// will only be set in the case of default methods.
}
}
-fn param_substs_to_str(this: ¶m_substs, tcx: &ty::ctxt) -> StrBuf {
+fn param_substs_to_str(this: ¶m_substs, tcx: &ty::ctxt) -> String {
format_strbuf!("param_substs({})", this.substs.repr(tcx))
}
impl Repr for param_substs {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
param_substs_to_str(self, tcx)
}
}
}
pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }
- pub fn ident(&self, ident: Ident) -> StrBuf {
+ pub fn ident(&self, ident: Ident) -> String {
token::get_ident(ident).get().to_strbuf()
}
- pub fn node_id_to_str(&self, id: ast::NodeId) -> StrBuf {
+ pub fn node_id_to_str(&self, id: ast::NodeId) -> String {
self.tcx().map.node_to_str(id).to_strbuf()
}
- pub fn expr_to_str(&self, e: &ast::Expr) -> StrBuf {
+ pub fn expr_to_str(&self, e: &ast::Expr) -> String {
e.repr(self.tcx())
}
}
}
- pub fn val_to_str(&self, val: ValueRef) -> StrBuf {
+ pub fn val_to_str(&self, val: ValueRef) -> String {
self.ccx().tn.val_to_str(val)
}
- pub fn llty_str(&self, ty: Type) -> StrBuf {
+ pub fn llty_str(&self, ty: Type) -> String {
self.ccx().tn.type_to_str(ty)
}
- pub fn ty_to_str(&self, t: ty::t) -> StrBuf {
+ pub fn ty_to_str(&self, t: ty::t) -> String {
t.repr(self.tcx())
}
- pub fn to_str(&self) -> StrBuf {
+ pub fn to_str(&self) -> String {
let blk: *Block = self;
format_strbuf!("[block {}]", blk)
}
pub n_inlines: Cell<uint>,
pub n_closures: Cell<uint>,
pub n_llvm_insns: Cell<uint>,
- pub llvm_insns: RefCell<HashMap<StrBuf, uint>>,
+ pub llvm_insns: RefCell<HashMap<String, uint>>,
// (ident, time-in-ms, llvm-instructions)
- pub fn_stats: RefCell<Vec<(StrBuf, uint, uint)> >,
+ pub fn_stats: RefCell<Vec<(String, uint, uint)> >,
}
pub struct CrateContext {
pub item_vals: RefCell<NodeMap<ValueRef>>,
pub exp_map2: resolve::ExportMap2,
pub reachable: NodeSet,
- pub item_symbols: RefCell<NodeMap<StrBuf>>,
+ pub item_symbols: RefCell<NodeMap<String>>,
pub link_meta: LinkMeta,
pub drop_glues: RefCell<HashMap<ty::t, ValueRef>>,
pub tydescs: RefCell<HashMap<ty::t, Rc<tydesc_info>>>,
pub llsizingtypes: RefCell<HashMap<ty::t, Type>>,
pub adt_reprs: RefCell<HashMap<ty::t, Rc<adt::Repr>>>,
pub symbol_hasher: RefCell<Sha256>,
- pub type_hashcodes: RefCell<HashMap<ty::t, StrBuf>>,
- pub all_llvm_symbols: RefCell<HashSet<StrBuf>>,
+ pub type_hashcodes: RefCell<HashMap<ty::t, String>>,
+ pub all_llvm_symbols: RefCell<HashSet<String>>,
pub tcx: ty::ctxt,
pub stats: Stats,
pub int_type: Type,
}
#[allow(dead_code)] // useful for debugging
- pub fn to_str(&self, ccx: &CrateContext) -> StrBuf {
+ pub fn to_str(&self, ccx: &CrateContext) -> String {
format_strbuf!("Datum({}, {}, {:?})",
ccx.tn.val_to_str(self.val),
ty_to_str(ccx.tcx(), self.ty),
use collections::HashSet;
use libc::{c_uint, c_ulonglong, c_longlong};
use std::ptr;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::sync::atomics;
use syntax::codemap::{Span, Pos};
use syntax::{abi, ast, codemap, ast_util, ast_map};
llcontext: ContextRef,
builder: DIBuilderRef,
current_debug_location: Cell<DebugLocation>,
- created_files: RefCell<HashMap<StrBuf, DIFile>>,
+ created_files: RefCell<HashMap<String, DIFile>>,
created_types: RefCell<HashMap<uint, DIType>>,
created_enum_disr_types: RefCell<HashMap<ast::DefId, DIType>>,
namespace_map: RefCell<HashMap<Vec<ast::Name>, Rc<NamespaceTreeNode>>>,
};
// get_template_parameters() will append a `<...>` clause to the function name if necessary.
- let mut function_name = StrBuf::from_str(token::get_ident(ident).get());
+ let mut function_name = String::from_str(token::get_ident(ident).get());
let template_parameters = get_template_parameters(cx,
generics,
param_substs,
generics: &ast::Generics,
param_substs: Option<¶m_substs>,
file_metadata: DIFile,
- name_to_append_suffix_to: &mut StrBuf)
+ name_to_append_suffix_to: &mut String)
-> DIArray {
let self_type = match param_substs {
Some(param_substs) => param_substs.substs.self_ty,
}
struct EnumVariantMemberDescriptionFactory {
- args: Vec<(StrBuf, ty::t)> ,
+ args: Vec<(String, ty::t)> ,
discriminant_type_metadata: Option<DIType>,
span: Span,
}
}
// Build an array of (field name, field type) pairs to be captured in the factory closure.
- let args: Vec<(StrBuf, ty::t)> = arg_names.iter()
+ let args: Vec<(String, ty::t)> = arg_names.iter()
.zip(struct_def.fields.iter())
.map(|(s, &t)| (s.to_strbuf(), t))
.collect();
}
struct MemberDescription {
- name: StrBuf,
+ name: String,
llvm_type: Type,
type_metadata: DIType,
offset: MemberOffset,
// Used to avoid LLVM metadata uniquing problems. See `create_struct_stub()` and
// `prepare_enum_metadata()`.
-fn generate_unique_type_id(prefix: &'static str) -> StrBuf {
+fn generate_unique_type_id(prefix: &'static str) -> String {
unsafe {
static mut unique_id_counter: atomics::AtomicUint = atomics::INIT_ATOMIC_UINT;
format_strbuf!("{}{}",
ast::ExprInlineAsm(ast::InlineAsm { inputs: ref inputs,
outputs: ref outputs,
.. }) => {
- // inputs, outputs: ~[(StrBuf, @expr)]
+ // inputs, outputs: ~[(String, @expr)]
for &(_, exp) in inputs.iter() {
walk_expr(cx, exp, scope_stack, scope_map);
}
}
impl NamespaceTreeNode {
- fn mangled_name_of_contained_item(&self, item_name: &str) -> StrBuf {
- fn fill_nested(node: &NamespaceTreeNode, output: &mut StrBuf) {
+ fn mangled_name_of_contained_item(&self, item_name: &str) -> String {
+ fn fill_nested(node: &NamespaceTreeNode, output: &mut String) {
match node.parent {
Some(ref parent) => fill_nested(&*parent.upgrade().unwrap(), output),
None => {}
output.push_str(string.get());
}
- let mut name = StrBuf::from_str("_ZN");
+ let mut name = String::from_str("_ZN");
fill_nested(self, &mut name);
name.push_str(format!("{}", item_name.len()).as_slice());
name.push_str(item_name);
}
impl Dest {
- pub fn to_str(&self, ccx: &CrateContext) -> StrBuf {
+ pub fn to_str(&self, ccx: &CrateContext) -> String {
match *self {
SaveIn(v) => format_strbuf!("SaveIn({})", ccx.tn.val_to_str(v)),
Ignore => "Ignore".to_strbuf()
pub fn register_rust_fn_with_foreign_abi(ccx: &CrateContext,
sp: Span,
- sym: StrBuf,
+ sym: String,
node_id: ast::NodeId)
-> ValueRef {
let _icx = push_ctxt("foreign::register_foreign_fn");
use lib::llvm::ValueRef;
pub trait LlvmRepr {
- fn llrepr(&self, ccx: &CrateContext) -> StrBuf;
+ fn llrepr(&self, ccx: &CrateContext) -> String;
}
impl<'a, T:LlvmRepr> LlvmRepr for &'a [T] {
- fn llrepr(&self, ccx: &CrateContext) -> StrBuf {
- let reprs: Vec<StrBuf> = self.iter().map(|t| t.llrepr(ccx)).collect();
+ fn llrepr(&self, ccx: &CrateContext) -> String {
+ let reprs: Vec<String> = self.iter().map(|t| t.llrepr(ccx)).collect();
format_strbuf!("[{}]", reprs.connect(","))
}
}
impl LlvmRepr for Type {
- fn llrepr(&self, ccx: &CrateContext) -> StrBuf {
+ fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn.type_to_str(*self)
}
}
impl LlvmRepr for ValueRef {
- fn llrepr(&self, ccx: &CrateContext) -> StrBuf {
+ fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn.val_to_str(*self)
}
}
}
impl VecTypes {
- pub fn to_str(&self, ccx: &CrateContext) -> StrBuf {
+ pub fn to_str(&self, ccx: &CrateContext) -> String {
format_strbuf!("VecTypes \\{unit_ty={}, llunit_ty={}, \
llunit_size={}, llunit_alloc_size={}\\}",
ty_to_str(ccx.tcx(), self.unit_ty),
what: named_ty,
did: ast::DefId,
tps: &[ty::t])
- -> StrBuf {
+ -> String {
let name = match what {
a_struct => { "struct" }
an_enum => { "enum" }
pub freevars: RefCell<freevars::freevar_map>,
pub tcache: type_cache,
pub rcache: creader_cache,
- pub short_names_cache: RefCell<HashMap<t, StrBuf>>,
+ pub short_names_cache: RefCell<HashMap<t, String>>,
pub needs_unwind_cleanup_cache: RefCell<HashMap<t, bool>>,
pub tc_cache: RefCell<HashMap<uint, TypeContents>>,
pub ast_ty_to_ty_cache: RefCell<NodeMap<ast_ty_to_ty_cache_entry>>,
substs.self_ty.is_none()
}
-pub fn substs_to_str(cx: &ctxt, substs: &substs) -> StrBuf {
+pub fn substs_to_str(cx: &ctxt, substs: &substs) -> String {
substs.repr(cx)
}
token::get_name(name),
fields.iter()
.map(|f| token::get_ident(f.ident).get().to_strbuf())
- .collect::<Vec<StrBuf>>()).as_slice());
+ .collect::<Vec<String>>()).as_slice());
}
pub fn method_idx(id: ast::Ident, meths: &[Rc<Method>]) -> Option<uint> {
rslt
}
-pub fn ty_sort_str(cx: &ctxt, t: t) -> StrBuf {
+pub fn ty_sort_str(cx: &ctxt, t: t) -> String {
match get(t).sty {
ty_nil | ty_bot | ty_bool | ty_char | ty_int(_) |
ty_uint(_) | ty_float(_) | ty_str => {
}
}
-pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> StrBuf {
+pub fn type_err_to_str(cx: &ctxt, err: &type_err) -> String {
/*!
*
* Explains the source of a type err in a short,
* to present additional details, particularly when
* it comes to lifetime-related errors. */
- fn tstore_to_closure(s: &TraitStore) -> StrBuf {
+ fn tstore_to_closure(s: &TraitStore) -> String {
match s {
&UniqTraitStore => "proc".to_strbuf(),
&RegionTraitStore(..) => "closure".to_strbuf()
}).collect()
}
-pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> StrBuf {
+pub fn item_path_str(cx: &ctxt, id: ast::DefId) -> String {
with_path(cx, id, |path| ast_map::path_to_str(path)).to_strbuf()
}
return true;
}
-pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, StrBuf> {
+pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, String> {
tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| {
tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item)
.expect("Failed to resolve TyDesc")
})
}
-pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, StrBuf> {
+pub fn get_opaque_ty(tcx: &ctxt) -> Result<t, String> {
tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| {
tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item)
.expect("Failed to resolve Opaque")
}
pub fn visitor_object_ty(tcx: &ctxt,
- region: ty::Region) -> Result<(Rc<TraitRef>, t), StrBuf> {
+ region: ty::Region) -> Result<(Rc<TraitRef>, t), String> {
let trait_lang_item = match tcx.lang_items.require(TyVisitorTraitLangItem) {
Ok(id) => id,
Err(s) => { return Err(s); }
self.fcx.tcx()
}
- fn ty_to_str(&self, t: ty::t) -> StrBuf {
+ fn ty_to_str(&self, t: ty::t) -> String {
self.fcx.infcx().ty_to_str(t)
}
- fn did_to_str(&self, did: DefId) -> StrBuf {
+ fn did_to_str(&self, did: DefId) -> String {
ty::item_path_str(self.tcx(), did)
}
}
impl Repr for Candidate {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
format_strbuf!("Candidate(rcvr_ty={}, rcvr_substs={}, method_ty={}, \
origin={:?})",
self.rcvr_match_condition.repr(tcx),
}
impl Repr for RcvrMatchCondition {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
RcvrMatchesIfObject(d) => {
format_strbuf!("RcvrMatchesIfObject({})", d.repr(tcx))
let ret_ty = fn_sig.output;
debug!("check_fn(arg_tys={:?}, ret_ty={:?})",
- arg_tys.iter().map(|&a| ppaux::ty_to_str(tcx, a)).collect::<Vec<StrBuf>>(),
+ arg_tys.iter().map(|&a| ppaux::ty_to_str(tcx, a)).collect::<Vec<String>>(),
ppaux::ty_to_str(tcx, ret_ty));
// Create the function context. This is either derived from scratch or,
}
impl<'a> FnCtxt<'a> {
- pub fn tag(&self) -> StrBuf {
+ pub fn tag(&self) -> String {
format_strbuf!("{}", self as *FnCtxt)
}
ast_ty_to_ty(self, self.infcx(), ast_t)
}
- pub fn pat_to_str(&self, pat: &ast::Pat) -> StrBuf {
+ pub fn pat_to_str(&self, pat: &ast::Pat) -> String {
pat.repr(self.tcx())
}
pub fn type_error_message(&self,
sp: Span,
- mk_msg: |StrBuf| -> StrBuf,
+ mk_msg: |String| -> String,
actual_ty: ty::t,
err: Option<&ty::type_err>) {
self.infcx().type_error_message(sp, mk_msg, actual_ty, err);
};
debug!("check_argument_types: formal_tys={:?}",
- formal_tys.iter().map(|t| fcx.infcx().ty_to_str(*t)).collect::<Vec<StrBuf>>());
+ formal_tys.iter().map(|t| fcx.infcx().ty_to_str(*t)).collect::<Vec<String>>());
// Check the arguments.
// We do this in a pretty awful way: first we typecheck any arguments
pub trait Combine {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a>;
- fn tag(&self) -> StrBuf;
+ fn tag(&self) -> String;
fn a_is_expected(&self) -> bool;
fn trace(&self) -> TypeTrace;
use std::cell::{Cell, RefCell};
use std::char::from_u32;
use std::rc::Rc;
-use std::strbuf::StrBuf;
+use std::string::String;
use syntax::ast;
use syntax::ast_map;
use syntax::ast_util;
trace: TypeTrace,
terr: &ty::type_err);
- fn values_str(&self, values: &ValuePairs) -> Option<StrBuf>;
+ fn values_str(&self, values: &ValuePairs) -> Option<String>;
fn expected_found_str<T:UserString+Resolvable>(
&self,
exp_found: &ty::expected_found<T>)
- -> Option<StrBuf>;
+ -> Option<String>;
fn report_concrete_failure(&self,
origin: SubregionOrigin,
ty::note_and_explain_type_err(self.tcx, terr);
}
- fn values_str(&self, values: &ValuePairs) -> Option<StrBuf> {
+ fn values_str(&self, values: &ValuePairs) -> Option<String> {
/*!
* Returns a string of the form "expected `{}` but found `{}`",
* or None if this is a derived error.
fn expected_found_str<T:UserString+Resolvable>(
&self,
exp_found: &ty::expected_found<T>)
- -> Option<StrBuf>
+ -> Option<String>
{
let expected = exp_found.expected.resolve(self);
if expected.contains_error() {
// LifeGiver is responsible for generating fresh lifetime names
struct LifeGiver {
- taken: HashSet<StrBuf>,
+ taken: HashSet<String>,
counter: Cell<uint>,
generated: RefCell<Vec<ast::Lifetime>>,
}
return lifetime;
// 0 .. 25 generates a .. z, 26 .. 51 generates aa .. zz, and so on
- fn num_to_str(counter: uint) -> StrBuf {
- let mut s = StrBuf::new();
+ fn num_to_str(counter: uint) -> String {
+ let mut s = String::new();
let (n, r) = (counter/26 + 1, counter % 26);
let letter: char = from_u32((r+97) as u32).unwrap();
for _ in range(0, n) {
impl<'f> Combine for Glb<'f> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx }
- fn tag(&self) -> StrBuf { "glb".to_strbuf() }
+ fn tag(&self) -> String { "glb".to_strbuf() }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace.clone() }
impl<'f> Combine for Lub<'f> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx }
- fn tag(&self) -> StrBuf { "lub".to_strbuf() }
+ fn tag(&self) -> String { "lub".to_strbuf() }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace.clone() }
region_var_bound_by_region_var(RegionVid, RegionVid)
}
-pub fn fixup_err_to_str(f: fixup_err) -> StrBuf {
+pub fn fixup_err_to_str(f: fixup_err) -> String {
match f {
unresolved_int_ty(_) => "unconstrained integral type".to_strbuf(),
unresolved_ty(_) => "unconstrained type".to_strbuf(),
self.report_region_errors(&errors); // see error_reporting.rs
}
- pub fn ty_to_str(&self, t: ty::t) -> StrBuf {
+ pub fn ty_to_str(&self, t: ty::t) -> String {
ty_to_str(self.tcx,
self.resolve_type_vars_if_possible(t))
}
- pub fn tys_to_str(&self, ts: &[ty::t]) -> StrBuf {
- let tstrs: Vec<StrBuf> = ts.iter().map(|t| self.ty_to_str(*t)).collect();
+ pub fn tys_to_str(&self, ts: &[ty::t]) -> String {
+ let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_str(*t)).collect();
format_strbuf!("({})", tstrs.connect(", "))
}
- pub fn trait_ref_to_str(&self, t: &ty::TraitRef) -> StrBuf {
+ pub fn trait_ref_to_str(&self, t: &ty::TraitRef) -> String {
let t = self.resolve_type_vars_in_trait_ref_if_possible(t);
trait_ref_to_str(self.tcx, &t)
}
// errors.
pub fn type_error_message_str(&self,
sp: Span,
- mk_msg: |Option<StrBuf>, StrBuf| -> StrBuf,
- actual_ty: StrBuf,
+ mk_msg: |Option<String>, String| -> String,
+ actual_ty: String,
err: Option<&ty::type_err>) {
self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err)
}
pub fn type_error_message_str_with_expected(&self,
sp: Span,
- mk_msg: |Option<StrBuf>,
- StrBuf|
- -> StrBuf,
+ mk_msg: |Option<String>,
+ String|
+ -> String,
expected_ty: Option<ty::t>,
- actual_ty: StrBuf,
+ actual_ty: String,
err: Option<&ty::type_err>) {
debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty);
pub fn type_error_message(&self,
sp: Span,
- mk_msg: |StrBuf| -> StrBuf,
+ mk_msg: |String| -> String,
actual_ty: ty::t,
err: Option<&ty::type_err>) {
let actual_ty = self.resolve_type_vars_if_possible(actual_ty);
// Don't report an error if expected is ty_err
ty::ty_err => return,
_ => {
- // if I leave out : StrBuf, it infers &str and complains
- |actual: StrBuf| {
+ // if I leave out : String, it infers &str and complains
+ |actual: String| {
format_strbuf!("mismatched types: expected `{}` but \
found `{}`",
self.ty_to_str(resolved_expected),
}
impl Repr for TypeTrace {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
format_strbuf!("TypeTrace({})", self.origin.repr(tcx))
}
}
}
impl Repr for TypeOrigin {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
MethodCompatCheck(a) => {
format_strbuf!("MethodCompatCheck({})", a.repr(tcx))
}
impl Repr for SubregionOrigin {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
Subtype(ref a) => {
format_strbuf!("Subtype({})", a.repr(tcx))
}
impl Repr for RegionVariableOrigin {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
MiscVariable(a) => {
format_strbuf!("MiscVariable({})", a.repr(tcx))
}
impl Repr for Constraint {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
ConstrainVarSubVar(a, b) => {
format_strbuf!("ConstrainVarSubVar({}, {})",
impl<'f> Combine for Sub<'f> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a> { self.get_ref().infcx }
- fn tag(&self) -> StrBuf { "sub".to_strbuf() }
+ fn tag(&self) -> String { "sub".to_strbuf() }
fn a_is_expected(&self) -> bool { self.get_ref().a_is_expected }
fn trace(&self) -> TypeTrace { self.get_ref().trace.clone() }
krate: @ast::Crate,
tcx: ty::ctxt,
infcx: infer::infer_ctxt,
- err_messages: @DVec<StrBuf>
+ err_messages: @DVec<String>
}
struct RH {
sub: &[]}]});
}
- pub fn lookup_item(&self, names: &[StrBuf]) -> ast::node_id {
+ pub fn lookup_item(&self, names: &[String]) -> ast::node_id {
return match search_mod(self, &self.krate.node.module, 0, names) {
Some(id) => id,
None => {
fn search_mod(self: &Env,
m: &ast::Mod,
idx: uint,
- names: &[StrBuf]) -> Option<ast::node_id> {
+ names: &[String]) -> Option<ast::node_id> {
assert!(idx < names.len());
for item in m.items.iter() {
if self.tcx.sess.str_of(item.ident) == names[idx] {
fn search(self: &Env,
it: @ast::Item,
idx: uint,
- names: &[StrBuf]) -> Option<ast::node_id> {
+ names: &[String]) -> Option<ast::node_id> {
if idx == names.len() {
return Some(it.id);
}
self.assert_subtype(b, a);
}
- pub fn ty_to_str(&self, a: ty::t) -> StrBuf {
+ pub fn ty_to_str(&self, a: ty::t) -> String {
ty_to_str(self.tcx, a)
}
use syntax::ast;
pub trait InferStr {
- fn inf_str(&self, cx: &InferCtxt) -> StrBuf;
+ fn inf_str(&self, cx: &InferCtxt) -> String;
}
impl InferStr for ty::t {
- fn inf_str(&self, cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, cx: &InferCtxt) -> String {
ty_to_str(cx.tcx, *self)
}
}
impl InferStr for FnSig {
- fn inf_str(&self, cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, cx: &InferCtxt) -> String {
format_strbuf!("({}) -> {}",
self.inputs
.iter()
.map(|a| a.inf_str(cx))
- .collect::<Vec<StrBuf>>().connect(", "),
+ .collect::<Vec<String>>().connect(", "),
self.output.inf_str(cx))
}
}
impl InferStr for ty::mt {
- fn inf_str(&self, cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, cx: &InferCtxt) -> String {
mt_to_str(cx.tcx, self)
}
}
impl InferStr for ty::Region {
- fn inf_str(&self, _cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, _cx: &InferCtxt) -> String {
format_strbuf!("{:?}", *self)
}
}
impl<V:InferStr> InferStr for Bound<V> {
- fn inf_str(&self, cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, cx: &InferCtxt) -> String {
match *self {
Some(ref v) => v.inf_str(cx),
None => "none".to_strbuf()
}
impl<T:InferStr> InferStr for Bounds<T> {
- fn inf_str(&self, cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, cx: &InferCtxt) -> String {
format_strbuf!("\\{{} <: {}\\}",
self.lb.inf_str(cx),
self.ub.inf_str(cx))
}
impl<V:Vid + ToStr,T:InferStr> InferStr for VarValue<V, T> {
- fn inf_str(&self, cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, cx: &InferCtxt) -> String {
match *self {
Redirect(ref vid) => format_strbuf!("Redirect({})", vid.to_str()),
Root(ref pt, rk) => {
}
impl InferStr for IntVarValue {
- fn inf_str(&self, _cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, _cx: &InferCtxt) -> String {
self.to_str().to_strbuf()
}
}
impl InferStr for ast::FloatTy {
- fn inf_str(&self, _cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, _cx: &InferCtxt) -> String {
self.to_str().to_strbuf()
}
}
impl InferStr for ty::TraitRef {
- fn inf_str(&self, cx: &InferCtxt) -> StrBuf {
+ fn inf_str(&self, cx: &InferCtxt) -> String {
trait_ref_to_str(cx.tcx, self)
}
}
}
impl Repr for vtable_origin {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
vtable_static(def_id, ref tys, ref vtable_res) => {
format_strbuf!("vtable_static({:?}:{}, {}, {})",
}
impl Repr for impl_res {
- fn repr(&self, tcx: &ty::ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ty::ctxt) -> String {
format_strbuf!("impl_res \\{trait_vtables={}, self_vtables={}\\}",
self.trait_vtables.repr(tcx),
self.self_vtables.repr(tcx))
span: Span,
t1: ty::t,
t2: ty::t,
- msg: || -> StrBuf)
+ msg: || -> String)
-> bool {
let result = match maybe_infcx {
None => {
use middle::typeck;
use std::rc::Rc;
-use std::strbuf::StrBuf;
+use std::string::String;
use syntax::abi;
use syntax::ast_map;
use syntax::codemap::{Span, Pos};
/// Produces a string suitable for debugging output.
pub trait Repr {
- fn repr(&self, tcx: &ctxt) -> StrBuf;
+ fn repr(&self, tcx: &ctxt) -> String;
}
/// Produces a string suitable for showing to the user.
pub trait UserString {
- fn user_string(&self, tcx: &ctxt) -> StrBuf;
+ fn user_string(&self, tcx: &ctxt) -> String;
}
pub fn note_and_explain_region(cx: &ctxt,
}
pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
- -> (StrBuf, Option<Span>) {
+ -> (String, Option<Span>) {
return match region {
ReScope(node_id) => {
match cx.map.find(node_id) {
};
fn explain_span(cx: &ctxt, heading: &str, span: Span)
- -> (StrBuf, Option<Span>) {
+ -> (String, Option<Span>) {
let lo = cx.sess.codemap().lookup_char_pos_adj(span.lo);
(format_strbuf!("the {} at {}:{}",
heading,
}
}
-pub fn bound_region_ptr_to_str(cx: &ctxt, br: BoundRegion) -> StrBuf {
+pub fn bound_region_ptr_to_str(cx: &ctxt, br: BoundRegion) -> String {
bound_region_to_str(cx, "", false, br)
}
pub fn bound_region_to_str(cx: &ctxt,
prefix: &str, space: bool,
- br: BoundRegion) -> StrBuf {
+ br: BoundRegion) -> String {
let space_str = if space { " " } else { "" };
if cx.sess.verbose() {
// In general, if you are giving a region error message,
// you should use `explain_region()` or, better yet,
// `note_and_explain_region()`
-pub fn region_ptr_to_str(cx: &ctxt, region: Region) -> StrBuf {
+pub fn region_ptr_to_str(cx: &ctxt, region: Region) -> String {
region_to_str(cx, "&", true, region)
}
-pub fn region_to_str(cx: &ctxt, prefix: &str, space: bool, region: Region) -> StrBuf {
+pub fn region_to_str(cx: &ctxt, prefix: &str, space: bool, region: Region) -> String {
let space_str = if space { " " } else { "" };
if cx.sess.verbose() {
}
}
-pub fn mutability_to_str(m: ast::Mutability) -> StrBuf {
+pub fn mutability_to_str(m: ast::Mutability) -> String {
match m {
ast::MutMutable => "mut ".to_strbuf(),
ast::MutImmutable => "".to_strbuf(),
}
}
-pub fn mt_to_str(cx: &ctxt, m: &mt) -> StrBuf {
+pub fn mt_to_str(cx: &ctxt, m: &mt) -> String {
format_strbuf!("{}{}", mutability_to_str(m.mutbl), ty_to_str(cx, m.ty))
}
-pub fn trait_store_to_str(cx: &ctxt, s: ty::TraitStore) -> StrBuf {
+pub fn trait_store_to_str(cx: &ctxt, s: ty::TraitStore) -> String {
match s {
ty::UniqTraitStore => "Box ".to_strbuf(),
ty::RegionTraitStore(r, m) => {
}
}
-pub fn vec_map_to_str<T>(ts: &[T], f: |t: &T| -> StrBuf) -> StrBuf {
- let tstrs = ts.iter().map(f).collect::<Vec<StrBuf>>();
+pub fn vec_map_to_str<T>(ts: &[T], f: |t: &T| -> String) -> String {
+ let tstrs = ts.iter().map(f).collect::<Vec<String>>();
format_strbuf!("[{}]", tstrs.connect(", "))
}
-pub fn fn_sig_to_str(cx: &ctxt, typ: &ty::FnSig) -> StrBuf {
+pub fn fn_sig_to_str(cx: &ctxt, typ: &ty::FnSig) -> String {
format_strbuf!("fn{}{} -> {}",
typ.binder_id,
typ.inputs.repr(cx),
typ.output.repr(cx))
}
-pub fn trait_ref_to_str(cx: &ctxt, trait_ref: &ty::TraitRef) -> StrBuf {
+pub fn trait_ref_to_str(cx: &ctxt, trait_ref: &ty::TraitRef) -> String {
trait_ref.user_string(cx).to_strbuf()
}
-pub fn ty_to_str(cx: &ctxt, typ: t) -> StrBuf {
- fn fn_input_to_str(cx: &ctxt, input: ty::t) -> StrBuf {
+pub fn ty_to_str(cx: &ctxt, typ: t) -> String {
+ fn fn_input_to_str(cx: &ctxt, input: ty::t) -> String {
ty_to_str(cx, input).to_strbuf()
}
fn bare_fn_to_str(cx: &ctxt,
abi: abi::Abi,
ident: Option<ast::Ident>,
sig: &ty::FnSig)
- -> StrBuf {
- let mut s = StrBuf::new();
+ -> String {
+ let mut s = String::new();
match fn_style {
ast::NormalFn => {}
_ => {
s
}
- fn closure_to_str(cx: &ctxt, cty: &ty::ClosureTy) -> StrBuf {
- let mut s = StrBuf::new();
+ fn closure_to_str(cx: &ctxt, cty: &ty::ClosureTy) -> String {
+ let mut s = String::new();
match cty.store {
ty::UniqTraitStore => {}
}
fn push_sig_to_str(cx: &ctxt,
- s: &mut StrBuf,
+ s: &mut String,
bra: char,
ket: char,
sig: &ty::FnSig) {
s.push_char(bra);
- let strs: Vec<StrBuf> = sig.inputs.iter().map(|a| fn_input_to_str(cx, *a)).collect();
+ let strs: Vec<String> = sig.inputs.iter().map(|a| fn_input_to_str(cx, *a)).collect();
s.push_str(strs.connect(", ").as_slice());
if sig.variadic {
s.push_str(", ...");
buf
}
ty_tup(ref elems) => {
- let strs: Vec<StrBuf> = elems.iter().map(|elem| ty_to_str(cx, *elem)).collect();
+ let strs: Vec<String> = elems.iter().map(|elem| ty_to_str(cx, *elem)).collect();
format_strbuf!("({})", strs.connect(","))
}
ty_closure(ref f) => {
tps: &[ty::t],
did: ast::DefId,
is_trait: bool)
- -> StrBuf {
+ -> String {
let mut strs = Vec::new();
match *regions {
ty::ErasedRegions => { }
}
}
-pub fn ty_to_short_str(cx: &ctxt, typ: t) -> StrBuf {
+pub fn ty_to_short_str(cx: &ctxt, typ: t) -> String {
let mut s = typ.repr(cx).to_strbuf();
if s.len() >= 32u {
s = s.as_slice().slice(0u, 32u).to_strbuf();
}
impl<T:Repr> Repr for Option<T> {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
match self {
&None => "None".to_strbuf(),
&Some(ref t) => t.repr(tcx),
}
impl<T:Repr,U:Repr> Repr for Result<T,U> {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
match self {
&Ok(ref t) => t.repr(tcx),
&Err(ref u) => format_strbuf!("Err({})", u.repr(tcx))
}
impl Repr for () {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
"()".to_strbuf()
}
}
impl<T:Repr> Repr for Rc<T> {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
(&**self).repr(tcx)
}
}
impl<T:Repr> Repr for @T {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
(&**self).repr(tcx)
}
}
impl<T:Repr> Repr for Box<T> {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
(&**self).repr(tcx)
}
}
-fn repr_vec<T:Repr>(tcx: &ctxt, v: &[T]) -> StrBuf {
+fn repr_vec<T:Repr>(tcx: &ctxt, v: &[T]) -> String {
vec_map_to_str(v, |t| t.repr(tcx))
}
impl<'a, T:Repr> Repr for &'a [T] {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
repr_vec(tcx, *self)
}
}
impl<T:Repr> Repr for OwnedSlice<T> {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
repr_vec(tcx, self.as_slice())
}
}
// This is necessary to handle types like Option<~[T]>, for which
// autoderef cannot convert the &[T] handler
impl<T:Repr> Repr for Vec<T> {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
repr_vec(tcx, self.as_slice())
}
}
impl Repr for ty::TypeParameterDef {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("TypeParameterDef({:?}, {})",
self.def_id,
self.bounds.repr(tcx))
}
impl Repr for ty::RegionParameterDef {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("RegionParameterDef({}, {:?})",
token::get_name(self.name),
self.def_id)
}
impl Repr for ty::t {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
ty_to_str(tcx, *self)
}
}
impl Repr for ty::substs {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("substs(regions={}, self_ty={}, tps={})",
self.regions.repr(tcx),
self.self_ty.repr(tcx),
}
impl Repr for ty::ItemSubsts {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("ItemSubsts({})", self.substs.repr(tcx))
}
}
impl Repr for ty::RegionSubsts {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
match *self {
ty::ErasedRegions => "erased".to_strbuf(),
ty::NonerasedRegions(ref regions) => regions.repr(tcx)
}
impl Repr for ty::ParamBounds {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
let mut res = Vec::new();
for b in self.builtin_bounds.iter() {
res.push(match b {
}
impl Repr for ty::TraitRef {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
trait_ref_to_str(tcx, self)
}
}
impl Repr for ast::Expr {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("expr({}: {})", self.id, pprust::expr_to_str(self))
}
}
impl Repr for ast::Item {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("item({})", tcx.map.node_to_str(self.id))
}
}
impl Repr for ast::Stmt {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("stmt({}: {})",
ast_util::stmt_id(self),
pprust::stmt_to_str(self))
}
impl Repr for ast::Pat {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("pat({}: {})", self.id, pprust::pat_to_str(self))
}
}
impl Repr for ty::BoundRegion {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
match *self {
ty::BrAnon(id) => format_strbuf!("BrAnon({})", id),
ty::BrNamed(id, name) => {
}
impl Repr for ty::Region {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
match *self {
ty::ReEarlyBound(id, index, name) => {
format_strbuf!("ReEarlyBound({}, {}, {})",
}
impl Repr for ast::DefId {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
// Unfortunately, there seems to be no way to attempt to print
// a path for a def-id, so I'll just make a best effort for now
// and otherwise fallback to just printing the crate/node pair
}
impl Repr for ty::ty_param_bounds_and_ty {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("ty_param_bounds_and_ty \\{generics: {}, ty: {}\\}",
self.generics.repr(tcx),
self.ty.repr(tcx))
}
impl Repr for ty::Generics {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("Generics(type_param_defs: {}, \
region_param_defs: {})",
self.type_param_defs().repr(tcx),
}
impl Repr for ty::ItemVariances {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("IterVariances(self_param={}, \
type_params={}, \
region_params={})",
}
impl Repr for ty::Variance {
- fn repr(&self, _: &ctxt) -> StrBuf {
+ fn repr(&self, _: &ctxt) -> String {
self.to_str().to_strbuf()
}
}
impl Repr for ty::Method {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("method(ident: {}, generics: {}, fty: {}, \
explicit_self: {}, vis: {}, def_id: {})",
self.ident.repr(tcx),
}
impl Repr for ast::Name {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
token::get_name(*self).get().to_strbuf()
}
}
impl Repr for ast::Ident {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
token::get_ident(*self).get().to_strbuf()
}
}
impl Repr for ast::ExplicitSelf_ {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("{:?}", *self)
}
}
impl Repr for ast::Visibility {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("{:?}", *self)
}
}
impl Repr for ty::BareFnTy {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("BareFnTy \\{fn_style: {:?}, abi: {}, sig: {}\\}",
self.fn_style,
self.abi.to_str(),
}
impl Repr for ty::FnSig {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
fn_sig_to_str(tcx, self)
}
}
impl Repr for typeck::MethodCallee {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("MethodCallee \\{origin: {}, ty: {}, {}\\}",
self.origin.repr(tcx),
self.ty.repr(tcx),
}
impl Repr for typeck::MethodOrigin {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
match self {
&typeck::MethodStatic(def_id) => {
format_strbuf!("MethodStatic({})", def_id.repr(tcx))
}
impl Repr for typeck::MethodParam {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("MethodParam({},{:?},{:?},{:?})",
self.trait_id.repr(tcx),
self.method_num,
}
impl Repr for typeck::MethodObject {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("MethodObject({},{:?},{:?})",
self.trait_id.repr(tcx),
self.method_num,
impl Repr for ty::RegionVid {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("{:?}", *self)
}
}
impl Repr for ty::TraitStore {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
trait_store_to_str(tcx, *self)
}
}
impl Repr for ty::BuiltinBound {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("{:?}", *self)
}
}
impl UserString for ty::BuiltinBound {
- fn user_string(&self, _tcx: &ctxt) -> StrBuf {
+ fn user_string(&self, _tcx: &ctxt) -> String {
match *self {
ty::BoundStatic => "'static".to_strbuf(),
ty::BoundSend => "Send".to_strbuf(),
}
impl Repr for ty::BuiltinBounds {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
self.user_string(tcx)
}
}
impl Repr for Span {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
tcx.sess.codemap().span_to_str(*self).to_strbuf()
}
}
impl<A:UserString> UserString for Rc<A> {
- fn user_string(&self, tcx: &ctxt) -> StrBuf {
+ fn user_string(&self, tcx: &ctxt) -> String {
let this: &A = &**self;
this.user_string(tcx)
}
}
impl UserString for ty::BuiltinBounds {
- fn user_string(&self, tcx: &ctxt) -> StrBuf {
+ fn user_string(&self, tcx: &ctxt) -> String {
self.iter()
.map(|bb| bb.user_string(tcx))
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.connect("+")
.to_strbuf()
}
}
impl UserString for ty::TraitRef {
- fn user_string(&self, tcx: &ctxt) -> StrBuf {
+ fn user_string(&self, tcx: &ctxt) -> String {
let base = ty::item_path_str(tcx, self.def_id);
if tcx.sess.verbose() && self.substs.self_ty.is_some() {
let mut all_tps = self.substs.tps.clone();
}
impl UserString for ty::t {
- fn user_string(&self, tcx: &ctxt) -> StrBuf {
+ fn user_string(&self, tcx: &ctxt) -> String {
ty_to_str(tcx, *self)
}
}
impl UserString for ast::Ident {
- fn user_string(&self, _tcx: &ctxt) -> StrBuf {
+ fn user_string(&self, _tcx: &ctxt) -> String {
token::get_name(self.name).get().to_strbuf()
}
}
impl Repr for abi::Abi {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
self.to_str().to_strbuf()
}
}
impl UserString for abi::Abi {
- fn user_string(&self, _tcx: &ctxt) -> StrBuf {
+ fn user_string(&self, _tcx: &ctxt) -> String {
self.to_str().to_strbuf()
}
}
impl Repr for ty::UpvarId {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("UpvarId({};`{}`;{})",
self.var_id,
ty::local_var_name_str(tcx, self.var_id),
}
impl Repr for ast::Mutability {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("{:?}", *self)
}
}
impl Repr for ty::BorrowKind {
- fn repr(&self, _tcx: &ctxt) -> StrBuf {
+ fn repr(&self, _tcx: &ctxt) -> String {
format_strbuf!("{:?}", *self)
}
}
impl Repr for ty::UpvarBorrow {
- fn repr(&self, tcx: &ctxt) -> StrBuf {
+ fn repr(&self, tcx: &ctxt) -> String {
format_strbuf!("UpvarBorrow({}, {})",
self.kind.repr(tcx),
self.region.repr(tcx))
}
/// Convenience function that retrieves the result of a digest as a
- /// StrBuf in hexadecimal format.
- fn result_str(&mut self) -> StrBuf {
+ /// String in hexadecimal format.
+ fn result_str(&mut self) -> String {
self.result_bytes().as_slice().to_hex().to_strbuf()
}
}
}
struct Test {
- input: StrBuf,
- output_str: StrBuf,
+ input: String,
+ output_str: String,
}
fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
use rustc::metadata::decoder;
use rustc::middle::ty;
-use std::strbuf::StrBuf;
+use std::string::String;
use core;
use doctree;
#[deriving(Clone, Encodable, Decodable)]
pub struct Crate {
- pub name: StrBuf,
+ pub name: String,
pub module: Option<Item>,
pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
}
#[deriving(Clone, Encodable, Decodable)]
pub struct ExternalCrate {
- pub name: StrBuf,
+ pub name: String,
pub attrs: Vec<Attribute>,
}
/// Stringified span
pub source: Span,
/// Not everything has a name. E.g., impls
- pub name: Option<StrBuf>,
+ pub name: Option<String>,
pub attrs: Vec<Attribute> ,
pub inner: ItemEnum,
pub visibility: Option<Visibility>,
#[deriving(Clone, Encodable, Decodable)]
pub enum Attribute {
- Word(StrBuf),
- List(StrBuf, Vec<Attribute> ),
- NameValue(StrBuf, StrBuf)
+ Word(String),
+ List(String, Vec<Attribute> ),
+ NameValue(String, String)
}
impl Clean<Attribute> for ast::MetaItem {
#[deriving(Clone, Encodable, Decodable)]
pub struct TyParam {
- pub name: StrBuf,
+ pub name: String,
pub did: ast::DefId,
pub bounds: Vec<TyParamBound>,
}
};
let fqn = csearch::get_item_path(tcx, self.def_id);
let fqn = fqn.move_iter().map(|i| i.to_str().to_strbuf())
- .collect::<Vec<StrBuf>>();
+ .collect::<Vec<String>>();
let path = external_path(fqn.last().unwrap().as_slice());
cx.external_paths.borrow_mut().get_mut_ref().insert(self.def_id,
(fqn, TypeTrait));
}
#[deriving(Clone, Encodable, Decodable)]
-pub struct Lifetime(StrBuf);
+pub struct Lifetime(String);
impl Lifetime {
pub fn get_ref<'a>(&'a self) -> &'a str {
#[deriving(Clone, Encodable, Decodable)]
pub struct Argument {
pub type_: Type,
- pub name: StrBuf,
+ pub name: String,
pub id: ast::NodeId,
}
BareFunction(Box<BareFunctionDecl>),
Tuple(Vec<Type>),
Vector(Box<Type>),
- FixedVector(Box<Type>, StrBuf),
+ FixedVector(Box<Type>, String),
String,
Bool,
/// aka TyNil
core::NotTyped(_) => fail!(),
};
let fqn = csearch::get_item_path(tcx, did);
- let fqn: Vec<StrBuf> = fqn.move_iter().map(|i| {
+ let fqn: Vec<String> = fqn.move_iter().map(|i| {
i.to_str().to_strbuf()
}).collect();
let mut path = external_path(fqn.last()
#[deriving(Clone, Encodable, Decodable)]
pub struct Span {
- pub filename: StrBuf,
+ pub filename: String,
pub loline: uint,
pub locol: uint,
pub hiline: uint,
#[deriving(Clone, Encodable, Decodable)]
pub struct PathSegment {
- pub name: StrBuf,
+ pub name: String,
pub lifetimes: Vec<Lifetime>,
pub types: Vec<Type>,
}
}
}
-fn path_to_str(p: &ast::Path) -> StrBuf {
+fn path_to_str(p: &ast::Path) -> String {
use syntax::parse::token;
- let mut s = StrBuf::new();
+ let mut s = String::new();
let mut first = true;
for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
if !first || p.global {
s
}
-impl Clean<StrBuf> for ast::Ident {
- fn clean(&self) -> StrBuf {
+impl Clean<String> for ast::Ident {
+ fn clean(&self) -> String {
token::get_ident(*self).get().to_strbuf()
}
}
pub fn_style: ast::FnStyle,
pub generics: Generics,
pub decl: FnDecl,
- pub abi: StrBuf,
+ pub abi: String,
}
impl Clean<BareFunctionDecl> for ast::BareFnTy {
/// It's useful to have the value of a static documented, but I have no
/// desire to represent expressions (that'd basically be all of the AST,
/// which is huge!). So, have a string.
- pub expr: StrBuf,
+ pub expr: String,
}
impl Clean<Item> for doctree::Static {
#[deriving(Clone, Encodable, Decodable)]
pub enum ViewItemInner {
- ExternCrate(StrBuf, Option<StrBuf>, ast::NodeId),
+ ExternCrate(String, Option<String>, ast::NodeId),
Import(ViewPath)
}
#[deriving(Clone, Encodable, Decodable)]
pub enum ViewPath {
// use str = source;
- SimpleImport(StrBuf, ImportSource),
+ SimpleImport(String, ImportSource),
// use source::*;
GlobImport(ImportSource),
// use source::{a, b, c};
#[deriving(Clone, Encodable, Decodable)]
pub struct ViewListIdent {
- pub name: StrBuf,
+ pub name: String,
pub source: Option<ast::DefId>,
}
// Utilities
trait ToSource {
- fn to_src(&self) -> StrBuf;
+ fn to_src(&self) -> String;
}
impl ToSource for syntax::codemap::Span {
- fn to_src(&self) -> StrBuf {
+ fn to_src(&self) -> String {
debug!("converting span {:?} to snippet", self.clean());
let ctxt = super::ctxtkey.get().unwrap();
let cm = ctxt.sess().codemap().clone();
}
}
-fn lit_to_str(lit: &ast::Lit) -> StrBuf {
+fn lit_to_str(lit: &ast::Lit) -> String {
match lit.node {
ast::LitStr(ref st, _) => st.get().to_strbuf(),
ast::LitBinary(ref data) => format_strbuf!("{:?}", data.as_slice()),
}
}
-fn name_from_pat(p: &ast::Pat) -> StrBuf {
+fn name_from_pat(p: &ast::Pat) -> String {
use syntax::ast::*;
debug!("Trying to get a name from pattern: {:?}", p);
#[deriving(Clone, Encodable, Decodable)]
pub struct Macro {
- pub source: StrBuf,
+ pub source: String,
}
impl Clean<Item> for doctree::Macro {
}
pub type ExternalPaths = RefCell<Option<HashMap<ast::DefId,
- (Vec<StrBuf>, clean::TypeKind)>>>;
+ (Vec<String>, clean::TypeKind)>>>;
pub struct DocContext {
pub krate: ast::Crate,
pub src: Path,
pub external_paths: ExternalPaths,
pub external_traits: RefCell<Option<HashMap<ast::DefId, clean::Trait>>>,
- pub external_typarams: RefCell<Option<HashMap<ast::DefId, StrBuf>>>,
+ pub external_typarams: RefCell<Option<HashMap<ast::DefId, String>>>,
}
impl DocContext {
pub public_items: privacy::PublicItems,
pub external_paths: ExternalPaths,
pub external_traits: RefCell<Option<HashMap<ast::DefId, clean::Trait>>>,
- pub external_typarams: RefCell<Option<HashMap<ast::DefId, StrBuf>>>,
+ pub external_typarams: RefCell<Option<HashMap<ast::DefId, String>>>,
}
/// Parses, resolves, and typechecks the given crate
-fn get_ast_and_resolve(cpath: &Path, libs: HashSet<Path>, cfgs: Vec<StrBuf>)
+fn get_ast_and_resolve(cpath: &Path, libs: HashSet<Path>, cfgs: Vec<String>)
-> (DocContext, CrateAnalysis) {
use syntax::codemap::dummy_spanned;
use rustc::driver::driver::{FileInput,
})
}
-pub fn run_core(libs: HashSet<Path>, cfgs: Vec<StrBuf>, path: &Path)
+pub fn run_core(libs: HashSet<Path>, cfgs: Vec<String>, path: &Path)
-> (clean::Crate, CrateAnalysis) {
let (ctxt, analysis) = get_ast_and_resolve(path, libs, cfgs);
let ctxt = @ctxt;
//! them in the future to instead emit any format desired.
use std::fmt;
-use std::strbuf::StrBuf;
+use std::string::String;
use syntax::ast;
use syntax::ast_util;
}
fn path(w: &mut fmt::Formatter, path: &clean::Path, print_all: bool,
- root: |&render::Cache, &[StrBuf]| -> Option<StrBuf>,
- info: |&render::Cache| -> Option<(Vec<StrBuf> , ItemType)>)
+ root: |&render::Cache, &[String]| -> Option<String>,
+ info: |&render::Cache| -> Option<(Vec<String> , ItemType)>)
-> fmt::Result
{
// The generics will get written to both the title and link
- let mut generics = StrBuf::new();
+ let mut generics = String::new();
let last = path.segments.last().unwrap();
if last.lifetimes.len() > 0 || last.types.len() > 0 {
let mut counter = 0;
let amt = path.segments.len() - 1;
match rel_root {
Some(root) => {
- let mut root = StrBuf::from_str(root.as_slice());
+ let mut root = String::from_str(root.as_slice());
for seg in path.segments.slice_to(amt).iter() {
if "super" == seg.name.as_slice() ||
"self" == seg.name.as_slice() {
match info(&**cache) {
// This is a documented path, link to it!
Some((ref fqp, shortty)) if abs_root.is_some() => {
- let mut url = StrBuf::from_str(abs_root.unwrap().as_slice());
+ let mut url = String::from_str(abs_root.unwrap().as_slice());
let to_link = fqp.slice_to(fqp.len() - 1);
for component in to_link.iter() {
url.push_str(component.as_slice());
},
ret = decl.decl.output,
bounds = {
- let mut ret = StrBuf::new();
+ let mut ret = String::new();
match *region {
Some(ref lt) => {
ret.push_str(format!(": {}",
.map(|s| s.to_str().to_strbuf());
format_strbuf!(
": {}",
- m.collect::<Vec<StrBuf>>().connect(" + "))
+ m.collect::<Vec<String>>().connect(" + "))
},
arrow = match decl.decl.output { clean::Unit => "no", _ => "yes" },
ret = decl.decl.output)
impl<'a> fmt::Show for Method<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Method(selfty, d) = *self;
- let mut args = StrBuf::new();
+ let mut args = String::new();
match *selfty {
clean::SelfStatic => {},
clean::SelfValue => args.push_str("self"),
use t = syntax::parse::token;
/// Highlights some source code, returning the HTML output.
-pub fn highlight(src: &str, class: Option<&str>) -> StrBuf {
+pub fn highlight(src: &str, class: Option<&str>) -> String {
debug!("highlighting: ================\n{}\n==============", src);
let sess = parse::new_parse_sess();
let fm = parse::string_to_filemap(&sess,
#[deriving(Clone)]
pub struct Layout {
- pub logo: StrBuf,
- pub favicon: StrBuf,
- pub krate: StrBuf,
+ pub logo: String,
+ pub favicon: String,
+ pub krate: String,
}
pub struct Page<'a> {
}
}
-local_data_key!(used_header_map: RefCell<HashMap<StrBuf, uint>>)
+local_data_key!(used_header_map: RefCell<HashMap<String, uint>>)
pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
extern fn block(ob: *mut hoedown_buffer, text: *hoedown_buffer,
Some(s) => s.to_lower().into_str().to_strbuf(),
None => s.to_strbuf()
}
- }).collect::<Vec<StrBuf>>().connect("-")).to_strbuf();
+ }).collect::<Vec<String>>().connect("-")).to_strbuf();
// This is a terrible hack working around how hoedown gives us rendered
// html for text rather than the raw text.
use std::io::{fs, File, BufferedWriter, MemWriter, BufferedReader};
use std::io;
use std::str;
-use std::strbuf::StrBuf;
+use std::string::String;
use sync::Arc;
use serialize::json::ToJson;
pub struct Context {
/// Current hierarchy of components leading down to what's currently being
/// rendered
- pub current: Vec<StrBuf> ,
+ pub current: Vec<String> ,
/// String representation of how to get back to the root path of the 'doc/'
/// folder in terms of a relative URL.
- pub root_path: StrBuf,
+ pub root_path: String,
/// The current destination folder of where HTML artifacts should be placed.
/// This changes as the context descends into the module hierarchy.
pub dst: Path,
/// functions), and the value is the list of containers belonging to this
/// header. This map will change depending on the surrounding context of the
/// page.
- pub sidebar: HashMap<StrBuf, Vec<StrBuf>>,
+ pub sidebar: HashMap<String, Vec<String>>,
/// This flag indicates whether [src] links should be generated or not. If
/// the source files are present in the html rendering, then this will be
/// `true`.
/// Indicates where an external crate can be found.
pub enum ExternalLocation {
/// Remote URL root of the external crate
- Remote(StrBuf),
+ Remote(String),
/// This external crate can be found in the local doc/ folder
Local,
/// The external crate could not be found.
/// Mapping of typaram ids to the name of the type parameter. This is used
/// when pretty-printing a type (so pretty printing doesn't have to
/// painfully maintain a context like this)
- pub typarams: HashMap<ast::DefId, StrBuf>,
+ pub typarams: HashMap<ast::DefId, String>,
/// Maps a type id to all known implementations for that type. This is only
/// recognized for intra-crate `ResolvedPath` types, and is used to print
///
/// The values of the map are a list of implementations and documentation
/// found on that implementation.
- pub impls: HashMap<ast::NodeId, Vec<(clean::Impl, Option<StrBuf>)>>,
+ pub impls: HashMap<ast::NodeId, Vec<(clean::Impl, Option<String>)>>,
/// Maintains a mapping of local crate node ids to the fully qualified name
/// and "short type description" of that node. This is used when generating
/// URLs when a type is being linked to. External paths are not located in
/// this map because the `External` type itself has all the information
/// necessary.
- pub paths: HashMap<ast::DefId, (Vec<StrBuf>, ItemType)>,
+ pub paths: HashMap<ast::DefId, (Vec<String>, ItemType)>,
/// This map contains information about all known traits of this crate.
/// Implementations of a crate should inherit the documentation of the
// Private fields only used when initially crawling a crate to build a cache
- stack: Vec<StrBuf> ,
+ stack: Vec<String> ,
parent_stack: Vec<ast::NodeId> ,
search_index: Vec<IndexItem> ,
privmod: bool,
cx: &'a mut Context,
/// Processed source-file paths
- seen: HashSet<StrBuf>,
+ seen: HashSet<String>,
/// Root destination to place all HTML output into
dst: Path,
}
/// by hand to a large JS file at the end of cache-creation.
struct IndexItem {
ty: ItemType,
- name: StrBuf,
- path: StrBuf,
- desc: StrBuf,
+ name: String,
+ path: String,
+ desc: String,
parent: Option<ast::NodeId>,
}
// TLS keys used to carry information around during rendering.
local_data_key!(pub cache_key: Arc<Cache>)
-local_data_key!(pub current_location_key: Vec<StrBuf> )
+local_data_key!(pub current_location_key: Vec<String> )
/// Generates the documentation for `crate` into the directory `dst`
pub fn run(mut krate: clean::Crate, dst: Path) -> io::IoResult<()> {
let mut cx = Context {
dst: dst,
current: Vec::new(),
- root_path: StrBuf::new(),
+ root_path: String::new(),
sidebar: HashMap::new(),
layout: layout::Layout {
logo: "".to_strbuf(),
include_bin!("static/Heuristica-Bold.woff")));
fn collect(path: &Path, krate: &str,
- key: &str) -> io::IoResult<Vec<StrBuf>> {
+ key: &str) -> io::IoResult<Vec<String>> {
let mut ret = Vec::new();
if path.exists() {
for line in BufferedReader::new(File::open(path)).lines() {
// Create the intermediate directories
let mut cur = self.dst.clone();
- let mut root_path = StrBuf::from_str("../../");
+ let mut root_path = String::from_str("../../");
clean_srcpath(p.dirname(), |component| {
cur.push(component);
mkdir(&cur).unwrap();
impl Context {
/// Recurse in the directory structure and change the "root path" to make
/// sure it always points to the top (relatively)
- fn recurse<T>(&mut self, s: StrBuf, f: |&mut Context| -> T) -> T {
+ fn recurse<T>(&mut self, s: String, f: |&mut Context| -> T) -> T {
if s.len() == 0 {
fail!("what {:?}", self);
}
}
}
- fn link(&self) -> StrBuf {
+ fn link(&self) -> String {
let mut path = Vec::new();
clean_srcpath(self.item.source.filename.as_bytes(), |component| {
path.push(component.to_owned());
let cur = self.cx.current.as_slice();
let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
for (i, component) in cur.iter().enumerate().take(amt) {
- let mut trail = StrBuf::new();
+ let mut trail = String::new();
for _ in range(0, cur.len() - i - 1) {
trail.push_str("../");
}
}
}
-fn item_path(item: &clean::Item) -> StrBuf {
+fn item_path(item: &clean::Item) -> String {
match item.inner {
clean::ModuleItem(..) => {
format_strbuf!("{}/index.html", item.name.get_ref())
}
}
-fn full_path(cx: &Context, item: &clean::Item) -> StrBuf {
+fn full_path(cx: &Context, item: &clean::Item) -> String {
let mut s = cx.current.connect("::");
s.push_str("::");
s.push_str(item.name.get_ref().as_slice());
fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
t: &clean::Trait) -> fmt::Result {
- let mut parents = StrBuf::new();
+ let mut parents = String::new();
if t.parents.len() > 0 {
parents.push_str(": ");
for (i, p) in t.parents.iter().enumerate() {
let mut non_trait = v.iter().filter(|p| {
p.ref0().trait_.is_none()
});
- let non_trait = non_trait.collect::<Vec<&(clean::Impl, Option<StrBuf>)>>();
+ let non_trait = non_trait.collect::<Vec<&(clean::Impl, Option<String>)>>();
let mut traits = v.iter().filter(|p| {
p.ref0().trait_.is_some()
});
- let traits = traits.collect::<Vec<&(clean::Impl, Option<StrBuf>)>>();
+ let traits = traits.collect::<Vec<&(clean::Impl, Option<String>)>>();
if non_trait.len() > 0 {
try!(write!(w, "<h2 id='methods'>Methods</h2>"));
}
fn render_impl(w: &mut fmt::Formatter, i: &clean::Impl,
- dox: &Option<StrBuf>) -> fmt::Result {
+ dox: &Option<String>) -> fmt::Result {
try!(write!(w, "<h3 class='impl'><code>impl{} ", i.generics));
match i.trait_ {
Some(ref ty) => try!(write!(w, "{} for ", *ty)),
}
}
-fn build_sidebar(m: &clean::Module) -> HashMap<StrBuf, Vec<StrBuf>> {
+fn build_sidebar(m: &clean::Module) -> HashMap<String, Vec<String>> {
let mut map = HashMap::new();
for item in m.items.iter() {
let short = shortty(item).to_static_str();
nav.sub {
margin: 0 auto;
}
-}
\ No newline at end of file
+}
-/*! normalize.css v3.0.0 | MIT License | git.io/normalize */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:bold}table{border-collapse:collapse;border-spacing:0}td,th{padding:0}
\ No newline at end of file
+/*! normalize.css v3.0.0 | MIT License | git.io/normalize */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:bold}table{border-collapse:collapse;border-spacing:0}td,th{padding:0}
//! Table-of-contents creation.
use std::fmt;
-use std::strbuf::StrBuf;
+use std::string::String;
/// A (recursive) table of contents
#[deriving(Eq)]
#[deriving(Eq)]
pub struct TocEntry {
level: u32,
- sec_number: StrBuf,
- name: StrBuf,
- id: StrBuf,
+ sec_number: String,
+ name: String,
+ id: String,
children: Toc,
}
/// Push a level `level` heading into the appropriate place in the
/// heirarchy, returning a string containing the section number in
/// `<num>.<num>.<num>` format.
- pub fn push<'a>(&'a mut self, level: u32, name: StrBuf, id: StrBuf) -> &'a str {
+ pub fn push<'a>(&'a mut self, level: u32, name: String, id: String) -> &'a str {
assert!(level >= 1);
// collapse all previous sections into their parents until we
{
let (toc_level, toc) = match self.chain.last() {
None => {
- sec_number = StrBuf::new();
+ sec_number = String::new();
(0, &self.top_level)
}
Some(entry) => {
- sec_number = StrBuf::from_str(entry.sec_number
+ sec_number = String::from_str(entry.sec_number
.as_slice());
sec_number.push_str(".");
(entry.level, &entry.children)
opts().as_slice()));
}
-pub fn main_args(args: &[StrBuf]) -> int {
+pub fn main_args(args: &[String]) -> int {
let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
Ok(m) => m,
Err(err) => {
let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
let test_args = matches.opt_strs("test-args");
- let test_args: Vec<StrBuf> = test_args.iter()
+ let test_args: Vec<String> = test_args.iter()
.flat_map(|s| s.as_slice().words())
.map(|s| s.to_strbuf())
.collect();
/// Looks inside the command line arguments to extract the relevant input format
/// and files and then generates the necessary rustdoc output for formatting.
fn acquire_input(input: &str,
- matches: &getopts::Matches) -> Result<Output, StrBuf> {
+ matches: &getopts::Matches) -> Result<Output, String> {
match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
Some("rust") => Ok(rust_input(input, matches)),
Some("json") => json_input(input),
/// This input format purely deserializes the json output file. No passes are
/// run over the deserialized output.
-fn json_input(input: &str) -> Result<Output, StrBuf> {
+fn json_input(input: &str) -> Result<Output, String> {
let mut input = match File::open(&Path::new(input)) {
Ok(f) => f,
Err(e) => {
use collections::HashSet;
use std::{str, io};
-use std::strbuf::StrBuf;
+use std::string::String;
use getopts;
use testing;
use html::markdown::{MarkdownWithToc, find_testable_code, reset_headers};
use test::Collector;
-fn load_string(input: &Path) -> io::IoResult<Option<StrBuf>> {
+fn load_string(input: &Path) -> io::IoResult<Option<String>> {
let mut f = try!(io::File::open(input));
let d = try!(f.read_to_end());
Ok(str::from_utf8(d.as_slice()).map(|s| s.to_strbuf()))
(metadata, "")
}
-fn load_external_files(names: &[StrBuf]) -> Option<StrBuf> {
- let mut out = StrBuf::new();
+fn load_external_files(names: &[String]) -> Option<String> {
+ let mut out = String::new();
for name in names.iter() {
out.push_str(load_or_return!(name.as_slice(), None, None).as_slice());
out.push_char('\n');
output.push(input_p.filestem().unwrap());
output.set_extension("html");
- let mut css = StrBuf::new();
+ let mut css = String::new();
for name in matches.opt_strs("markdown-css").iter() {
let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
css.push_str(s.as_slice())
}
/// Run any tests/code examples in the markdown file `input`.
-pub fn test(input: &str, libs: HashSet<Path>, mut test_args: Vec<StrBuf>) -> int {
+pub fn test(input: &str, libs: HashSet<Path>, mut test_args: Vec<String>) -> int {
let input_str = load_or_return!(input, 1, 2);
let mut collector = Collector::new(input.to_strbuf(), libs, true, true);
use collections::HashSet;
use rustc::util::nodemap::NodeSet;
use std::cmp;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::uint;
use syntax::ast;
use syntax::ast_util;
struct Collapser;
impl fold::DocFolder for Collapser {
fn fold_item(&mut self, i: Item) -> Option<Item> {
- let mut docstr = StrBuf::new();
+ let mut docstr = String::new();
let mut i = i;
for attr in i.attrs.iter() {
match *attr {
(krate, None)
}
-pub fn unindent(s: &str) -> StrBuf {
+pub fn unindent(s: &str) -> String {
let lines = s.lines_any().collect::<Vec<&str> >();
let mut saw_first_line = false;
let mut saw_second_line = false;
use dl = std::unstable::dynamic_lib;
use serialize::json;
-use std::strbuf::StrBuf;
+use std::string::String;
-pub type PluginJson = Option<(StrBuf, json::Json)>;
+pub type PluginJson = Option<(String, json::Json)>;
pub type PluginResult = (clean::Crate, PluginJson);
pub type PluginCallback = fn (clean::Crate) -> PluginResult;
/// Turns `name` into the proper dynamic library filename for the given
/// platform. On windows, it turns into name.dll, on OS X, name.dylib, and
/// elsewhere, libname.so.
- pub fn load_plugin(&mut self, name: StrBuf) {
+ pub fn load_plugin(&mut self, name: String) {
let x = self.prefix.join(libname(name));
let lib_result = dl::DynamicLibrary::open(Some(&x));
let lib = lib_result.unwrap();
}
#[cfg(target_os="win32")]
-fn libname(mut n: StrBuf) -> StrBuf {
+fn libname(mut n: String) -> String {
n.push_str(".dll");
n
}
#[cfg(target_os="macos")]
-fn libname(mut n: StrBuf) -> StrBuf {
+fn libname(mut n: String) -> String {
n.push_str(".dylib");
n
}
#[cfg(not(target_os="win32"), not(target_os="macos"))]
-fn libname(n: StrBuf) -> StrBuf {
- let mut i = StrBuf::from_str("lib");
+fn libname(n: String) -> String {
+ let mut i = String::from_str("lib");
i.push_str(n.as_slice());
i.push_str(".so");
i
use std::io::{Command, TempDir};
use std::os;
use std::str;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::unstable::dynamic_lib::DynamicLibrary;
use collections::{HashSet, HashMap};
use visit_ast::RustdocVisitor;
pub fn run(input: &str,
- cfgs: Vec<StrBuf>,
+ cfgs: Vec<String>,
libs: HashSet<Path>,
- mut test_args: Vec<StrBuf>)
+ mut test_args: Vec<String>)
-> int {
let input_path = Path::new(input);
let input = driver::FileInput(input_path.clone());
// Remove the previous dylib search path var
let var = DynamicLibrary::envvar();
- let mut env: Vec<(StrBuf,StrBuf)> = os::env().move_iter().collect();
+ let mut env: Vec<(String,String)> = os::env().move_iter().collect();
match env.iter().position(|&(ref k, _)| k.as_slice() == var) {
Some(i) => { env.remove(i); }
None => {}
}
}
-fn maketest(s: &str, cratename: &str, loose_feature_gating: bool) -> StrBuf {
- let mut prog = StrBuf::from_str(r"
+fn maketest(s: &str, cratename: &str, loose_feature_gating: bool) -> String {
+ let mut prog = String::from_str(r"
#![deny(warnings)]
#![allow(unused_variable, dead_assignment, unused_mut, attribute_usage, dead_code)]
");
pub struct Collector {
pub tests: Vec<testing::TestDescAndFn>,
- names: Vec<StrBuf>,
+ names: Vec<String>,
libs: HashSet<Path>,
cnt: uint,
use_headers: bool,
- current_header: Option<StrBuf>,
- cratename: StrBuf,
+ current_header: Option<String>,
+ cratename: String,
loose_feature_gating: bool
}
impl Collector {
- pub fn new(cratename: StrBuf, libs: HashSet<Path>,
+ pub fn new(cratename: String, libs: HashSet<Path>,
use_headers: bool, loose_feature_gating: bool) -> Collector {
Collector {
tests: Vec::new(),
}
}
- pub fn add_test(&mut self, test: StrBuf, should_fail: bool, no_run: bool, should_ignore: bool) {
+ pub fn add_test(&mut self, test: String, should_fail: bool, no_run: bool, should_ignore: bool) {
let name = if self.use_headers {
let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
format_strbuf!("{}_{}", s, self.cnt)
} else {
'_'
}
- }).collect::<StrBuf>();
+ }).collect::<String>();
// new header => reset count.
self.cnt = 0;
pub struct UvError(c_int);
impl UvError {
- pub fn name(&self) -> StrBuf {
+ pub fn name(&self) -> String {
unsafe {
let inner = match self { &UvError(a) => a };
let name_str = uvll::uv_err_name(inner);
}
}
- pub fn desc(&self) -> StrBuf {
+ pub fn desc(&self) -> String {
unsafe {
let inner = match self { &UvError(a) => a };
let desc_str = uvll::uv_strerror(inner);
use std::fmt;
use std::fmt::Show;
use std::option::{Option, Some, None};
-use std::strbuf::StrBuf;
+use std::string::String;
/// An identifier in the pre-release or build metadata. If the identifier can
/// be parsed as a decimal value, it will be represented with `Numeric`.
#[allow(missing_doc)]
pub enum Identifier {
Numeric(uint),
- AlphaNumeric(StrBuf)
+ AlphaNumeric(String)
}
impl cmp::Ord for Identifier {
}
fn take_nonempty_prefix<T:Iterator<char>>(rdr: &mut T, pred: |char| -> bool)
- -> (StrBuf, Option<char>) {
- let mut buf = StrBuf::new();
+ -> (String, Option<char>) {
+ let mut buf = String::new();
let mut ch = rdr.next();
loop {
match ch {
pub trait ToBase64 {
/// Converts the value of `self` to a base64 value following the specified
/// format configuration, returning the owned string.
- fn to_base64(&self, config: Config) -> StrBuf;
+ fn to_base64(&self, config: Config) -> String;
}
impl<'a> ToBase64 for &'a [u8] {
* }
* ```
*/
- fn to_base64(&self, config: Config) -> StrBuf {
+ fn to_base64(&self, config: Config) -> String {
let bytes = match config.char_set {
Standard => STANDARD_CHARS,
UrlSafe => URLSAFE_CHARS
* Convert any base64 encoded string (literal, `@`, `&`, or `~`)
* to the byte values it encodes.
*
- * You can use the `StrBuf::from_utf8` function in `std::strbuf` to turn a
+ * You can use the `String::from_utf8` function in `std::string` to turn a
* `Vec<u8>` into a string with characters corresponding to those values.
*
* # Example
* println!("base64 output: {}", hello_str);
* let res = hello_str.as_slice().from_base64();
* if res.is_ok() {
- * let opt_bytes = StrBuf::from_utf8(res.unwrap());
+ * let opt_bytes = String::from_utf8(res.unwrap());
* if opt_bytes.is_ok() {
* println!("decoded from base64: {}", opt_bytes.unwrap());
* }
str::from_utf8(self.data.slice(self.start, self.end)).unwrap()
}
- pub fn as_str(&self) -> StrBuf {
+ pub fn as_str(&self) -> String {
self.as_str_slice().to_strbuf()
}
}
#[deriving(Show)]
pub enum Error {
IntTooBig(uint),
- Expected(StrBuf),
+ Expected(String),
IoError(io::IoError)
}
// --------------------------------------
fn read_char(&mut self) -> DecodeResult<char> {
Ok(char::from_u32(doc_as_u32(try!(self.next_doc(EsChar)))).unwrap())
}
- fn read_str(&mut self) -> DecodeResult<StrBuf> {
+ fn read_str(&mut self) -> DecodeResult<String> {
Ok(try!(self.next_doc(EsStr)).as_str())
}
pub trait ToHex {
/// Converts the value of `self` to a hex value, returning the owned
/// string.
- fn to_hex(&self) -> StrBuf;
+ fn to_hex(&self) -> String;
}
static CHARS: &'static[u8] = bytes!("0123456789abcdef");
* }
* ```
*/
- fn to_hex(&self) -> StrBuf {
+ fn to_hex(&self) -> String {
let mut v = Vec::with_capacity(self.len() * 2);
for &byte in self.iter() {
v.push(CHARS[(byte >> 4) as uint]);
* Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`)
* to the byte values it encodes.
*
- * You can use the `StrBuf::from_utf8` function in `std::strbuf` to turn a
+ * You can use the `String::from_utf8` function in `std::string` to turn a
* `Vec<u8>` into a string with characters corresponding to those values.
*
* # Example
* println!("{}", hello_str);
* let bytes = hello_str.as_slice().from_hex().unwrap();
* println!("{:?}", bytes);
- * let result_str = StrBuf::from_utf8(bytes).unwrap();
+ * let result_str = String::from_utf8(bytes).unwrap();
* println!("{}", result_str);
* }
* ```
#[deriving(Encodable)]
pub struct TestStruct {
- data_str: StrBuf,
+ data_str: String,
}
fn main() {
```
Two wrapper functions are provided to encode a Encodable object
-into a string (StrBuf) or buffer (~[u8]): `str_encode(&m)` and `buffer_encode(&m)`.
+into a string (String) or buffer (~[u8]): `str_encode(&m)` and `buffer_encode(&m)`.
```rust
use serialize::json;
let to_encode_object = "example of string to encode".to_strbuf();
-let encoded_str: StrBuf = json::Encoder::str_encode(&to_encode_object);
+let encoded_str: String = json::Encoder::str_encode(&to_encode_object);
```
JSON API provide an enum `json::Json` and a trait `ToJson` to encode object.
pub struct MyStruct {
attr1: u8,
- attr2: StrBuf,
+ attr2: String,
}
impl ToJson for MyStruct {
fn main() {
let test2: MyStruct = MyStruct {attr1: 1, attr2:"test".to_strbuf()};
let tjson: json::Json = test2.to_json();
- let json_str: StrBuf = tjson.to_str().into_strbuf();
+ let json_str: String = tjson.to_str().into_strbuf();
}
```
#[deriving(Decodable)]
pub struct MyStruct {
attr1: u8,
- attr2: StrBuf,
+ attr2: String,
}
fn main() {
- let json_str_to_decode: StrBuf =
+ let json_str_to_decode: String =
"{\"attr1\":1,\"attr2\":\"toto\"}".to_strbuf();
let json_object = json::from_str(json_str_to_decode.as_slice());
let mut decoder = json::Decoder::new(json_object.unwrap());
#[deriving(Decodable, Encodable)] //generate Decodable, Encodable impl.
pub struct TestStruct1 {
data_int: u8,
- data_str: StrBuf,
+ data_str: String,
data_vector: Vec<u8>,
}
fn main() {
let to_encode_object = TestStruct1
{data_int: 1, data_str:"toto".to_strbuf(), data_vector:vec![2,3,4,5]};
- let encoded_str: StrBuf = json::Encoder::str_encode(&to_encode_object);
+ let encoded_str: String = json::Encoder::str_encode(&to_encode_object);
// To deserialize use the `json::from_str` and `json::Decoder`
#[deriving(Decodable, Encodable)] // generate Decodable, Encodable impl.
pub struct TestStruct1 {
data_int: u8,
- data_str: StrBuf,
+ data_str: String,
data_vector: Vec<u8>,
}
let test2: TestStruct1 = TestStruct1 {data_int: 1, data_str:"toto".to_strbuf(),
data_vector:vec![2,3,4,5]};
let tjson: json::Json = test2.to_json();
- let json_str: StrBuf = tjson.to_str().into_strbuf();
+ let json_str: String = tjson.to_str().into_strbuf();
// Deserialize like before.
use std::num;
use std::str::ScalarValue;
use std::str;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::vec::Vec;
use Encodable;
#[deriving(Clone, Eq)]
pub enum Json {
Number(f64),
- String(StrBuf),
+ String(String),
Boolean(bool),
List(List),
Object(Box<Object>),
}
pub type List = Vec<Json>;
-pub type Object = TreeMap<StrBuf, Json>;
+pub type Object = TreeMap<String, Json>;
/// The errors that can arise while parsing a JSON stream.
#[deriving(Clone, Eq)]
#[deriving(Clone, Eq, Show)]
pub enum DecoderError {
ParseError(ParserError),
- ExpectedError(StrBuf, StrBuf),
- MissingFieldError(StrBuf),
- UnknownVariantError(StrBuf),
+ ExpectedError(String, String),
+ MissingFieldError(String),
+ UnknownVariantError(String),
}
/// Returns a readable error string for a given error code.
pub type EncodeResult = io::IoResult<()>;
pub type DecodeResult<T> = Result<T, DecoderError>;
-fn escape_str(s: &str) -> StrBuf {
- let mut escaped = StrBuf::from_str("\"");
+fn escape_str(s: &str) -> String {
+ let mut escaped = String::from_str("\"");
for c in s.chars() {
match c {
'"' => escaped.push_str("\\\""),
escaped
}
-fn spaces(n: uint) -> StrBuf {
- let mut ss = StrBuf::new();
+fn spaces(n: uint) -> String {
+ let mut ss = String::new();
for _ in range(0, n) {
ss.push_str(" ");
}
pub fn str_encode<T:Encodable<Encoder<'a>,
io::IoError>>(
to_encode_object: &T)
- -> StrBuf {
+ -> String {
let buff = Encoder::buffer_encode(to_encode_object);
str::from_utf8(buff.as_slice()).unwrap().to_strbuf()
}
}
/// Encodes a json value into a string
- pub fn to_pretty_str(&self) -> StrBuf {
+ pub fn to_pretty_str(&self) -> String {
let mut s = MemWriter::new();
self.to_pretty_writer(&mut s as &mut io::Writer).unwrap();
str::from_utf8(s.unwrap().as_slice()).unwrap().to_strbuf()
/// If the Json value is an Object, returns the value associated with the provided key.
/// Otherwise, returns None.
- pub fn find<'a>(&'a self, key: &StrBuf) -> Option<&'a Json>{
+ pub fn find<'a>(&'a self, key: &String) -> Option<&'a Json>{
match self {
&Object(ref map) => map.find(key),
_ => None
/// Attempts to get a nested Json Object for each key in `keys`.
/// If any key is found not to exist, find_path will return None.
/// Otherwise, it will return the Json value associated with the final key.
- pub fn find_path<'a>(&'a self, keys: &[&StrBuf]) -> Option<&'a Json>{
+ pub fn find_path<'a>(&'a self, keys: &[&String]) -> Option<&'a Json>{
let mut target = self;
for key in keys.iter() {
match target.find(*key) {
/// If the Json value is an Object, performs a depth-first search until
/// a value associated with the provided key is found. If no value is found
/// or the Json value is not an Object, returns None.
- pub fn search<'a>(&'a self, key: &StrBuf) -> Option<&'a Json> {
+ pub fn search<'a>(&'a self, key: &String) -> Option<&'a Json> {
match self {
&Object(ref map) => {
match map.find(key) {
ListEnd,
BooleanValue(bool),
NumberValue(f64),
- StringValue(StrBuf),
+ StringValue(String),
NullValue,
Error(ParserError),
}
}
// Used by Parser to insert Key elements at the top of the stack.
- fn push_key(&mut self, key: StrBuf) {
+ fn push_key(&mut self, key: String) {
self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
for c in key.as_bytes().iter() {
self.str_buffer.push(*c);
Ok(n)
}
- fn parse_str(&mut self) -> Result<StrBuf, ParserError> {
+ fn parse_str(&mut self) -> Result<String, ParserError> {
let mut escape = false;
- let mut res = StrBuf::new();
+ let mut res = String::new();
loop {
self.bump();
Some(NumberValue(n)) => { Ok(Number(n)) }
Some(BooleanValue(b)) => { Ok(Boolean(b)) }
Some(StringValue(ref mut s)) => {
- let mut temp = StrBuf::new();
+ let mut temp = String::new();
swap(s, &mut temp);
Ok(String(temp))
}
format_strbuf!("{}", s)))
}
- fn read_str(&mut self) -> DecodeResult<StrBuf> {
+ fn read_str(&mut self) -> DecodeResult<String> {
debug!("read_str");
Ok(try!(expect!(self.pop(), String)))
}
fn to_json(&self) -> Json { Boolean(*self) }
}
-impl ToJson for StrBuf {
+impl ToJson for String {
fn to_json(&self) -> Json { String((*self).clone()) }
}
fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) }
}
-impl<A:ToJson> ToJson for TreeMap<StrBuf, A> {
+impl<A:ToJson> ToJson for TreeMap<String, A> {
fn to_json(&self) -> Json {
let mut d = TreeMap::new();
for (key, value) in self.iter() {
}
}
-impl<A:ToJson> ToJson for HashMap<StrBuf, A> {
+impl<A:ToJson> ToJson for HashMap<String, A> {
fn to_json(&self) -> Json {
let mut d = TreeMap::new();
for (key, value) in self.iter() {
#[deriving(Eq, Encodable, Decodable, Show)]
enum Animal {
Dog,
- Frog(StrBuf, int)
+ Frog(String, int)
}
#[deriving(Eq, Encodable, Decodable, Show)]
struct Inner {
a: (),
b: uint,
- c: Vec<StrBuf>,
+ c: Vec<String>,
}
#[deriving(Eq, Encodable, Decodable, Show)]
inner: Vec<Inner>,
}
- fn mk_object(items: &[(StrBuf, Json)]) -> Json {
+ fn mk_object(items: &[(String, Json)]) -> Json {
let mut d = box TreeMap::new();
for item in items.iter() {
from_str(a.to_pretty_str().as_slice()).unwrap());
}
- fn with_str_writer(f: |&mut io::Writer|) -> StrBuf {
+ fn with_str_writer(f: |&mut io::Writer|) -> String {
use std::io::MemWriter;
use std::str;
#[test]
fn test_write_none() {
- let value: Option<StrBuf> = None;
+ let value: Option<String> = None;
let s = with_str_writer(|wr| {
let mut encoder = Encoder::new(wr);
value.encode(&mut encoder).unwrap();
for &(i, o) in s.iter() {
let mut decoder = Decoder::new(from_str(i).unwrap());
- let v: StrBuf = Decodable::decode(&mut decoder).unwrap();
+ let v: String = Decodable::decode(&mut decoder).unwrap();
assert_eq!(v.as_slice(), o);
let mut decoder = Decoder::new(from_str(i).unwrap());
- let v: StrBuf = Decodable::decode(&mut decoder).unwrap();
+ let v: String = Decodable::decode(&mut decoder).unwrap();
assert_eq!(v, o.to_strbuf());
}
}
#[test]
fn test_decode_option() {
let mut decoder = Decoder::new(from_str("null").unwrap());
- let value: Option<StrBuf> = Decodable::decode(&mut decoder).unwrap();
+ let value: Option<String> = Decodable::decode(&mut decoder).unwrap();
assert_eq!(value, None);
let mut decoder = Decoder::new(from_str("\"jodhpurs\"").unwrap());
- let value: Option<StrBuf> = Decodable::decode(&mut decoder).unwrap();
+ let value: Option<String> = Decodable::decode(&mut decoder).unwrap();
assert_eq!(value, Some("jodhpurs".to_strbuf()));
}
let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
\"fields\":[\"Henry\", 349]}}";
let mut decoder = Decoder::new(from_str(s).unwrap());
- let mut map: TreeMap<StrBuf, Animal> = Decodable::decode(&mut decoder).unwrap();
+ let mut map: TreeMap<String, Animal> = Decodable::decode(&mut decoder).unwrap();
assert_eq!(map.pop(&"a".to_strbuf()), Some(Dog));
assert_eq!(map.pop(&"b".to_strbuf()), Some(Frog("Henry".to_strbuf(), 349)));
struct DecodeStruct {
x: f64,
y: bool,
- z: StrBuf,
+ z: String,
w: Vec<DecodeStruct>
}
#[deriving(Decodable)]
enum DecodeEnum {
A(f64),
- B(StrBuf)
+ B(String)
}
fn check_err<T: Decodable<Decoder, DecoderError>>(to_parse: &'static str,
expected: DecoderError) {
});
}
- fn big_json() -> StrBuf {
+ fn big_json() -> String {
let mut src = "[\n".to_strbuf();
for _ in range(0, 500) {
src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \
fn read_f64(&mut self) -> Result<f64, E>;
fn read_f32(&mut self) -> Result<f32, E>;
fn read_char(&mut self) -> Result<char, E>;
- fn read_str(&mut self) -> Result<StrBuf, E>;
+ fn read_str(&mut self) -> Result<String, E>;
// Compound types:
fn read_enum<T>(&mut self, name: &str, f: |&mut Self| -> Result<T, E>) -> Result<T, E>;
}
}
-impl<E, S:Encoder<E>> Encodable<S, E> for StrBuf {
+impl<E, S:Encoder<E>> Encodable<S, E> for String {
fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_str(self.as_slice())
}
}
-impl<E, D:Decoder<E>> Decodable<D, E> for StrBuf {
- fn decode(d: &mut D) -> Result<StrBuf, E> {
- Ok(StrBuf::from_str(try!(d.read_str()).as_slice()))
+impl<E, D:Decoder<E>> Decodable<D, E> for String {
+ fn decode(d: &mut D) -> Result<String, E> {
+ Ok(String::from_str(try!(d.read_str()).as_slice()))
}
}
use slice::{ImmutableVector, MutableVector, Vector};
use str::{OwnedStr, Str, StrAllocating, StrSlice};
use str;
-use strbuf::StrBuf;
+use string::String;
use to_str::{IntoStr};
use vec::Vec;
}
}
-impl OwnedAsciiCast for StrBuf {
+impl OwnedAsciiCast for String {
#[inline]
fn is_ascii(&self) -> bool {
self.as_slice().is_ascii()
impl IntoStr for ~[Ascii] {
#[inline]
- fn into_str(self) -> StrBuf {
+ fn into_str(self) -> String {
let vector: Vec<Ascii> = self.as_slice().iter().map(|x| *x).collect();
vector.into_str()
}
impl IntoStr for Vec<Ascii> {
#[inline]
- fn into_str(self) -> StrBuf {
+ fn into_str(self) -> String {
unsafe {
let s: &str = mem::transmute(self.as_slice());
s.to_strbuf()
/// Convert the string to ASCII upper case:
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
/// but non-ASCII letters are unchanged.
- fn into_ascii_upper(self) -> StrBuf;
+ fn into_ascii_upper(self) -> String;
/// Convert the string to ASCII lower case:
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
/// but non-ASCII letters are unchanged.
- fn into_ascii_lower(self) -> StrBuf;
+ fn into_ascii_lower(self) -> String;
}
/// Extension methods for ASCII-subset only operations on string slices
/// Makes a copy of the string in ASCII upper case:
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
/// but non-ASCII letters are unchanged.
- fn to_ascii_upper(&self) -> StrBuf;
+ fn to_ascii_upper(&self) -> String;
/// Makes a copy of the string in ASCII lower case:
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
/// but non-ASCII letters are unchanged.
- fn to_ascii_lower(&self) -> StrBuf;
+ fn to_ascii_lower(&self) -> String;
/// Check that two strings are an ASCII case-insensitive match.
/// Same as `to_ascii_lower(a) == to_ascii_lower(b)`,
impl<'a> StrAsciiExt for &'a str {
#[inline]
- fn to_ascii_upper(&self) -> StrBuf {
+ fn to_ascii_upper(&self) -> String {
unsafe { str_copy_map_bytes(*self, ASCII_UPPER_MAP) }
}
#[inline]
- fn to_ascii_lower(&self) -> StrBuf {
+ fn to_ascii_lower(&self) -> String {
unsafe { str_copy_map_bytes(*self, ASCII_LOWER_MAP) }
}
}
}
-impl OwnedStrAsciiExt for StrBuf {
+impl OwnedStrAsciiExt for String {
#[inline]
- fn into_ascii_upper(self) -> StrBuf {
+ fn into_ascii_upper(self) -> String {
unsafe { str_map_bytes(self, ASCII_UPPER_MAP) }
}
#[inline]
- fn into_ascii_lower(self) -> StrBuf {
+ fn into_ascii_lower(self) -> String {
unsafe { str_map_bytes(self, ASCII_LOWER_MAP) }
}
}
#[inline]
-unsafe fn str_map_bytes(string: StrBuf, map: &'static [u8]) -> StrBuf {
+unsafe fn str_map_bytes(string: String, map: &'static [u8]) -> String {
let mut bytes = string.into_bytes();
for b in bytes.mut_iter() {
}
#[inline]
-unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> StrBuf {
+unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> String {
let mut s = string.to_strbuf();
for b in s.as_mut_bytes().mut_iter() {
*b = map[*b as uint];
use slice;
use str::StrSlice;
use str;
-use strbuf::StrBuf;
+use string::String;
/// The representation of a C String.
///
// FIXME (#12938): Until DST lands, we cannot decompose &str into &
// and str, so we cannot usefully take ToCStr arguments by reference
// (without forcing an additional & around &str). So we are instead
-// temporarily adding an instance for ~str and StrBuf, so that we can
+// temporarily adding an instance for ~str and String, so that we can
// take ToCStr as owned. When DST lands, the string instances should
// be revisted, and arguments bound by ToCStr should be passed by
// reference.
}
}
-impl ToCStr for StrBuf {
+impl ToCStr for String {
#[inline]
fn to_c_str(&self) -> CString {
self.as_bytes().to_c_str()
The `format!` macro is intended to be familiar to those coming from C's
printf/fprintf functions or Python's `str.format` function. In its current
-revision, the `format!` macro returns a `StrBuf` type which is the result of
+revision, the `format!` macro returns a `String` type which is the result of
the formatting. In the future it will also be able to pass in a stream to
format arguments directly while performing minimal allocations.
# #[allow(unused_must_use)]
# fn main() {
-format_args!(fmt::format, "this returns {}", "StrBuf");
+format_args!(fmt::format, "this returns {}", "String");
let some_writer: &mut io::Writer = &mut io::stdout();
format_args!(|args| { write!(some_writer, "{}", args) }, "print with a {}", "closure");
use result::{Ok, Err};
use str::{Str, StrAllocating};
use str;
-use strbuf::StrBuf;
+use string;
use slice::Vector;
pub use core::fmt::{Formatter, Result, FormatWriter, Show, rt};
/// let s = format_args!(fmt::format, "Hello, {}!", "world");
/// assert_eq!(s, "Hello, world!".to_owned());
/// ```
-pub fn format(args: &Arguments) -> StrBuf{
+pub fn format(args: &Arguments) -> string::String{
let mut output = io::MemWriter::new();
let _ = write!(&mut output, "{}", args);
str::from_utf8(output.unwrap().as_slice()).unwrap().into_strbuf()
}
/// Temporary transition utility
-pub fn format_strbuf(args: &Arguments) -> StrBuf {
+pub fn format_strbuf(args: &Arguments) -> string::String {
let mut output = io::MemWriter::new();
let _ = write!(&mut output, "{}", args);
str::from_utf8(output.unwrap().as_slice()).unwrap().into_strbuf()
* #[deriving(Hash)]
* struct Person {
* id: uint,
- * name: StrBuf,
+ * name: String,
* phone: u64,
* }
*
*
* struct Person {
* id: uint,
- * name: StrBuf,
+ * name: String,
* phone: u64,
* }
*
use num::ToStrRadix;
use option::{Some, None};
use str::Str;
- use strbuf::StrBuf;
+ use string::String;
use slice::{Vector, ImmutableVector};
use self::test::Bencher;
let mut state_inc = SipState::new_with_keys(k0, k1);
let mut state_full = SipState::new_with_keys(k0, k1);
- fn to_hex_str(r: &[u8, ..8]) -> StrBuf {
- let mut s = StrBuf::new();
+ fn to_hex_str(r: &[u8, ..8]) -> String {
+ let mut s = String::new();
for b in r.iter() {
s.push_str((*b as uint).to_str_radix(16u).as_slice());
}
]
}
- fn result_str(h: u64) -> StrBuf {
+ fn result_str(h: u64) -> String {
let r = result_bytes(h);
- let mut s = StrBuf::new();
+ let mut s = String::new();
for b in r.iter() {
s.push_str((*b as uint).to_str_radix(16u).as_slice());
}
let path = Path::new("message.txt");
let mut file = BufferedReader::new(File::open(&path));
- let lines: Vec<StrBuf> = file.lines().map(|x| x.unwrap()).collect();
+ let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();
```
* Make a simple TCP client connection and request
use slice::{Vector, MutableVector, ImmutableVector};
use str::{StrSlice, StrAllocating};
use str;
-use strbuf::StrBuf;
+use string::String;
use uint;
use vec::Vec;
/// A human-readable description about the error
pub desc: &'static str,
/// Detailed information about this error, not always available
- pub detail: Option<StrBuf>
+ pub detail: Option<String>
}
impl IoError {
/// This function returns all of the same errors as `read_to_end` with an
/// additional error if the reader's contents are not a valid sequence of
/// UTF-8 bytes.
- fn read_to_str(&mut self) -> IoResult<StrBuf> {
+ fn read_to_str(&mut self) -> IoResult<String> {
self.read_to_end().and_then(|s| {
match str::from_utf8(s.as_slice()) {
Some(s) => Ok(s.to_strbuf()),
buffer: &'r mut T,
}
-impl<'r, T: Buffer> Iterator<IoResult<StrBuf>> for Lines<'r, T> {
- fn next(&mut self) -> Option<IoResult<StrBuf>> {
+impl<'r, T: Buffer> Iterator<IoResult<String>> for Lines<'r, T> {
+ fn next(&mut self) -> Option<IoResult<String>> {
match self.buffer.read_line() {
Ok(x) => Some(Ok(x)),
Err(IoError { kind: EndOfFile, ..}) => None,
///
/// Additionally, this function can fail if the line of input read is not a
/// valid UTF-8 sequence of bytes.
- fn read_line(&mut self) -> IoResult<StrBuf> {
+ fn read_line(&mut self) -> IoResult<String> {
self.read_until('\n' as u8).and_then(|line|
match str::from_utf8(line.as_slice()) {
Some(s) => Ok(s.to_strbuf()),
}
})
- pub fn read_all(input: &mut Reader) -> StrBuf {
+ pub fn read_all(input: &mut Reader) -> String {
input.read_to_str().unwrap()
}
- pub fn run_output(cmd: Command) -> StrBuf {
+ pub fn run_output(cmd: Command) -> String {
let p = cmd.spawn();
assert!(p.is_ok());
let mut p = p.unwrap();
//! `&str`, a UTF-8 string, is a built-in type, and the standard library
//! defines methods for it on a variety of traits in the
//! [`str`](str/index.html) module. Rust strings are immutable;
-//! use the `StrBuf` type defined in [`strbuf`](strbuf/index.html)
+//! use the `String` type defined in [`strbuf`](strbuf/index.html)
//! for a mutable string builder.
//!
//! For converting to strings use the [`format!`](fmt/index.html)
pub mod slice;
pub mod vec;
pub mod str;
-pub mod strbuf;
+pub mod string;
pub mod ascii;
// The test runner requires std::slice::Vector, so re-export std::slice just for it.
#[cfg(test)] pub use slice;
- #[cfg(test)] pub use strbuf;
+ #[cfg(test)] pub use string;
}
#[test]
fn test_tls_multitask() {
- static my_key: Key<StrBuf> = &Key;
+ static my_key: Key<String> = &Key;
my_key.replace(Some("parent data".to_strbuf()));
task::spawn(proc() {
// TLS shouldn't carry over.
#[test]
fn test_tls_overwrite() {
- static my_key: Key<StrBuf> = &Key;
+ static my_key: Key<String> = &Key;
my_key.replace(Some("first data".to_strbuf()));
my_key.replace(Some("next data".to_strbuf())); // Shouldn't leak.
assert!(my_key.get().unwrap().as_slice() == "next data");
#[test]
fn test_tls_pop() {
- static my_key: Key<StrBuf> = &Key;
+ static my_key: Key<String> = &Key;
my_key.replace(Some("weasel".to_strbuf()));
assert!(my_key.replace(None).unwrap() == "weasel".to_strbuf());
// Pop must remove the data from the map.
// to get recorded as something within a rust stack segment. Then a
// subsequent upcall (esp. for logging, think vsnprintf) would run on
// a stack smaller than 1 MB.
- static my_key: Key<StrBuf> = &Key;
+ static my_key: Key<String> = &Key;
task::spawn(proc() {
my_key.replace(Some("hax".to_strbuf()));
});
#[test]
fn test_tls_multiple_types() {
- static str_key: Key<StrBuf> = &Key;
+ static str_key: Key<String> = &Key;
static box_key: Key<@()> = &Key;
static int_key: Key<int> = &Key;
task::spawn(proc() {
#[test]
fn test_tls_overwrite_multiple_types() {
- static str_key: Key<StrBuf> = &Key;
+ static str_key: Key<String> = &Key;
static box_key: Key<@()> = &Key;
static int_key: Key<int> = &Key;
task::spawn(proc() {
#[test]
#[should_fail]
fn test_tls_cleanup_on_failure() {
- static str_key: Key<StrBuf> = &Key;
+ static str_key: Key<String> = &Key;
static box_key: Key<@()> = &Key;
static int_key: Key<int> = &Key;
str_key.replace(Some("parent data".to_strbuf()));
use libc::c_int;
use num::strconv;
use num;
-use strbuf::StrBuf;
+use string::String;
pub use core::f32::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON, MIN_VALUE};
pub use core::f32::{MIN_POS_VALUE, MAX_VALUE, MIN_EXP, MAX_EXP, MIN_10_EXP};
///
/// * num - The float value
#[inline]
-pub fn to_str(num: f32) -> StrBuf {
+pub fn to_str(num: f32) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false);
r
///
/// * num - The float value
#[inline]
-pub fn to_str_hex(num: f32) -> StrBuf {
+pub fn to_str_hex(num: f32) -> String {
let (r, _) = strconv::float_to_str_common(
num, 16u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false);
r
/// * num - The float value
/// * radix - The base to use
#[inline]
-pub fn to_str_radix_special(num: f32, rdx: uint) -> (StrBuf, bool) {
+pub fn to_str_radix_special(num: f32, rdx: uint) -> (String, bool) {
strconv::float_to_str_common(num, rdx, true,
strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false)
}
/// * num - The float value
/// * digits - The number of significant digits
#[inline]
-pub fn to_str_exact(num: f32, dig: uint) -> StrBuf {
+pub fn to_str_exact(num: f32, dig: uint) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpNone, false);
r
/// * num - The float value
/// * digits - The number of significant digits
#[inline]
-pub fn to_str_digits(num: f32, dig: uint) -> StrBuf {
+pub fn to_str_digits(num: f32, dig: uint) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpNone, false);
r
/// * digits - The number of digits after the decimal point
/// * upper - Use `E` instead of `e` for the exponent sign
#[inline]
-pub fn to_str_exp_exact(num: f32, dig: uint, upper: bool) -> StrBuf {
+pub fn to_str_exp_exact(num: f32, dig: uint, upper: bool) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpDec, upper);
r
/// * digits - The number of digits after the decimal point
/// * upper - Use `E` instead of `e` for the exponent sign
#[inline]
-pub fn to_str_exp_digits(num: f32, dig: uint, upper: bool) -> StrBuf {
+pub fn to_str_exp_digits(num: f32, dig: uint, upper: bool) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpDec, upper);
r
/// possible misinterpretation of the result at higher bases. If those values
/// are expected, use `to_str_radix_special()` instead.
#[inline]
- fn to_str_radix(&self, rdx: uint) -> StrBuf {
+ fn to_str_radix(&self, rdx: uint) -> String {
let (r, special) = strconv::float_to_str_common(
*self, rdx, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false);
if special { fail!("number has a special value, \
use libc::c_int;
use num::strconv;
use num;
-use strbuf::StrBuf;
+use string::String;
pub use core::f64::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON, MIN_VALUE};
pub use core::f64::{MIN_POS_VALUE, MAX_VALUE, MIN_EXP, MAX_EXP, MIN_10_EXP};
///
/// * num - The float value
#[inline]
-pub fn to_str(num: f64) -> StrBuf {
+pub fn to_str(num: f64) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false);
r
///
/// * num - The float value
#[inline]
-pub fn to_str_hex(num: f64) -> StrBuf {
+pub fn to_str_hex(num: f64) -> String {
let (r, _) = strconv::float_to_str_common(
num, 16u, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false);
r
/// * num - The float value
/// * radix - The base to use
#[inline]
-pub fn to_str_radix_special(num: f64, rdx: uint) -> (StrBuf, bool) {
+pub fn to_str_radix_special(num: f64, rdx: uint) -> (String, bool) {
strconv::float_to_str_common(num, rdx, true,
strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false)
}
/// * num - The float value
/// * digits - The number of significant digits
#[inline]
-pub fn to_str_exact(num: f64, dig: uint) -> StrBuf {
+pub fn to_str_exact(num: f64, dig: uint) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpNone, false);
r
/// * num - The float value
/// * digits - The number of significant digits
#[inline]
-pub fn to_str_digits(num: f64, dig: uint) -> StrBuf {
+pub fn to_str_digits(num: f64, dig: uint) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpNone, false);
r
/// * digits - The number of digits after the decimal point
/// * upper - Use `E` instead of `e` for the exponent sign
#[inline]
-pub fn to_str_exp_exact(num: f64, dig: uint, upper: bool) -> StrBuf {
+pub fn to_str_exp_exact(num: f64, dig: uint, upper: bool) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigExact(dig), strconv::ExpDec, upper);
r
/// * digits - The number of digits after the decimal point
/// * upper - Use `E` instead of `e` for the exponent sign
#[inline]
-pub fn to_str_exp_digits(num: f64, dig: uint, upper: bool) -> StrBuf {
+pub fn to_str_exp_digits(num: f64, dig: uint, upper: bool) -> String {
let (r, _) = strconv::float_to_str_common(
num, 10u, true, strconv::SignNeg, strconv::DigMax(dig), strconv::ExpDec, upper);
r
/// possible misinterpretation of the result at higher bases. If those values
/// are expected, use `to_str_radix_special()` instead.
#[inline]
- fn to_str_radix(&self, rdx: uint) -> StrBuf {
+ fn to_str_radix(&self, rdx: uint) -> String {
let (r, special) = strconv::float_to_str_common(
*self, rdx, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false);
if special { fail!("number has a special value, \
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::i16::{BITS, BYTES, MIN, MAX};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::i32::{BITS, BYTES, MIN, MAX};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::i64::{BITS, BYTES, MIN, MAX};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::i8::{BITS, BYTES, MIN, MAX};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::int::{BITS, BYTES, MIN, MAX};
impl ToStrRadix for $T {
/// Convert to a string in a given base.
#[inline]
- fn to_str_radix(&self, radix: uint) -> StrBuf {
+ fn to_str_radix(&self, radix: uint) -> String {
format_strbuf!("{}", ::fmt::radix(*self, radix as u8))
}
}
#![allow(missing_doc)]
use option::Option;
-use strbuf::StrBuf;
+use string::String;
#[cfg(test)] use fmt::Show;
/// A generic trait for converting a value to a string with a radix (base)
pub trait ToStrRadix {
- fn to_str_radix(&self, radix: uint) -> StrBuf;
+ fn to_str_radix(&self, radix: uint) -> String;
}
/// A generic trait for converting a string with a radix (base) to a value
use slice::{ImmutableVector, MutableVector};
use std::cmp::{Ord, Eq};
use str::StrSlice;
-use strbuf::StrBuf;
+use string::String;
use vec::Vec;
/// A flag that specifies whether to use exponential (scientific) notation.
Div<T,T>+Neg<T>+Rem<T,T>+Mul<T,T>>(
num: T, radix: uint, negative_zero: bool,
sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_capital: bool
- ) -> (StrBuf, bool) {
+ ) -> (String, bool) {
let (bytes, special) = float_to_str_bytes_common(num, radix,
negative_zero, sign, digits, exp_format, exp_capital);
- (StrBuf::from_utf8(bytes).unwrap(), special)
+ (String::from_utf8(bytes).unwrap(), special)
}
// Some constants for from_str_bytes_common's input validation,
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::u16::{BITS, BYTES, MIN, MAX};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::u32::{BITS, BYTES, MIN, MAX};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::u64::{BITS, BYTES, MIN, MAX};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::u8::{BITS, BYTES, MIN, MAX};
use num::strconv;
use option::Option;
use slice::ImmutableVector;
-use strbuf::StrBuf;
+use string::String;
pub use core::uint::{BITS, BYTES, MIN, MAX};
impl ToStrRadix for $T {
/// Convert to a string in a given base.
#[inline]
- fn to_str_radix(&self, radix: uint) -> StrBuf {
+ fn to_str_radix(&self, radix: uint) -> String {
format_strbuf!("{}", ::fmt::radix(*self, radix as u8))
}
}
use slice::{Vector, ImmutableVector, MutableVector, OwnedVector};
use str::{Str, StrSlice, StrAllocating};
use str;
-use strbuf::StrBuf;
+use string::String;
use sync::atomics::{AtomicInt, INIT_ATOMIC_INT, SeqCst};
use vec::Vec;
use option;
use os::TMPBUF_SZ;
use slice::{MutableVector, ImmutableVector};
- use strbuf::StrBuf;
+ use string::String;
use str::{StrSlice, StrAllocating};
use str;
use vec::Vec;
pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
- -> Option<StrBuf> {
+ -> Option<String> {
unsafe {
let mut n = TMPBUF_SZ as DWORD;
///
/// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
/// for details.
-pub fn env() -> Vec<(StrBuf,StrBuf)> {
+pub fn env() -> Vec<(String,String)> {
env_as_bytes().move_iter().map(|(k,v)| {
let k = str::from_utf8_lossy(k.as_slice()).to_strbuf();
let v = str::from_utf8_lossy(v.as_slice()).to_strbuf();
/// # Failure
///
/// Fails if `n` has any interior NULs.
-pub fn getenv(n: &str) -> Option<StrBuf> {
+pub fn getenv(n: &str) -> Option<String> {
getenv_as_bytes(n).map(|v| str::from_utf8_lossy(v.as_slice()).to_strbuf())
}
#[cfg(windows)]
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
-pub fn getenv(n: &str) -> Option<StrBuf> {
+pub fn getenv(n: &str) -> Option<String> {
unsafe {
with_env_lock(|| {
use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
}
/// Returns the proper dll filename for the given basename of a file.
-pub fn dll_filename(base: &str) -> StrBuf {
+pub fn dll_filename(base: &str) -> String {
format_strbuf!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
}
}
/// Return the string corresponding to an `errno()` value of `errnum`.
-pub fn error_string(errnum: uint) -> StrBuf {
+pub fn error_string(errnum: uint) -> String {
return strerror(errnum);
#[cfg(unix)]
- fn strerror(errnum: uint) -> StrBuf {
+ fn strerror(errnum: uint) -> String {
#[cfg(target_os = "macos")]
#[cfg(target_os = "android")]
#[cfg(target_os = "freebsd")]
}
#[cfg(windows)]
- fn strerror(errnum: uint) -> StrBuf {
+ fn strerror(errnum: uint) -> String {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
}
/// Get a string representing the platform-dependent last error
-pub fn last_os_error() -> StrBuf {
+pub fn last_os_error() -> String {
error_string(errno() as uint)
}
}
#[cfg(not(windows))]
-fn real_args() -> Vec<StrBuf> {
+fn real_args() -> Vec<String> {
real_args_as_bytes().move_iter()
.map(|v| {
str::from_utf8_lossy(v.as_slice()).into_strbuf()
}
#[cfg(windows)]
-fn real_args() -> Vec<StrBuf> {
+fn real_args() -> Vec<String> {
use slice;
use option::Expect;
/// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
/// See `str::from_utf8_lossy` for details.
#[cfg(not(test))]
-pub fn args() -> Vec<StrBuf> {
+pub fn args() -> Vec<String> {
real_args()
}
#[cfg(test)]
#[allow(missing_doc)]
-pub fn args() -> ::realstd::vec::Vec<::realstd::strbuf::StrBuf> {
+pub fn args() -> ::realstd::vec::Vec<::realstd::string::String> {
::realstd::os::args()
}
assert!(a.len() >= 1);
}
- fn make_rand_name() -> StrBuf {
+ fn make_rand_name() -> String {
let mut rng = rand::task_rng();
let n = format_strbuf!("TEST{}", rng.gen_ascii_str(10u).as_slice());
assert!(getenv(n.as_slice()).is_none());
use option::{Option, None, Some};
use str;
use str::{MaybeOwned, Str, StrSlice, from_utf8_lossy};
-use strbuf::StrBuf;
+use string::String;
use slice::Vector;
use slice::{ImmutableEqVector, ImmutableVector};
use vec::Vec;
fn is_str(_: Option<&'a str>) -> bool { true }
}
-impl BytesContainer for StrBuf {
+impl BytesContainer for String {
#[inline]
fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
self.as_bytes()
Some(self.as_slice())
}
#[inline]
- fn is_str(_: Option<StrBuf>) -> bool { true }
+ fn is_str(_: Option<String>) -> bool { true }
}
impl<'a> BytesContainer for &'a [u8] {
use option::{Option, Some, None};
use slice::{Vector, OwnedVector, ImmutableVector};
use str::{CharSplits, Str, StrAllocating, StrVector, StrSlice};
-use strbuf::StrBuf;
+use string::String;
use vec::Vec;
use super::{contains_nul, BytesContainer, GenericPath, GenericPathUnsafe};
// preserved by the data structure; let the Windows API error out on them.
#[deriving(Clone)]
pub struct Path {
- repr: StrBuf, // assumed to never be empty
+ repr: String, // assumed to never be empty
prefix: Option<PathPrefix>,
sepidx: Option<uint> // index of the final separator in the non-prefix portion of repr
}
let filename = filename.container_as_str().unwrap();
match self.sepidx_or_prefix_len() {
None if ".." == self.repr.as_slice() => {
- let mut s = StrBuf::with_capacity(3 + filename.len());
+ let mut s = String::with_capacity(3 + filename.len());
s.push_str("..");
s.push_char(SEP);
s.push_str(filename);
self.update_normalized(filename);
}
Some((_,idxa,end)) if self.repr.as_slice().slice(idxa,end) == ".." => {
- let mut s = StrBuf::with_capacity(end + 1 + filename.len());
+ let mut s = String::with_capacity(end + 1 + filename.len());
s.push_str(self.repr.as_slice().slice_to(end));
s.push_char(SEP);
s.push_str(filename);
self.update_normalized(s);
}
Some((idxb,idxa,_)) if self.prefix == Some(DiskPrefix) && idxa == self.prefix_len() => {
- let mut s = StrBuf::with_capacity(idxb + filename.len());
+ let mut s = String::with_capacity(idxb + filename.len());
s.push_str(self.repr.as_slice().slice_to(idxb));
s.push_str(filename);
self.update_normalized(s);
}
Some((idxb,_,_)) => {
- let mut s = StrBuf::with_capacity(idxb + 1 + filename.len());
+ let mut s = String::with_capacity(idxb + 1 + filename.len());
s.push_str(self.repr.as_slice().slice_to(idxb));
s.push_char(SEP);
s.push_str(filename);
let newpath = Path::normalize__(path, prefix);
me.repr = match newpath {
Some(p) => p,
- None => StrBuf::from_str(path)
+ None => String::from_str(path)
};
me.prefix = prefix;
me.update_sepidx();
let path_ = if is_verbatim(me) { Path::normalize__(path, None) }
else { None };
let pathlen = path_.as_ref().map_or(path.len(), |p| p.len());
- let mut s = StrBuf::with_capacity(me.repr.len() + 1 + pathlen);
+ let mut s = String::with_capacity(me.repr.len() + 1 + pathlen);
s.push_str(me.repr.as_slice());
let plen = me.prefix_len();
// if me is "C:" we don't want to add a path separator
match self.sepidx_or_prefix_len() {
None if "." == self.repr.as_slice() => false,
None => {
- self.repr = StrBuf::from_str(".");
+ self.repr = String::from_str(".");
self.sepidx = None;
true
}
}
}
- fn normalize_<S: StrAllocating>(s: S) -> (Option<PathPrefix>, StrBuf) {
+ fn normalize_<S: StrAllocating>(s: S) -> (Option<PathPrefix>, String) {
// make borrowck happy
let (prefix, val) = {
let prefix = parse_prefix(s.as_slice());
})
}
- fn normalize__(s: &str, prefix: Option<PathPrefix>) -> Option<StrBuf> {
+ fn normalize__(s: &str, prefix: Option<PathPrefix>) -> Option<String> {
if prefix_is_verbatim(prefix) {
// don't do any normalization
match prefix {
Some(VerbatimUNCPrefix(x, 0)) if s.len() == 8 + x => {
// the server component has no trailing '\'
- let mut s = StrBuf::from_str(s);
+ let mut s = String::from_str(s);
s.push_char(SEP);
Some(s)
}
match prefix.unwrap() {
DiskPrefix => {
let len = prefix_len(prefix) + is_abs as uint;
- let mut s = StrBuf::from_str(s.slice_to(len));
+ let mut s = String::from_str(s.slice_to(len));
unsafe {
let v = s.as_mut_vec();
*v.get_mut(0) = v.get(0)
}
VerbatimDiskPrefix => {
let len = prefix_len(prefix) + is_abs as uint;
- let mut s = StrBuf::from_str(s.slice_to(len));
+ let mut s = String::from_str(s.slice_to(len));
unsafe {
let v = s.as_mut_vec();
*v.get_mut(4) = v.get(4).to_ascii().to_upper().to_byte();
_ => {
let plen = prefix_len(prefix);
if s.len() > plen {
- Some(StrBuf::from_str(s.slice_to(plen)))
+ Some(String::from_str(s.slice_to(plen)))
} else { None }
}
}
} else if is_abs && comps.is_empty() {
- Some(StrBuf::from_char(1, SEP))
+ Some(String::from_char(1, SEP))
} else {
let prefix_ = s.slice_to(prefix_len(prefix));
let n = prefix_.len() +
if is_abs { comps.len() } else { comps.len() - 1} +
comps.iter().map(|v| v.len()).sum();
- let mut s = StrBuf::with_capacity(n);
+ let mut s = String::with_capacity(n);
match prefix {
Some(DiskPrefix) => {
s.push_char(prefix_[0].to_ascii().to_upper().to_char());
pub use slice::{ImmutableVector, MutableVector};
pub use slice::{ImmutableEqVector, ImmutableTotalOrdVector, MutableTotalOrdVector};
pub use slice::{Vector, VectorVector, OwnedVector, MutableVectorAllocating};
-pub use strbuf::StrBuf;
+pub use string::String;
pub use vec::Vec;
// Reexported runtime types
use result::{Ok, Err};
use slice::Vector;
use str::{Str, StrSlice};
-use strbuf::StrBuf;
+use string::String;
use to_str::ToStr;
use vec::Vec;
}
}
-pub fn repr_to_str<T>(t: &T) -> StrBuf {
+pub fn repr_to_str<T>(t: &T) -> String {
use str;
use str::StrAllocating;
use io;
#[test]
fn tls() {
- local_data_key!(key: @StrBuf)
+ local_data_key!(key: @String)
key.replace(Some(@"data".to_strbuf()));
assert_eq!(key.get().unwrap().as_slice(), "data");
- local_data_key!(key2: @StrBuf)
+ local_data_key!(key2: @String)
key2.replace(Some(@"data".to_strbuf()));
assert_eq!(key2.get().unwrap().as_slice(), "data");
}
use rt::local::Local;
use rt::task::Task;
use str::Str;
-use strbuf::StrBuf;
+use string::String;
use task::TaskResult;
use uw = rt::libunwind;
{
let msg_s = match msg.as_ref::<&'static str>() {
Some(s) => *s,
- None => match msg.as_ref::<StrBuf>() {
+ None => match msg.as_ref::<String>() {
Some(s) => s.as_slice(),
None => "Box<Any>",
}
use result::Result;
use slice::Vector;
use slice::{ImmutableVector, MutableVector, CloneableVector};
-use strbuf::StrBuf;
+use string::String;
use vec::Vec;
pub use core::str::{from_utf8, CharEq, Chars, CharOffsets};
///
/// Returns `Err` with the original vector if the vector contains invalid
/// UTF-8.
-pub fn from_utf8_owned(vv: Vec<u8>) -> Result<StrBuf, Vec<u8>> {
- StrBuf::from_utf8(vv)
+pub fn from_utf8_owned(vv: Vec<u8>) -> Result<String, Vec<u8>> {
+ String::from_utf8(vv)
}
/// Convert a byte to a UTF-8 string
/// # Failure
///
/// Fails if invalid UTF-8
-pub fn from_byte(b: u8) -> StrBuf {
+pub fn from_byte(b: u8) -> String {
assert!(b < 128u8);
- StrBuf::from_char(1, b as char)
+ String::from_char(1, b as char)
}
/// Convert a char to a string
-pub fn from_char(ch: char) -> StrBuf {
- let mut buf = StrBuf::new();
+pub fn from_char(ch: char) -> String {
+ let mut buf = String::new();
buf.push_char(ch);
buf
}
/// Convert a vector of chars to a string
-pub fn from_chars(chs: &[char]) -> StrBuf {
+pub fn from_chars(chs: &[char]) -> String {
chs.iter().map(|c| *c).collect()
}
/// Methods for vectors of strings
pub trait StrVector {
/// Concatenate a vector of strings.
- fn concat(&self) -> StrBuf;
+ fn concat(&self) -> String;
/// Concatenate a vector of strings, placing a given separator between each.
- fn connect(&self, sep: &str) -> StrBuf;
+ fn connect(&self, sep: &str) -> String;
}
impl<'a, S: Str> StrVector for &'a [S] {
- fn concat(&self) -> StrBuf {
+ fn concat(&self) -> String {
if self.is_empty() {
- return StrBuf::new();
+ return String::new();
}
// `len` calculation may overflow but push_str but will check boundaries
let len = self.iter().map(|s| s.as_slice().len()).sum();
- let mut result = StrBuf::with_capacity(len);
+ let mut result = String::with_capacity(len);
for s in self.iter() {
result.push_str(s.as_slice())
result
}
- fn connect(&self, sep: &str) -> StrBuf {
+ fn connect(&self, sep: &str) -> String {
if self.is_empty() {
- return StrBuf::new();
+ return String::new();
}
// concat is faster
// `len` calculation may overflow but push_str but will check boundaries
let len = sep.len() * (self.len() - 1)
+ self.iter().map(|s| s.as_slice().len()).sum();
- let mut result = StrBuf::with_capacity(len);
+ let mut result = String::with_capacity(len);
let mut first = true;
for s in self.iter() {
impl<'a, S: Str> StrVector for Vec<S> {
#[inline]
- fn concat(&self) -> StrBuf {
+ fn concat(&self) -> String {
self.as_slice().concat()
}
#[inline]
- fn connect(&self, sep: &str) -> StrBuf {
+ fn connect(&self, sep: &str) -> String {
self.as_slice().connect(sep)
}
}
/// # Return value
///
/// The original string with all occurrences of `from` replaced with `to`
-pub fn replace(s: &str, from: &str, to: &str) -> StrBuf {
- let mut result = StrBuf::new();
+pub fn replace(s: &str, from: &str, to: &str) -> String {
+ let mut result = String::new();
let mut last_end = 0;
for (start, end) in s.match_indices(from) {
result.push_str(unsafe{raw::slice_bytes(s, last_end, start)});
/// v[4] = 0xD800;
/// assert_eq!(str::from_utf16(v), None);
/// ```
-pub fn from_utf16(v: &[u16]) -> Option<StrBuf> {
- let mut s = StrBuf::with_capacity(v.len() / 2);
+pub fn from_utf16(v: &[u16]) -> Option<String> {
+ let mut s = String::with_capacity(v.len() / 2);
for c in utf16_items(v) {
match c {
ScalarValue(c) => s.push_char(c),
/// assert_eq!(str::from_utf16_lossy(v),
/// "𝄞mus\uFFFDic\uFFFD".to_owned());
/// ```
-pub fn from_utf16_lossy(v: &[u16]) -> StrBuf {
+pub fn from_utf16_lossy(v: &[u16]) -> String {
utf16_items(v).map(|c| c.to_char_lossy()).collect()
}
}
}
- let mut res = StrBuf::with_capacity(total);
+ let mut res = String::with_capacity(total);
if i > 0 {
unsafe {
Section: MaybeOwned
*/
-/// A MaybeOwned is a string that can hold either a StrBuf or a &str.
+/// A MaybeOwned is a string that can hold either a String or a &str.
/// This can be useful as an optimization when an allocation is sometimes
/// needed but not always.
pub enum MaybeOwned<'a> {
/// A borrowed string
Slice(&'a str),
/// An owned string
- Owned(StrBuf)
+ Owned(String)
}
/// SendStr is a specialization of `MaybeOwned` to be sendable
fn into_maybe_owned(self) -> MaybeOwned<'a>;
}
-impl<'a> IntoMaybeOwned<'a> for StrBuf {
+impl<'a> IntoMaybeOwned<'a> for String {
#[inline]
fn into_maybe_owned(self) -> MaybeOwned<'a> {
Owned(self)
impl<'a> StrAllocating for MaybeOwned<'a> {
#[inline]
- fn into_owned(self) -> StrBuf {
+ fn into_owned(self) -> String {
match self {
Slice(s) => s.to_owned(),
Owned(s) => s
use libc;
use mem;
use raw::Slice;
- use strbuf::StrBuf;
+ use string::String;
use vec::Vec;
pub use core::str::raw::{from_utf8, c_str_to_static_slice, slice_bytes};
pub use core::str::raw::{slice_unchecked};
/// Create a Rust string from a *u8 buffer of the given length
- pub unsafe fn from_buf_len(buf: *u8, len: uint) -> StrBuf {
- let mut result = StrBuf::new();
+ pub unsafe fn from_buf_len(buf: *u8, len: uint) -> String {
+ let mut result = String::new();
result.push_bytes(mem::transmute(Slice {
data: buf,
len: len,
}
/// Create a Rust string from a null-terminated C string
- pub unsafe fn from_c_str(c_string: *libc::c_char) -> StrBuf {
- let mut buf = StrBuf::new();
+ pub unsafe fn from_c_str(c_string: *libc::c_char) -> String {
+ let mut buf = String::new();
buf.push_bytes(CString::new(c_string, false).as_bytes_no_nul());
buf
}
/// Converts an owned vector of bytes to a new owned string. This assumes
/// that the utf-8-ness of the vector has already been validated
#[inline]
- pub unsafe fn from_utf8_owned(v: Vec<u8>) -> StrBuf {
+ pub unsafe fn from_utf8_owned(v: Vec<u8>) -> String {
mem::transmute(v)
}
/// Converts a byte to a string.
- pub unsafe fn from_byte(u: u8) -> StrBuf {
+ pub unsafe fn from_byte(u: u8) -> String {
from_utf8_owned(vec![u])
}
/// Any string that can be represented as a slice
pub trait StrAllocating: Str {
- /// Convert `self` into a `StrBuf`, not making a copy if possible.
- fn into_owned(self) -> StrBuf;
+ /// Convert `self` into a `String`, not making a copy if possible.
+ fn into_owned(self) -> String;
- /// Convert `self` into a `StrBuf`.
+ /// Convert `self` into a `String`.
#[inline]
- fn to_strbuf(&self) -> StrBuf {
- StrBuf::from_str(self.as_slice())
+ fn to_strbuf(&self) -> String {
+ String::from_str(self.as_slice())
}
- /// Convert `self` into a `StrBuf`, not making a copy if possible.
+ /// Convert `self` into a `String`, not making a copy if possible.
#[inline]
- fn into_strbuf(self) -> StrBuf {
+ fn into_strbuf(self) -> String {
self.into_owned()
}
/// Escape each char in `s` with `char::escape_default`.
- fn escape_default(&self) -> StrBuf {
+ fn escape_default(&self) -> String {
let me = self.as_slice();
- let mut out = StrBuf::with_capacity(me.len());
+ let mut out = String::with_capacity(me.len());
for c in me.chars() {
c.escape_default(|c| out.push_char(c));
}
}
/// Escape each char in `s` with `char::escape_unicode`.
- fn escape_unicode(&self) -> StrBuf {
+ fn escape_unicode(&self) -> String {
let me = self.as_slice();
- let mut out = StrBuf::with_capacity(me.len());
+ let mut out = String::with_capacity(me.len());
for c in me.chars() {
c.escape_unicode(|c| out.push_char(c));
}
/// // not found, so no change.
/// assert_eq!(s.replace("cookie monster", "little lamb"), s);
/// ```
- fn replace(&self, from: &str, to: &str) -> StrBuf {
+ fn replace(&self, from: &str, to: &str) -> String {
let me = self.as_slice();
- let mut result = StrBuf::new();
+ let mut result = String::new();
let mut last_end = 0;
for (start, end) in me.match_indices(from) {
result.push_str(unsafe{raw::slice_bytes(me, last_end, start)});
result
}
- /// Copy a slice into a new `StrBuf`.
+ /// Copy a slice into a new `String`.
#[inline]
- fn to_owned(&self) -> StrBuf {
+ fn to_owned(&self) -> String {
use slice::Vector;
unsafe {
}
/// Given a string, make a new string with repeated copies of it.
- fn repeat(&self, nn: uint) -> StrBuf {
+ fn repeat(&self, nn: uint) -> String {
let me = self.as_slice();
- let mut ret = StrBuf::with_capacity(nn * me.len());
+ let mut ret = String::with_capacity(nn * me.len());
for _ in range(0, nn) {
ret.push_str(me);
}
impl<'a> StrAllocating for &'a str {
#[inline]
- fn into_owned(self) -> StrBuf {
+ fn into_owned(self) -> String {
self.to_owned()
}
}
fn into_bytes(self) -> Vec<u8>;
/// Pushes the given string onto this string, returning the concatenation of the two strings.
- fn append(self, rhs: &str) -> StrBuf;
+ fn append(self, rhs: &str) -> String;
}
-impl OwnedStr for StrBuf {
+impl OwnedStr for String {
#[inline]
fn into_bytes(self) -> Vec<u8> {
unsafe { mem::transmute(self) }
}
#[inline]
- fn append(self, rhs: &str) -> StrBuf {
- let mut new_str = StrBuf::from_owned_str(self);
+ fn append(self, rhs: &str) -> String {
+ let mut new_str = String::from_owned_str(self);
new_str.push_str(rhs);
new_str
}
use default::Default;
use prelude::*;
use str::*;
- use strbuf::StrBuf;
+ use string::String;
#[test]
fn test_eq_slice() {
#[test]
fn test_collect() {
let empty = "".to_owned();
- let s: StrBuf = empty.as_slice().chars().collect();
+ let s: String = empty.as_slice().chars().collect();
assert_eq!(empty, s);
let data = "ประเทศไทย中".to_owned();
- let s: StrBuf = data.as_slice().chars().collect();
+ let s: String = data.as_slice().chars().collect();
assert_eq!(data, s);
}
#[test]
fn test_concat() {
- fn t(v: &[StrBuf], s: &str) {
+ fn t(v: &[String], s: &str) {
assert_eq!(v.concat(), s.to_str().into_owned());
}
t(["you".to_owned(), "know".to_owned(), "I'm".to_owned(),
"no".to_owned(), "good".to_owned()], "youknowI'mnogood");
- let v: &[StrBuf] = [];
+ let v: &[String] = [];
t(v, "");
t(["hi".to_owned()], "hi");
}
#[test]
fn test_connect() {
- fn t(v: &[StrBuf], sep: &str, s: &str) {
+ fn t(v: &[String], sep: &str, s: &str) {
assert_eq!(v.connect(sep), s.to_str().into_owned());
}
t(["you".to_owned(), "know".to_owned(), "I'm".to_owned(),
"no".to_owned(), "good".to_owned()],
" ", "you know I'm no good");
- let v: &[StrBuf] = [];
+ let v: &[String] = [];
t(v, " ", "");
t(["hi".to_owned()], " ", "hi");
}
assert_eq!("ab", unsafe {raw::slice_bytes("abc", 0, 2)});
assert_eq!("bc", unsafe {raw::slice_bytes("abc", 1, 3)});
assert_eq!("", unsafe {raw::slice_bytes("abc", 1, 1)});
- fn a_million_letter_a() -> StrBuf {
+ fn a_million_letter_a() -> String {
let mut i = 0;
- let mut rs = StrBuf::new();
+ let mut rs = String::new();
while i < 100000 {
rs.push_str("aaaaaaaaaa");
i += 1;
}
rs
}
- fn half_a_million_letter_a() -> StrBuf {
+ fn half_a_million_letter_a() -> String {
let mut i = 0;
- let mut rs = StrBuf::new();
+ let mut rs = String::new();
while i < 100000 {
rs.push_str("aaaaa");
i += 1;
assert_eq!("", data.slice(3, 3));
assert_eq!("华", data.slice(30, 33));
- fn a_million_letter_X() -> StrBuf {
+ fn a_million_letter_X() -> String {
let mut i = 0;
- let mut rs = StrBuf::new();
+ let mut rs = String::new();
while i < 100000 {
rs.push_str("华华华华华华华华华华");
i += 1;
}
rs
}
- fn half_a_million_letter_X() -> StrBuf {
+ fn half_a_million_letter_X() -> String {
let mut i = 0;
- let mut rs = StrBuf::new();
+ let mut rs = String::new();
while i < 100000 {
rs.push_str("华华华华华");
i += 1;
#[test]
fn vec_str_conversions() {
- let s1: StrBuf = "All mimsy were the borogoves".to_strbuf();
+ let s1: String = "All mimsy were the borogoves".to_strbuf();
let v: Vec<u8> = Vec::from_slice(s1.as_bytes());
- let s2: StrBuf = from_utf8(v.as_slice()).unwrap().to_strbuf();
+ let s2: String = from_utf8(v.as_slice()).unwrap().to_strbuf();
let mut i: uint = 0u;
let n1: uint = s1.len();
let n2: uint = v.len();
#[test]
fn test_nfd_chars() {
- assert_eq!("abc".nfd_chars().collect::<StrBuf>(), "abc".to_strbuf());
- assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<StrBuf>(), "d\u0307\u01c4".to_strbuf());
- assert_eq!("\u2026".nfd_chars().collect::<StrBuf>(), "\u2026".to_strbuf());
- assert_eq!("\u2126".nfd_chars().collect::<StrBuf>(), "\u03a9".to_strbuf());
- assert_eq!("\u1e0b\u0323".nfd_chars().collect::<StrBuf>(), "d\u0323\u0307".to_strbuf());
- assert_eq!("\u1e0d\u0307".nfd_chars().collect::<StrBuf>(), "d\u0323\u0307".to_strbuf());
- assert_eq!("a\u0301".nfd_chars().collect::<StrBuf>(), "a\u0301".to_strbuf());
- assert_eq!("\u0301a".nfd_chars().collect::<StrBuf>(), "\u0301a".to_strbuf());
- assert_eq!("\ud4db".nfd_chars().collect::<StrBuf>(), "\u1111\u1171\u11b6".to_strbuf());
- assert_eq!("\uac1c".nfd_chars().collect::<StrBuf>(), "\u1100\u1162".to_strbuf());
+ assert_eq!("abc".nfd_chars().collect::<String>(), "abc".to_strbuf());
+ assert_eq!("\u1e0b\u01c4".nfd_chars().collect::<String>(), "d\u0307\u01c4".to_strbuf());
+ assert_eq!("\u2026".nfd_chars().collect::<String>(), "\u2026".to_strbuf());
+ assert_eq!("\u2126".nfd_chars().collect::<String>(), "\u03a9".to_strbuf());
+ assert_eq!("\u1e0b\u0323".nfd_chars().collect::<String>(), "d\u0323\u0307".to_strbuf());
+ assert_eq!("\u1e0d\u0307".nfd_chars().collect::<String>(), "d\u0323\u0307".to_strbuf());
+ assert_eq!("a\u0301".nfd_chars().collect::<String>(), "a\u0301".to_strbuf());
+ assert_eq!("\u0301a".nfd_chars().collect::<String>(), "\u0301a".to_strbuf());
+ assert_eq!("\ud4db".nfd_chars().collect::<String>(), "\u1111\u1171\u11b6".to_strbuf());
+ assert_eq!("\uac1c".nfd_chars().collect::<String>(), "\u1100\u1162".to_strbuf());
}
#[test]
fn test_nfkd_chars() {
- assert_eq!("abc".nfkd_chars().collect::<StrBuf>(), "abc".to_strbuf());
- assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<StrBuf>(), "d\u0307DZ\u030c".to_strbuf());
- assert_eq!("\u2026".nfkd_chars().collect::<StrBuf>(), "...".to_strbuf());
- assert_eq!("\u2126".nfkd_chars().collect::<StrBuf>(), "\u03a9".to_strbuf());
- assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<StrBuf>(), "d\u0323\u0307".to_strbuf());
- assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<StrBuf>(), "d\u0323\u0307".to_strbuf());
- assert_eq!("a\u0301".nfkd_chars().collect::<StrBuf>(), "a\u0301".to_strbuf());
- assert_eq!("\u0301a".nfkd_chars().collect::<StrBuf>(), "\u0301a".to_strbuf());
- assert_eq!("\ud4db".nfkd_chars().collect::<StrBuf>(), "\u1111\u1171\u11b6".to_strbuf());
- assert_eq!("\uac1c".nfkd_chars().collect::<StrBuf>(), "\u1100\u1162".to_strbuf());
+ assert_eq!("abc".nfkd_chars().collect::<String>(), "abc".to_strbuf());
+ assert_eq!("\u1e0b\u01c4".nfkd_chars().collect::<String>(), "d\u0307DZ\u030c".to_strbuf());
+ assert_eq!("\u2026".nfkd_chars().collect::<String>(), "...".to_strbuf());
+ assert_eq!("\u2126".nfkd_chars().collect::<String>(), "\u03a9".to_strbuf());
+ assert_eq!("\u1e0b\u0323".nfkd_chars().collect::<String>(), "d\u0323\u0307".to_strbuf());
+ assert_eq!("\u1e0d\u0307".nfkd_chars().collect::<String>(), "d\u0323\u0307".to_strbuf());
+ assert_eq!("a\u0301".nfkd_chars().collect::<String>(), "a\u0301".to_strbuf());
+ assert_eq!("\u0301a".nfkd_chars().collect::<String>(), "\u0301a".to_strbuf());
+ assert_eq!("\ud4db".nfkd_chars().collect::<String>(), "\u1111\u1171\u11b6".to_strbuf());
+ assert_eq!("\uac1c".nfkd_chars().collect::<String>(), "\u1100\u1162".to_strbuf());
}
#[test]
}
t::<&str>();
- t::<StrBuf>();
+ t::<String>();
}
#[test]
#[test]
fn test_from_str() {
- let owned: Option<StrBuf> = from_str("string");
+ let owned: Option<String> = from_str("string");
assert_eq!(owned, Some("string".to_strbuf()));
}
+++ /dev/null
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! An owned, growable string that enforces that its contents are valid UTF-8.
-
-use c_vec::CVec;
-use char::Char;
-use cmp::Equiv;
-use container::{Container, Mutable};
-use default::Default;
-use fmt;
-use from_str::FromStr;
-use io::Writer;
-use iter::{Extendable, FromIterator, Iterator, range};
-use mem;
-use option::{None, Option, Some};
-use ptr::RawPtr;
-use ptr;
-use result::{Result, Ok, Err};
-use slice::Vector;
-use str::{CharRange, Str, StrSlice, StrAllocating};
-use str;
-use vec::Vec;
-
-/// A growable string stored as a UTF-8 encoded buffer.
-#[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
-pub struct StrBuf {
- vec: Vec<u8>,
-}
-
-impl StrBuf {
- /// Creates a new string buffer initialized with the empty string.
- #[inline]
- pub fn new() -> StrBuf {
- StrBuf {
- vec: Vec::new(),
- }
- }
-
- /// Creates a new string buffer with the given capacity.
- #[inline]
- pub fn with_capacity(capacity: uint) -> StrBuf {
- StrBuf {
- vec: Vec::with_capacity(capacity),
- }
- }
-
- /// Creates a new string buffer from length, capacity, and a pointer.
- #[inline]
- pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> StrBuf {
- StrBuf {
- vec: Vec::from_raw_parts(length, capacity, ptr),
- }
- }
-
- /// Creates a new string buffer from the given string.
- #[inline]
- pub fn from_str(string: &str) -> StrBuf {
- StrBuf {
- vec: Vec::from_slice(string.as_bytes())
- }
- }
-
- /// Creates a new string buffer from the given owned string, taking care not to copy it.
- #[inline]
- pub fn from_owned_str(string: StrBuf) -> StrBuf {
- string
- }
-
- /// Returns the vector as a string buffer, if possible, taking care not to
- /// copy it.
- ///
- /// Returns `Err` with the original vector if the vector contains invalid
- /// UTF-8.
- #[inline]
- pub fn from_utf8(vec: Vec<u8>) -> Result<StrBuf, Vec<u8>> {
- if str::is_utf8(vec.as_slice()) {
- Ok(StrBuf { vec: vec })
- } else {
- Err(vec)
- }
- }
-
- /// Return the underlying byte buffer, encoded as UTF-8.
- #[inline]
- pub fn into_bytes(self) -> Vec<u8> {
- self.vec
- }
-
- /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
- /// again.
- #[inline]
- pub fn append(mut self, second: &str) -> StrBuf {
- self.push_str(second);
- self
- }
-
- /// Creates a string buffer by repeating a character `length` times.
- #[inline]
- pub fn from_char(length: uint, ch: char) -> StrBuf {
- if length == 0 {
- return StrBuf::new()
- }
-
- let mut buf = StrBuf::new();
- buf.push_char(ch);
- let size = buf.len() * length;
- buf.reserve(size);
- for _ in range(1, length) {
- buf.push_char(ch)
- }
- buf
- }
-
- /// Pushes the given string onto this string buffer.
- #[inline]
- pub fn push_str(&mut self, string: &str) {
- self.vec.push_all(string.as_bytes())
- }
-
- /// Push `ch` onto the given string `count` times.
- #[inline]
- pub fn grow(&mut self, count: uint, ch: char) {
- for _ in range(0, count) {
- self.push_char(ch)
- }
- }
-
- /// Returns the number of bytes that this string buffer can hold without reallocating.
- #[inline]
- pub fn byte_capacity(&self) -> uint {
- self.vec.capacity()
- }
-
- /// Reserves capacity for at least `extra` additional bytes in this string buffer.
- #[inline]
- pub fn reserve_additional(&mut self, extra: uint) {
- self.vec.reserve_additional(extra)
- }
-
- /// Reserves capacity for at least `capacity` bytes in this string buffer.
- #[inline]
- pub fn reserve(&mut self, capacity: uint) {
- self.vec.reserve(capacity)
- }
-
- /// Reserves capacity for exactly `capacity` bytes in this string buffer.
- #[inline]
- pub fn reserve_exact(&mut self, capacity: uint) {
- self.vec.reserve_exact(capacity)
- }
-
- /// Shrinks the capacity of this string buffer to match its length.
- #[inline]
- pub fn shrink_to_fit(&mut self) {
- self.vec.shrink_to_fit()
- }
-
- /// Adds the given character to the end of the string.
- #[inline]
- pub fn push_char(&mut self, ch: char) {
- let cur_len = self.len();
- unsafe {
- // This may use up to 4 bytes.
- self.vec.reserve_additional(4);
-
- // Attempt to not use an intermediate buffer by just pushing bytes
- // directly onto this string.
- let mut c_vector = CVec::new(self.vec.as_mut_ptr().offset(cur_len as int), 4);
- let used = ch.encode_utf8(c_vector.as_mut_slice());
- self.vec.set_len(cur_len + used);
- }
- }
-
- /// Pushes the given bytes onto this string buffer. This is unsafe because it does not check
- /// to ensure that the resulting string will be valid UTF-8.
- #[inline]
- pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
- self.vec.push_all(bytes)
- }
-
- /// Works with the underlying buffer as a byte slice.
- #[inline]
- pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
- self.vec.as_slice()
- }
-
- /// Works with the underlying buffer as a mutable byte slice. Unsafe
- /// because this can be used to violate the UTF-8 property.
- #[inline]
- pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
- self.vec.as_mut_slice()
- }
-
- /// Shorten a string to the specified length (which must be <= the current length)
- #[inline]
- pub fn truncate(&mut self, len: uint) {
- assert!(self.as_slice().is_char_boundary(len));
- self.vec.truncate(len)
- }
-
- /// Appends a byte to this string buffer. The caller must preserve the valid UTF-8 property.
- #[inline]
- pub unsafe fn push_byte(&mut self, byte: u8) {
- self.push_bytes([byte])
- }
-
- /// Removes the last byte from the string buffer and returns it. Returns `None` if this string
- /// buffer is empty.
- ///
- /// The caller must preserve the valid UTF-8 property.
- #[inline]
- pub unsafe fn pop_byte(&mut self) -> Option<u8> {
- let len = self.len();
- if len == 0 {
- return None
- }
-
- let byte = self.as_slice()[len - 1];
- self.vec.set_len(len - 1);
- Some(byte)
- }
-
- /// Removes the last character from the string buffer and returns it. Returns `None` if this
- /// string buffer is empty.
- #[inline]
- pub fn pop_char(&mut self) -> Option<char> {
- let len = self.len();
- if len == 0 {
- return None
- }
-
- let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
- unsafe {
- self.vec.set_len(next);
- }
- Some(ch)
- }
-
- /// Removes the first byte from the string buffer and returns it. Returns `None` if this string
- /// buffer is empty.
- ///
- /// The caller must preserve the valid UTF-8 property.
- pub unsafe fn shift_byte(&mut self) -> Option<u8> {
- self.vec.shift()
- }
-
- /// Removes the first character from the string buffer and returns it. Returns `None` if this
- /// string buffer is empty.
- ///
- /// # Warning
- ///
- /// This is a O(n) operation as it requires copying every element in the buffer.
- pub fn shift_char (&mut self) -> Option<char> {
- let len = self.len();
- if len == 0 {
- return None
- }
-
- let CharRange {ch, next} = self.as_slice().char_range_at(0);
- let new_len = len - next;
- unsafe {
- ptr::copy_memory(self.vec.as_mut_ptr(), self.vec.as_ptr().offset(next as int), new_len);
- self.vec.set_len(new_len);
- }
- Some(ch)
- }
-
- /// Views the string buffer as a mutable sequence of bytes.
- ///
- /// Callers must preserve the valid UTF-8 property.
- pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
- &mut self.vec
- }
-}
-
-impl Container for StrBuf {
- #[inline]
- fn len(&self) -> uint {
- self.vec.len()
- }
-}
-
-impl Mutable for StrBuf {
- #[inline]
- fn clear(&mut self) {
- self.vec.clear()
- }
-}
-
-impl FromIterator<char> for StrBuf {
- fn from_iter<I:Iterator<char>>(iterator: I) -> StrBuf {
- let mut buf = StrBuf::new();
- buf.extend(iterator);
- buf
- }
-}
-
-impl Extendable<char> for StrBuf {
- fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
- for ch in iterator {
- self.push_char(ch)
- }
- }
-}
-
-impl Str for StrBuf {
- #[inline]
- fn as_slice<'a>(&'a self) -> &'a str {
- unsafe {
- mem::transmute(self.vec.as_slice())
- }
- }
-}
-
-impl StrAllocating for StrBuf {
- #[inline]
- fn into_owned(self) -> StrBuf {
- self
- }
-
- #[inline]
- fn into_strbuf(self) -> StrBuf {
- self
- }
-}
-
-impl Default for StrBuf {
- fn default() -> StrBuf {
- StrBuf::new()
- }
-}
-
-impl fmt::Show for StrBuf {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- self.as_slice().fmt(f)
- }
-}
-
-impl<H:Writer> ::hash::Hash<H> for StrBuf {
- #[inline]
- fn hash(&self, hasher: &mut H) {
- self.as_slice().hash(hasher)
- }
-}
-
-impl<'a, S: Str> Equiv<S> for StrBuf {
- #[inline]
- fn equiv(&self, other: &S) -> bool {
- self.as_slice() == other.as_slice()
- }
-}
-
-impl FromStr for StrBuf {
- #[inline]
- fn from_str(s: &str) -> Option<StrBuf> {
- Some(s.to_strbuf())
- }
-}
-
-#[cfg(test)]
-mod tests {
- extern crate test;
- use container::{Container, Mutable};
- use self::test::Bencher;
- use str::{Str, StrSlice};
- use super::StrBuf;
-
- #[bench]
- fn bench_with_capacity(b: &mut Bencher) {
- b.iter(|| {
- StrBuf::with_capacity(100)
- });
- }
-
- #[bench]
- fn bench_push_str(b: &mut Bencher) {
- let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
- b.iter(|| {
- let mut r = StrBuf::new();
- r.push_str(s);
- });
- }
-
- #[test]
- fn test_push_bytes() {
- let mut s = StrBuf::from_str("ABC");
- unsafe {
- s.push_bytes([ 'D' as u8 ]);
- }
- assert_eq!(s.as_slice(), "ABCD");
- }
-
- #[test]
- fn test_push_str() {
- let mut s = StrBuf::new();
- s.push_str("");
- assert_eq!(s.as_slice().slice_from(0), "");
- s.push_str("abc");
- assert_eq!(s.as_slice().slice_from(0), "abc");
- s.push_str("ประเทศไทย中华Việt Nam");
- assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
- }
-
- #[test]
- fn test_push_char() {
- let mut data = StrBuf::from_str("ประเทศไทย中");
- data.push_char('华');
- data.push_char('b'); // 1 byte
- data.push_char('¢'); // 2 byte
- data.push_char('€'); // 3 byte
- data.push_char('𤭢'); // 4 byte
- assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
- }
-
- #[test]
- fn test_pop_char() {
- let mut data = StrBuf::from_str("ประเทศไทย中华b¢€𤭢");
- assert_eq!(data.pop_char().unwrap(), '𤭢'); // 4 bytes
- assert_eq!(data.pop_char().unwrap(), '€'); // 3 bytes
- assert_eq!(data.pop_char().unwrap(), '¢'); // 2 bytes
- assert_eq!(data.pop_char().unwrap(), 'b'); // 1 bytes
- assert_eq!(data.pop_char().unwrap(), '华');
- assert_eq!(data.as_slice(), "ประเทศไทย中");
- }
-
- #[test]
- fn test_shift_char() {
- let mut data = StrBuf::from_str("𤭢€¢b华ประเทศไทย中");
- assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
- assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
- assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
- assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
- assert_eq!(data.shift_char().unwrap(), '华');
- assert_eq!(data.as_slice(), "ประเทศไทย中");
- }
-
- #[test]
- fn test_str_truncate() {
- let mut s = StrBuf::from_str("12345");
- s.truncate(5);
- assert_eq!(s.as_slice(), "12345");
- s.truncate(3);
- assert_eq!(s.as_slice(), "123");
- s.truncate(0);
- assert_eq!(s.as_slice(), "");
-
- let mut s = StrBuf::from_str("12345");
- let p = s.as_slice().as_ptr();
- s.truncate(3);
- s.push_str("6");
- let p_ = s.as_slice().as_ptr();
- assert_eq!(p_, p);
- }
-
- #[test]
- #[should_fail]
- fn test_str_truncate_invalid_len() {
- let mut s = StrBuf::from_str("12345");
- s.truncate(6);
- }
-
- #[test]
- #[should_fail]
- fn test_str_truncate_split_codepoint() {
- let mut s = StrBuf::from_str("\u00FC"); // ü
- s.truncate(1);
- }
-
- #[test]
- fn test_str_clear() {
- let mut s = StrBuf::from_str("12345");
- s.clear();
- assert_eq!(s.len(), 0);
- assert_eq!(s.as_slice(), "");
- }
-}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! An owned, growable string that enforces that its contents are valid UTF-8.
+
+use c_vec::CVec;
+use char::Char;
+use cmp::Equiv;
+use container::{Container, Mutable};
+use default::Default;
+use fmt;
+use from_str::FromStr;
+use io::Writer;
+use iter::{Extendable, FromIterator, Iterator, range};
+use mem;
+use option::{None, Option, Some};
+use ptr::RawPtr;
+use ptr;
+use result::{Result, Ok, Err};
+use slice::Vector;
+use str::{CharRange, Str, StrSlice, StrAllocating};
+use str;
+use vec::Vec;
+
+/// A growable string stored as a UTF-8 encoded buffer.
+#[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
+pub struct String {
+ vec: Vec<u8>,
+}
+
+impl String {
+ /// Creates a new string buffer initialized with the empty string.
+ #[inline]
+ pub fn new() -> String {
+ String {
+ vec: Vec::new(),
+ }
+ }
+
+ /// Creates a new string buffer with the given capacity.
+ #[inline]
+ pub fn with_capacity(capacity: uint) -> String {
+ String {
+ vec: Vec::with_capacity(capacity),
+ }
+ }
+
+ /// Creates a new string buffer from length, capacity, and a pointer.
+ #[inline]
+ pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
+ String {
+ vec: Vec::from_raw_parts(length, capacity, ptr),
+ }
+ }
+
+ /// Creates a new string buffer from the given string.
+ #[inline]
+ pub fn from_str(string: &str) -> String {
+ String {
+ vec: Vec::from_slice(string.as_bytes())
+ }
+ }
+
+ /// Creates a new string buffer from the given owned string, taking care not to copy it.
+ #[inline]
+ pub fn from_owned_str(string: String) -> String {
+ string
+ }
+
+ /// Returns the vector as a string buffer, if possible, taking care not to
+ /// copy it.
+ ///
+ /// Returns `Err` with the original vector if the vector contains invalid
+ /// UTF-8.
+ #[inline]
+ pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
+ if str::is_utf8(vec.as_slice()) {
+ Ok(String { vec: vec })
+ } else {
+ Err(vec)
+ }
+ }
+
+ /// Return the underlying byte buffer, encoded as UTF-8.
+ #[inline]
+ pub fn into_bytes(self) -> Vec<u8> {
+ self.vec
+ }
+
+ /// Pushes the given string onto this buffer; then, returns `self` so that it can be used
+ /// again.
+ #[inline]
+ pub fn append(mut self, second: &str) -> String {
+ self.push_str(second);
+ self
+ }
+
+ /// Creates a string buffer by repeating a character `length` times.
+ #[inline]
+ pub fn from_char(length: uint, ch: char) -> String {
+ if length == 0 {
+ return String::new()
+ }
+
+ let mut buf = String::new();
+ buf.push_char(ch);
+ let size = buf.len() * length;
+ buf.reserve(size);
+ for _ in range(1, length) {
+ buf.push_char(ch)
+ }
+ buf
+ }
+
+ /// Pushes the given string onto this string buffer.
+ #[inline]
+ pub fn push_str(&mut self, string: &str) {
+ self.vec.push_all(string.as_bytes())
+ }
+
+ /// Push `ch` onto the given string `count` times.
+ #[inline]
+ pub fn grow(&mut self, count: uint, ch: char) {
+ for _ in range(0, count) {
+ self.push_char(ch)
+ }
+ }
+
+ /// Returns the number of bytes that this string buffer can hold without reallocating.
+ #[inline]
+ pub fn byte_capacity(&self) -> uint {
+ self.vec.capacity()
+ }
+
+ /// Reserves capacity for at least `extra` additional bytes in this string buffer.
+ #[inline]
+ pub fn reserve_additional(&mut self, extra: uint) {
+ self.vec.reserve_additional(extra)
+ }
+
+ /// Reserves capacity for at least `capacity` bytes in this string buffer.
+ #[inline]
+ pub fn reserve(&mut self, capacity: uint) {
+ self.vec.reserve(capacity)
+ }
+
+ /// Reserves capacity for exactly `capacity` bytes in this string buffer.
+ #[inline]
+ pub fn reserve_exact(&mut self, capacity: uint) {
+ self.vec.reserve_exact(capacity)
+ }
+
+ /// Shrinks the capacity of this string buffer to match its length.
+ #[inline]
+ pub fn shrink_to_fit(&mut self) {
+ self.vec.shrink_to_fit()
+ }
+
+ /// Adds the given character to the end of the string.
+ #[inline]
+ pub fn push_char(&mut self, ch: char) {
+ let cur_len = self.len();
+ unsafe {
+ // This may use up to 4 bytes.
+ self.vec.reserve_additional(4);
+
+ // Attempt to not use an intermediate buffer by just pushing bytes
+ // directly onto this string.
+ let mut c_vector = CVec::new(self.vec.as_mut_ptr().offset(cur_len as int), 4);
+ let used = ch.encode_utf8(c_vector.as_mut_slice());
+ self.vec.set_len(cur_len + used);
+ }
+ }
+
+ /// Pushes the given bytes onto this string buffer. This is unsafe because it does not check
+ /// to ensure that the resulting string will be valid UTF-8.
+ #[inline]
+ pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
+ self.vec.push_all(bytes)
+ }
+
+ /// Works with the underlying buffer as a byte slice.
+ #[inline]
+ pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
+ self.vec.as_slice()
+ }
+
+ /// Works with the underlying buffer as a mutable byte slice. Unsafe
+ /// because this can be used to violate the UTF-8 property.
+ #[inline]
+ pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
+ self.vec.as_mut_slice()
+ }
+
+ /// Shorten a string to the specified length (which must be <= the current length)
+ #[inline]
+ pub fn truncate(&mut self, len: uint) {
+ assert!(self.as_slice().is_char_boundary(len));
+ self.vec.truncate(len)
+ }
+
+ /// Appends a byte to this string buffer. The caller must preserve the valid UTF-8 property.
+ #[inline]
+ pub unsafe fn push_byte(&mut self, byte: u8) {
+ self.push_bytes([byte])
+ }
+
+ /// Removes the last byte from the string buffer and returns it. Returns `None` if this string
+ /// buffer is empty.
+ ///
+ /// The caller must preserve the valid UTF-8 property.
+ #[inline]
+ pub unsafe fn pop_byte(&mut self) -> Option<u8> {
+ let len = self.len();
+ if len == 0 {
+ return None
+ }
+
+ let byte = self.as_slice()[len - 1];
+ self.vec.set_len(len - 1);
+ Some(byte)
+ }
+
+ /// Removes the last character from the string buffer and returns it. Returns `None` if this
+ /// string buffer is empty.
+ #[inline]
+ pub fn pop_char(&mut self) -> Option<char> {
+ let len = self.len();
+ if len == 0 {
+ return None
+ }
+
+ let CharRange {ch, next} = self.as_slice().char_range_at_reverse(len);
+ unsafe {
+ self.vec.set_len(next);
+ }
+ Some(ch)
+ }
+
+ /// Removes the first byte from the string buffer and returns it. Returns `None` if this string
+ /// buffer is empty.
+ ///
+ /// The caller must preserve the valid UTF-8 property.
+ pub unsafe fn shift_byte(&mut self) -> Option<u8> {
+ self.vec.shift()
+ }
+
+ /// Removes the first character from the string buffer and returns it. Returns `None` if this
+ /// string buffer is empty.
+ ///
+ /// # Warning
+ ///
+ /// This is a O(n) operation as it requires copying every element in the buffer.
+ pub fn shift_char (&mut self) -> Option<char> {
+ let len = self.len();
+ if len == 0 {
+ return None
+ }
+
+ let CharRange {ch, next} = self.as_slice().char_range_at(0);
+ let new_len = len - next;
+ unsafe {
+ ptr::copy_memory(self.vec.as_mut_ptr(), self.vec.as_ptr().offset(next as int), new_len);
+ self.vec.set_len(new_len);
+ }
+ Some(ch)
+ }
+
+ /// Views the string buffer as a mutable sequence of bytes.
+ ///
+ /// Callers must preserve the valid UTF-8 property.
+ pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
+ &mut self.vec
+ }
+}
+
+impl Container for String {
+ #[inline]
+ fn len(&self) -> uint {
+ self.vec.len()
+ }
+}
+
+impl Mutable for String {
+ #[inline]
+ fn clear(&mut self) {
+ self.vec.clear()
+ }
+}
+
+impl FromIterator<char> for String {
+ fn from_iter<I:Iterator<char>>(iterator: I) -> String {
+ let mut buf = String::new();
+ buf.extend(iterator);
+ buf
+ }
+}
+
+impl Extendable<char> for String {
+ fn extend<I:Iterator<char>>(&mut self, mut iterator: I) {
+ for ch in iterator {
+ self.push_char(ch)
+ }
+ }
+}
+
+impl Str for String {
+ #[inline]
+ fn as_slice<'a>(&'a self) -> &'a str {
+ unsafe {
+ mem::transmute(self.vec.as_slice())
+ }
+ }
+}
+
+impl StrAllocating for String {
+ #[inline]
+ fn into_owned(self) -> String {
+ self
+ }
+
+ #[inline]
+ fn into_strbuf(self) -> String {
+ self
+ }
+}
+
+impl Default for String {
+ fn default() -> String {
+ String::new()
+ }
+}
+
+impl fmt::Show for String {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.as_slice().fmt(f)
+ }
+}
+
+impl<H:Writer> ::hash::Hash<H> for String {
+ #[inline]
+ fn hash(&self, hasher: &mut H) {
+ self.as_slice().hash(hasher)
+ }
+}
+
+impl<'a, S: Str> Equiv<S> for String {
+ #[inline]
+ fn equiv(&self, other: &S) -> bool {
+ self.as_slice() == other.as_slice()
+ }
+}
+
+impl FromStr for String {
+ #[inline]
+ fn from_str(s: &str) -> Option<String> {
+ Some(s.to_strbuf())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ extern crate test;
+ use container::{Container, Mutable};
+ use self::test::Bencher;
+ use str::{Str, StrSlice};
+ use super::String;
+
+ #[bench]
+ fn bench_with_capacity(b: &mut Bencher) {
+ b.iter(|| {
+ String::with_capacity(100)
+ });
+ }
+
+ #[bench]
+ fn bench_push_str(b: &mut Bencher) {
+ let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
+ b.iter(|| {
+ let mut r = String::new();
+ r.push_str(s);
+ });
+ }
+
+ #[test]
+ fn test_push_bytes() {
+ let mut s = String::from_str("ABC");
+ unsafe {
+ s.push_bytes([ 'D' as u8 ]);
+ }
+ assert_eq!(s.as_slice(), "ABCD");
+ }
+
+ #[test]
+ fn test_push_str() {
+ let mut s = String::new();
+ s.push_str("");
+ assert_eq!(s.as_slice().slice_from(0), "");
+ s.push_str("abc");
+ assert_eq!(s.as_slice().slice_from(0), "abc");
+ s.push_str("ประเทศไทย中华Việt Nam");
+ assert_eq!(s.as_slice().slice_from(0), "abcประเทศไทย中华Việt Nam");
+ }
+
+ #[test]
+ fn test_push_char() {
+ let mut data = String::from_str("ประเทศไทย中");
+ data.push_char('华');
+ data.push_char('b'); // 1 byte
+ data.push_char('¢'); // 2 byte
+ data.push_char('€'); // 3 byte
+ data.push_char('𤭢'); // 4 byte
+ assert_eq!(data.as_slice(), "ประเทศไทย中华b¢€𤭢");
+ }
+
+ #[test]
+ fn test_pop_char() {
+ let mut data = String::from_str("ประเทศไทย中华b¢€𤭢");
+ assert_eq!(data.pop_char().unwrap(), '𤭢'); // 4 bytes
+ assert_eq!(data.pop_char().unwrap(), '€'); // 3 bytes
+ assert_eq!(data.pop_char().unwrap(), '¢'); // 2 bytes
+ assert_eq!(data.pop_char().unwrap(), 'b'); // 1 bytes
+ assert_eq!(data.pop_char().unwrap(), '华');
+ assert_eq!(data.as_slice(), "ประเทศไทย中");
+ }
+
+ #[test]
+ fn test_shift_char() {
+ let mut data = String::from_str("𤭢€¢b华ประเทศไทย中");
+ assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
+ assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
+ assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
+ assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
+ assert_eq!(data.shift_char().unwrap(), '华');
+ assert_eq!(data.as_slice(), "ประเทศไทย中");
+ }
+
+ #[test]
+ fn test_str_truncate() {
+ let mut s = String::from_str("12345");
+ s.truncate(5);
+ assert_eq!(s.as_slice(), "12345");
+ s.truncate(3);
+ assert_eq!(s.as_slice(), "123");
+ s.truncate(0);
+ assert_eq!(s.as_slice(), "");
+
+ let mut s = String::from_str("12345");
+ let p = s.as_slice().as_ptr();
+ s.truncate(3);
+ s.push_str("6");
+ let p_ = s.as_slice().as_ptr();
+ assert_eq!(p_, p);
+ }
+
+ #[test]
+ #[should_fail]
+ fn test_str_truncate_invalid_len() {
+ let mut s = String::from_str("12345");
+ s.truncate(6);
+ }
+
+ #[test]
+ #[should_fail]
+ fn test_str_truncate_split_codepoint() {
+ let mut s = String::from_str("\u00FC"); // ü
+ s.truncate(1);
+ }
+
+ #[test]
+ fn test_str_clear() {
+ let mut s = String::from_str("12345");
+ s.clear();
+ assert_eq!(s.len(), 0);
+ assert_eq!(s.as_slice(), "");
+ }
+}
#[cfg(test)] use owned::AnyOwnExt;
#[cfg(test)] use result;
#[cfg(test)] use str::StrAllocating;
-#[cfg(test)] use strbuf::StrBuf;
+#[cfg(test)] use string::String;
/// Indicates the manner in which a task exited.
///
fail!("owned string".to_strbuf());
}) {
Err(e) => {
- type T = StrBuf;
+ type T = String;
assert!(e.is::<T>());
assert_eq!(*e.move::<T>().unwrap(), "owned string".to_strbuf());
}
*/
use fmt;
-use strbuf::StrBuf;
+use string::String;
/// A generic trait for converting a value to a string
pub trait ToStr {
/// Converts the value of `self` to an owned string
- fn to_str(&self) -> StrBuf;
+ fn to_str(&self) -> String;
}
/// Trait for converting a type to a string, consuming it in the process.
pub trait IntoStr {
/// Consume and convert to a string.
- fn into_str(self) -> StrBuf;
+ fn into_str(self) -> String;
}
impl<T: fmt::Show> ToStr for T {
- fn to_str(&self) -> StrBuf {
+ fn to_str(&self) -> String {
format_strbuf!("{}", *self)
}
}
use result::*;
use slice::{Vector,ImmutableVector};
use str;
-use strbuf::StrBuf;
+use string::String;
use vec::Vec;
pub struct DynamicLibrary { handle: *u8}
/// Lazily open a dynamic library. When passed None it gives a
/// handle to the calling process
pub fn open<T: ToCStr>(filename: Option<T>)
- -> Result<DynamicLibrary, StrBuf> {
+ -> Result<DynamicLibrary, String> {
unsafe {
let mut filename = filename;
let maybe_library = dl::check_for_errors_in(|| {
}
/// Access the value at the symbol of the dynamic library
- pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<T, StrBuf> {
+ pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<T, String> {
// This function should have a lifetime constraint of 'a on
// T but that feature is still unimplemented
use ptr;
use result::*;
use str::StrAllocating;
- use strbuf::StrBuf;
+ use string::String;
pub unsafe fn open_external<T: ToCStr>(filename: T) -> *u8 {
filename.with_c_str(|raw_name| {
dlopen(ptr::null(), Lazy as libc::c_int) as *u8
}
- pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, StrBuf> {
+ pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
unsafe {
use os;
use ptr;
use result::{Ok, Err, Result};
- use strbuf::StrBuf;
+ use string::String;
use str;
use c_str::ToCStr;
handle as *u8
}
- pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, StrBuf> {
+ pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
unsafe {
SetLastError(0);
/// ```rust
/// let v = vec!("a".to_owned(), "b".to_owned());
/// for s in v.move_iter() {
- /// // s has type StrBuf, not &StrBuf
+ /// // s has type String, not &String
/// println!("{}", s);
/// }
/// ```
assert_eq!(b.as_slice(), &[]);
let a = vec!["one".to_strbuf(), "two".to_strbuf()];
- let b: ~[StrBuf] = FromVec::from_vec(a);
+ let b: ~[String] = FromVec::from_vec(a);
assert_eq!(b.as_slice(), &["one".to_strbuf(), "two".to_strbuf()]);
struct Foo {
#[should_fail]
fn test_futurefail() {
let mut f = Future::spawn(proc() fail!());
- let _x: StrBuf = f.get();
+ let _x: String = f.get();
}
#[test]
use std::fmt;
use std::iter;
use std::slice;
-use std::strbuf::StrBuf;
+use std::string::String;
#[deriving(Clone, Eq)]
pub enum PathElem {
/// The type of the iterator used by with_path.
pub type PathElems<'a, 'b> = iter::Chain<Values<'a, PathElem>, LinkedPath<'b>>;
-pub fn path_to_str<PI: Iterator<PathElem>>(mut path: PI) -> StrBuf {
+pub fn path_to_str<PI: Iterator<PathElem>>(mut path: PI) -> String {
let itr = token::get_ident_interner();
- path.fold(StrBuf::new(), |mut s, e| {
+ path.fold(String::new(), |mut s, e| {
let e = itr.get(e.name());
if !s.is_empty() {
s.push_str("::");
self.with_path_next(id, None, f)
}
- pub fn path_to_str(&self, id: NodeId) -> StrBuf {
+ pub fn path_to_str(&self, id: NodeId) -> String {
self.with_path(id, |path| path_to_str(path))
}
- fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> StrBuf {
+ fn path_to_str_with_ident(&self, id: NodeId, i: Ident) -> String {
self.with_path(id, |path| {
path_to_str(path.chain(Some(PathName(i.name)).move_iter()))
})
.unwrap_or_else(|| fail!("AstMap.span: could not find span for id {}", id))
}
- pub fn node_to_str(&self, id: NodeId) -> StrBuf {
+ pub fn node_to_str(&self, id: NodeId) -> String {
node_id_to_str(self, id)
}
}
ii
}
-fn node_id_to_str(map: &Map, id: NodeId) -> StrBuf {
+fn node_id_to_str(map: &Map, id: NodeId) -> String {
match map.find(id) {
Some(NodeItem(item)) => {
let path_str = map.path_to_str_with_ident(id, item.ident);
use std::cell::Cell;
use std::cmp;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::u32;
-pub fn path_name_i(idents: &[Ident]) -> StrBuf {
+pub fn path_name_i(idents: &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
token::get_ident(*i).get().to_strbuf()
- }).collect::<Vec<StrBuf>>().connect("::").to_strbuf()
+ }).collect::<Vec<String>>().connect("::").to_strbuf()
}
// totally scary function: ignores all but the last element, should have
// Get a string representation of a signed int type, with its value.
// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
-pub fn int_ty_to_str(t: IntTy, val: Option<i64>, mode: SuffixMode) -> StrBuf {
+pub fn int_ty_to_str(t: IntTy, val: Option<i64>, mode: SuffixMode) -> String {
let s = match t {
TyI if val.is_some() => match mode {
AutoSuffix => "",
// Get a string representation of an unsigned int type, with its value.
// We want to avoid "42uint" in favor of "42u"
-pub fn uint_ty_to_str(t: UintTy, val: Option<u64>, mode: SuffixMode) -> StrBuf {
+pub fn uint_ty_to_str(t: UintTy, val: Option<u64>, mode: SuffixMode) -> String {
let s = match t {
TyU if val.is_some() => match mode {
AutoSuffix => "",
}
}
-pub fn float_ty_to_str(t: FloatTy) -> StrBuf {
+pub fn float_ty_to_str(t: FloatTy) -> String {
match t {
TyF32 => "f32".to_strbuf(),
TyF64 => "f64".to_strbuf(),
use serialize::{Encodable, Decodable, Encoder, Decoder};
use std::cell::RefCell;
use std::rc::Rc;
-use std::strbuf::StrBuf;
+use std::string::String;
pub trait Pos {
fn from_uint(n: uint) -> Self;
pub struct NameAndSpan {
/// The name of the macro that was invoked to create the thing
/// with this Span.
- pub name: StrBuf,
+ pub name: String,
/// The format with which the macro was invoked.
pub format: MacroFormat,
/// The span of the macro definition itself. The macro may not
pub callee: NameAndSpan
}
-pub type FileName = StrBuf;
+pub type FileName = String;
pub struct FileLines {
pub file: Rc<FileMap>,
/// e.g. `<anon>`
pub name: FileName,
/// The complete source code
- pub src: StrBuf,
+ pub src: String,
/// The start position of this source in the CodeMap
pub start_pos: BytePos,
/// Locations of lines beginnings in the source code
}
// get a line from the list of pre-computed line-beginnings
- pub fn get_line(&self, line: int) -> StrBuf {
+ pub fn get_line(&self, line: int) -> String {
let mut lines = self.lines.borrow_mut();
let begin: BytePos = *lines.get(line as uint) - self.start_pos;
let begin = begin.to_uint();
}
}
- pub fn new_filemap(&self, filename: FileName, src: StrBuf) -> Rc<FileMap> {
+ pub fn new_filemap(&self, filename: FileName, src: String) -> Rc<FileMap> {
let mut files = self.files.borrow_mut();
let start_pos = match files.last() {
None => 0,
// FIXME #12884: no efficient/safe way to remove from the start of a string
// and reuse the allocation.
let mut src = if src.as_slice().starts_with("\ufeff") {
- StrBuf::from_str(src.as_slice().slice_from(3))
+ String::from_str(src.as_slice().slice_from(3))
} else {
- StrBuf::from_str(src.as_slice())
+ String::from_str(src.as_slice())
};
// Append '\n' in case it's not already there.
filemap
}
- pub fn mk_substr_filename(&self, sp: Span) -> StrBuf {
+ pub fn mk_substr_filename(&self, sp: Span) -> String {
let pos = self.lookup_char_pos(sp.lo);
(format!("<{}:{}:{}>",
pos.file.name,
}
}
- pub fn span_to_str(&self, sp: Span) -> StrBuf {
+ pub fn span_to_str(&self, sp: Span) -> String {
if self.files.borrow().len() == 0 && sp == DUMMY_SP {
return "no-location".to_strbuf();
}
FileLines {file: lo.file, lines: lines}
}
- pub fn span_to_snippet(&self, sp: Span) -> Option<StrBuf> {
+ pub fn span_to_snippet(&self, sp: Span) -> Option<String> {
let begin = self.lookup_byte_offset(sp.lo);
let end = self.lookup_byte_offset(sp.hi);
pub struct CrateId {
/// A path which represents the codes origin. By convention this is the
/// URL, without `http://` or `https://` prefix, to the crate's repository
- pub path: StrBuf,
+ pub path: String,
/// The name of the crate.
- pub name: StrBuf,
+ pub name: String,
/// The version of the crate.
- pub version: Option<StrBuf>,
+ pub version: Option<String>,
}
impl fmt::Show for CrateId {
}
}
- pub fn short_name_with_version(&self) -> StrBuf {
+ pub fn short_name_with_version(&self) -> String {
(format!("{}-{}", self.name, self.version_or_default())).to_strbuf()
}
use std::fmt;
use std::io;
use std::iter::range;
-use std::strbuf::StrBuf;
+use std::string::String;
use term;
// maximum number of lines we will print for each error; arbitrary.
// indent past |name:## | and the 0-offset column location
let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
- let mut s = StrBuf::new();
+ let mut s = String::new();
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line ' part of the previous line.
let skip = fm.name.len() + digits + 3u;
};
}
try!(write!(&mut err.dst, "{}", s));
- let mut s = StrBuf::from_str("^");
+ let mut s = String::from_str("^");
let hi = cm.lookup_char_pos(sp.hi);
if hi.col != lo.col {
// the ^ already takes up one space
let hi = cm.lookup_char_pos(sp.hi);
// Span seems to use half-opened interval, so subtract 1
let skip = last_line_start.len() + hi.col.to_uint() - 1;
- let mut s = StrBuf::new();
+ let mut s = String::new();
for _ in range(0, skip) {
s.push_char(' ');
}
Ok(())
}
-pub fn expect<T:Clone>(diag: &SpanHandler, opt: Option<T>, msg: || -> StrBuf)
+pub fn expect<T:Clone>(diag: &SpanHandler, opt: Option<T>, msg: || -> String)
-> T {
match opt {
Some(ref t) => (*t).clone(),
// ast::MacInvocTT.
pub struct MacroDef {
- pub name: StrBuf,
+ pub name: String,
pub ext: SyntaxExtension
}
pub struct MacroCrate {
pub lib: Option<Path>,
- pub macros: Vec<StrBuf>,
- pub registrar_symbol: Option<StrBuf>,
+ pub macros: Vec<String>,
+ pub registrar_symbol: Option<String>,
}
pub trait CrateLoader {
sp: Span,
tts: &[ast::TokenTree],
name: &str)
- -> Option<StrBuf> {
+ -> Option<String> {
if tts.len() != 1 {
cx.span_err(sp, format!("{} takes 1 argument.", name).as_slice());
} else {
use ext::build::AstBuilder;
use parse::token;
-use std::strbuf::StrBuf;
+use std::string::String;
pub fn expand_syntax_ext(cx: &mut base::ExtCtxt,
sp: codemap::Span,
Some(e) => e,
None => return base::DummyResult::expr(sp)
};
- let mut accumulator = StrBuf::new();
+ let mut accumulator = String::new();
for e in es.move_iter() {
match e.node {
ast::ExprLit(lit) => {
use parse::token;
use parse::token::{str_to_ident};
-use std::strbuf::StrBuf;
+use std::string::String;
pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult> {
- let mut res_str = StrBuf::new();
+ let mut res_str = String::new();
for (i, e) in tts.iter().enumerate() {
if i & 1 == 1 {
match *e {
use parse::token;
use collections::HashMap;
-use std::strbuf::StrBuf;
+use std::string::String;
pub fn expand_deriving_show(cx: &mut ExtCtxt,
span: Span,
}
};
- let mut format_string = StrBuf::from_str(token::get_ident(name).get());
+ let mut format_string = String::from_str(token::get_ident(name).get());
// the internal fields we're actually formatting
let mut exprs = Vec::new();
}
}
- fn expand_crate_str(crate_str: StrBuf) -> ast::Crate {
+ fn expand_crate_str(crate_str: String) -> ast::Crate {
let ps = parse::new_parse_sess();
let crate_ast = string_to_parser(&ps, crate_str).parse_crate_mod();
// the cfg argument actually does matter, here...
// println!("expanded: {:?}\n",expanded_ast);
//mtwt_resolve_crate(expanded_ast)
//}
- //fn expand_and_resolve_and_pretty_print (crate_str: @str) -> StrBuf {
+ //fn expand_and_resolve_and_pretty_print (crate_str: @str) -> String {
//let resolved_ast = expand_and_resolve(crate_str);
//pprust::to_str(&resolved_ast,fake_print_crate,get_ident_interner())
//}
#[deriving(Eq)]
enum ArgumentType {
- Known(StrBuf),
+ Known(String),
Unsigned,
String,
}
enum Position {
Exact(uint),
- Named(StrBuf),
+ Named(String),
}
struct Context<'a, 'b> {
// Note that we keep a side-array of the ordering of the named arguments
// found to be sure that we can translate them in the same order that they
// were declared in.
- names: HashMap<StrBuf, @ast::Expr>,
- name_types: HashMap<StrBuf, ArgumentType>,
- name_ordering: Vec<StrBuf>,
+ names: HashMap<String, @ast::Expr>,
+ name_types: HashMap<String, ArgumentType>,
+ name_ordering: Vec<String>,
// Collection of the compiled `rt::Piece` structures
pieces: Vec<@ast::Expr> ,
- name_positions: HashMap<StrBuf, uint>,
+ name_positions: HashMap<String, uint>,
method_statics: Vec<@ast::Item> ,
// Updated as arguments are consumed or methods are entered
/// named arguments))
fn parse_args(ecx: &mut ExtCtxt, sp: Span, allow_method: bool,
tts: &[ast::TokenTree])
- -> (Invocation, Option<(@ast::Expr, Vec<@ast::Expr>, Vec<StrBuf>,
- HashMap<StrBuf, @ast::Expr>)>) {
+ -> (Invocation, Option<(@ast::Expr, Vec<@ast::Expr>, Vec<String>,
+ HashMap<String, @ast::Expr>)>) {
let mut args = Vec::new();
- let mut names = HashMap::<StrBuf, @ast::Expr>::new();
+ let mut names = HashMap::<String, @ast::Expr>::new();
let mut order = Vec::new();
let mut p = rsparse::new_parser_from_tts(ecx.parse_sess(),
pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span,
invocation: Invocation,
efmt: @ast::Expr, args: Vec<@ast::Expr>,
- name_ordering: Vec<StrBuf>,
- names: HashMap<StrBuf, @ast::Expr>) -> @ast::Expr {
+ name_ordering: Vec<String>,
+ names: HashMap<String, @ast::Expr>) -> @ast::Expr {
let arg_types = Vec::from_fn(args.len(), |_| None);
let mut cx = Context {
ecx: ecx,
trait ToSource : ToTokens {
// Takes a thing and generates a string containing rust code for it.
- pub fn to_source() -> StrBuf;
+ pub fn to_source() -> String;
// If you can make source, you can definitely make tokens.
pub fn to_tokens(cx: &ExtCtxt) -> ~[TokenTree] {
pub trait ToSource {
// Takes a thing and generates a string containing rust code for it.
- fn to_source(&self) -> StrBuf;
+ fn to_source(&self) -> String;
}
impl ToSource for ast::Ident {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
get_ident(*self).get().to_strbuf()
}
}
impl ToSource for @ast::Item {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
pprust::item_to_str(*self)
}
}
impl<'a> ToSource for &'a [@ast::Item] {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
self.iter()
.map(|i| i.to_source())
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.connect("\n\n")
.to_strbuf()
}
}
impl ToSource for ast::Ty {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
pprust::ty_to_str(self)
}
}
impl<'a> ToSource for &'a [ast::Ty] {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
self.iter()
.map(|i| i.to_source())
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.connect(", ")
.to_strbuf()
}
}
impl ToSource for Generics {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
pprust::generics_to_str(self)
}
}
impl ToSource for @ast::Expr {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
pprust::expr_to_str(*self)
}
}
impl ToSource for ast::Block {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
pprust::block_to_str(self)
}
}
impl<'a> ToSource for &'a str {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitStr(
token::intern_and_get_ident(*self), ast::CookedStr));
pprust::lit_to_str(&lit)
}
impl ToSource for () {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
"()".to_strbuf()
}
}
impl ToSource for bool {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitBool(*self));
pprust::lit_to_str(&lit)
}
}
impl ToSource for char {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitChar(*self));
pprust::lit_to_str(&lit)
}
}
impl ToSource for int {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI));
pprust::lit_to_str(&lit)
}
}
impl ToSource for i8 {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI8));
pprust::lit_to_str(&lit)
}
}
impl ToSource for i16 {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI16));
pprust::lit_to_str(&lit)
}
impl ToSource for i32 {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI32));
pprust::lit_to_str(&lit)
}
}
impl ToSource for i64 {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitInt(*self as i64, ast::TyI64));
pprust::lit_to_str(&lit)
}
}
impl ToSource for uint {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU));
pprust::lit_to_str(&lit)
}
}
impl ToSource for u8 {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU8));
pprust::lit_to_str(&lit)
}
}
impl ToSource for u16 {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU16));
pprust::lit_to_str(&lit)
}
}
impl ToSource for u32 {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU32));
pprust::lit_to_str(&lit)
}
}
impl ToSource for u64 {
- fn to_source(&self) -> StrBuf {
+ fn to_source(&self) -> String {
let lit = dummy_spanned(ast::LitUint(*self as u64, ast::TyU64));
pprust::lit_to_str(&lit)
}
impl_to_tokens!(u64)
pub trait ExtParseUtils {
- fn parse_item(&self, s: StrBuf) -> @ast::Item;
- fn parse_expr(&self, s: StrBuf) -> @ast::Expr;
- fn parse_stmt(&self, s: StrBuf) -> @ast::Stmt;
- fn parse_tts(&self, s: StrBuf) -> Vec<ast::TokenTree> ;
+ fn parse_item(&self, s: String) -> @ast::Item;
+ fn parse_expr(&self, s: String) -> @ast::Expr;
+ fn parse_stmt(&self, s: String) -> @ast::Stmt;
+ fn parse_tts(&self, s: String) -> Vec<ast::TokenTree> ;
}
impl<'a> ExtParseUtils for ExtCtxt<'a> {
- fn parse_item(&self, s: StrBuf) -> @ast::Item {
+ fn parse_item(&self, s: String) -> @ast::Item {
let res = parse::parse_item_from_source_str(
"<quote expansion>".to_strbuf(),
s,
}
}
- fn parse_stmt(&self, s: StrBuf) -> @ast::Stmt {
+ fn parse_stmt(&self, s: String) -> @ast::Stmt {
parse::parse_stmt_from_source_str("<quote expansion>".to_strbuf(),
s,
self.cfg(),
self.parse_sess())
}
- fn parse_expr(&self, s: StrBuf) -> @ast::Expr {
+ fn parse_expr(&self, s: String) -> @ast::Expr {
parse::parse_expr_from_source_str("<quote expansion>".to_strbuf(),
s,
self.cfg(),
self.parse_sess())
}
- fn parse_tts(&self, s: StrBuf) -> Vec<ast::TokenTree> {
+ fn parse_tts(&self, s: String) -> Vec<ast::TokenTree> {
parse::parse_tts_from_source_str("<quote expansion>".to_strbuf(),
s,
self.cfg(),
base::MacExpr::new(expanded)
}
-fn ids_ext(strs: Vec<StrBuf> ) -> Vec<ast::Ident> {
+fn ids_ext(strs: Vec<String> ) -> Vec<ast::Ident> {
strs.iter().map(|str| str_to_ident((*str).as_slice())).collect()
}
let string = cx.mod_path()
.iter()
.map(|x| token::get_ident(*x).get().to_strbuf())
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.connect("::");
base::MacExpr::new(cx.expr_str(
sp,
pub enum ParseResult {
Success(HashMap<Ident, Rc<NamedMatch>>),
- Failure(codemap::Span, StrBuf),
- Error(codemap::Span, StrBuf)
+ Failure(codemap::Span, String),
+ Error(codemap::Span, String)
}
pub fn parse_or_else(sess: &ParseSess,
token::get_ident(bind))).to_strbuf()
}
_ => fail!()
- } }).collect::<Vec<StrBuf>>().connect(" or ");
+ } }).collect::<Vec<String>>().connect(" or ");
return Error(sp, format!(
"local ambiguity: multiple parsing options: \
built-in NTs {} or {} other options.",
enum LockstepIterSize {
LisUnconstrained,
LisConstraint(uint, Ident),
- LisContradiction(StrBuf),
+ LisContradiction(String),
}
fn lis_merge(lhs: LockstepIterSize, rhs: LockstepIterSize) -> LockstepIterSize {
use std::io;
use std::str;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::uint;
#[deriving(Clone, Eq)]
#[deriving(Clone)]
pub struct Comment {
pub style: CommentStyle,
- pub lines: Vec<StrBuf>,
+ pub lines: Vec<String>,
pub pos: BytePos,
}
}
}
-pub fn strip_doc_comment_decoration(comment: &str) -> StrBuf {
+pub fn strip_doc_comment_decoration(comment: &str) -> String {
/// remove whitespace-only lines from the start/end of lines
- fn vertical_trim(lines: Vec<StrBuf> ) -> Vec<StrBuf> {
+ fn vertical_trim(lines: Vec<String> ) -> Vec<String> {
let mut i = 0u;
let mut j = lines.len();
// first line of all-stars should be omitted
}
/// remove a "[ \t]*\*" block from each line, if possible
- fn horizontal_trim(lines: Vec<StrBuf> ) -> Vec<StrBuf> {
+ fn horizontal_trim(lines: Vec<String> ) -> Vec<String> {
let mut i = uint::MAX;
let mut can_trim = true;
let mut first = true;
let lines = comment.slice(3u, comment.len() - 2u)
.lines_any()
.map(|s| s.to_strbuf())
- .collect::<Vec<StrBuf> >();
+ .collect::<Vec<String> >();
let lines = vertical_trim(lines);
let lines = horizontal_trim(lines);
fail!("not a doc-comment: {}", comment);
}
-fn read_to_eol(rdr: &mut StringReader) -> StrBuf {
- let mut val = StrBuf::new();
+fn read_to_eol(rdr: &mut StringReader) -> String {
+ let mut val = String::new();
while !rdr.curr_is('\n') && !is_eof(rdr) {
val.push_char(rdr.curr.unwrap());
bump(rdr);
return val
}
-fn read_one_line_comment(rdr: &mut StringReader) -> StrBuf {
+fn read_one_line_comment(rdr: &mut StringReader) -> String {
let val = read_to_eol(rdr);
assert!((val.as_slice()[0] == '/' as u8 &&
val.as_slice()[1] == '/' as u8) ||
comments: &mut Vec<Comment>) {
debug!(">>> line comments");
let p = rdr.last_pos;
- let mut lines: Vec<StrBuf> = Vec::new();
+ let mut lines: Vec<String> = Vec::new();
while rdr.curr_is('/') && nextch_is(rdr, '/') {
let line = read_one_line_comment(rdr);
debug!("{}", line);
return Some(cursor);
}
-fn trim_whitespace_prefix_and_push_line(lines: &mut Vec<StrBuf> ,
- s: StrBuf, col: CharPos) {
+fn trim_whitespace_prefix_and_push_line(lines: &mut Vec<String> ,
+ s: String, col: CharPos) {
let len = s.len();
let s1 = match all_whitespace(s.as_slice(), col) {
Some(col) => {
comments: &mut Vec<Comment> ) {
debug!(">>> block comment");
let p = rdr.last_pos;
- let mut lines: Vec<StrBuf> = Vec::new();
+ let mut lines: Vec<String> = Vec::new();
let col = rdr.col;
bump(rdr);
bump(rdr);
- let mut curr_line = StrBuf::from_str("/*");
+ let mut curr_line = String::from_str("/*");
// doc-comments are not really comments, they are attributes
if (rdr.curr_is('*') && !nextch_is(rdr, '*')) || rdr.curr_is('!') {
trim_whitespace_prefix_and_push_line(&mut lines,
curr_line,
col);
- curr_line = StrBuf::new();
+ curr_line = String::new();
bump(rdr);
} else {
curr_line.push_char(rdr.curr.unwrap());
#[deriving(Clone)]
pub struct Literal {
- pub lit: StrBuf,
+ pub lit: String,
pub pos: BytePos,
}
// probably not a good thing.
pub fn gather_comments_and_literals(span_diagnostic:
&diagnostic::SpanHandler,
- path: StrBuf,
+ path: String,
srdr: &mut io::Reader)
-> (Vec<Comment>, Vec<Literal>) {
let src = srdr.read_to_end().unwrap();
if res.is_some() { res } else { consume_whitespace_and_comments(rdr) }
}
-fn scan_exponent(rdr: &mut StringReader, start_bpos: BytePos) -> Option<StrBuf> {
+fn scan_exponent(rdr: &mut StringReader, start_bpos: BytePos) -> Option<String> {
// \x00 hits the `return None` case immediately, so this is fine.
let mut c = rdr.curr.unwrap_or('\x00');
- let mut rslt = StrBuf::new();
+ let mut rslt = String::new();
if c == 'e' || c == 'E' {
rslt.push_char(c);
bump(rdr);
}
}
-fn scan_digits(rdr: &mut StringReader, radix: uint) -> StrBuf {
- let mut rslt = StrBuf::new();
+fn scan_digits(rdr: &mut StringReader, radix: uint) -> String {
+ let mut rslt = String::new();
loop {
let c = rdr.curr;
if c == Some('_') { bump(rdr); continue; }
return token::LIT_CHAR(c2);
}
'"' => {
- let mut accum_str = StrBuf::new();
+ let mut accum_str = String::new();
let start_bpos = rdr.last_pos;
bump(rdr);
while !rdr.curr_is('"') {
// open a string reader for the given string
fn setup<'a>(span_handler: &'a diagnostic::SpanHandler,
- teststr: StrBuf) -> StringReader<'a> {
+ teststr: String) -> StringReader<'a> {
let fm = span_handler.cm.new_filemap("zebra.rs".to_strbuf(), teststr);
new_string_reader(span_handler, fm)
}
inner
}
-pub fn parse_crate_from_source_str(name: StrBuf,
- source: StrBuf,
+pub fn parse_crate_from_source_str(name: String,
+ source: String,
cfg: ast::CrateConfig,
sess: &ParseSess)
-> ast::Crate {
maybe_aborted(p.parse_crate_mod(),p)
}
-pub fn parse_crate_attrs_from_source_str(name: StrBuf,
- source: StrBuf,
+pub fn parse_crate_attrs_from_source_str(name: String,
+ source: String,
cfg: ast::CrateConfig,
sess: &ParseSess)
-> Vec<ast::Attribute> {
inner
}
-pub fn parse_expr_from_source_str(name: StrBuf,
- source: StrBuf,
+pub fn parse_expr_from_source_str(name: String,
+ source: String,
cfg: ast::CrateConfig,
sess: &ParseSess)
-> @ast::Expr {
maybe_aborted(p.parse_expr(), p)
}
-pub fn parse_item_from_source_str(name: StrBuf,
- source: StrBuf,
+pub fn parse_item_from_source_str(name: String,
+ source: String,
cfg: ast::CrateConfig,
sess: &ParseSess)
-> Option<@ast::Item> {
maybe_aborted(p.parse_item(attrs),p)
}
-pub fn parse_meta_from_source_str(name: StrBuf,
- source: StrBuf,
+pub fn parse_meta_from_source_str(name: String,
+ source: String,
cfg: ast::CrateConfig,
sess: &ParseSess)
-> @ast::MetaItem {
maybe_aborted(p.parse_meta_item(),p)
}
-pub fn parse_stmt_from_source_str(name: StrBuf,
- source: StrBuf,
+pub fn parse_stmt_from_source_str(name: String,
+ source: String,
cfg: ast::CrateConfig,
attrs: Vec<ast::Attribute> ,
sess: &ParseSess)
maybe_aborted(p.parse_stmt(attrs),p)
}
-pub fn parse_tts_from_source_str(name: StrBuf,
- source: StrBuf,
+pub fn parse_tts_from_source_str(name: String,
+ source: String,
cfg: ast::CrateConfig,
sess: &ParseSess)
-> Vec<ast::TokenTree> {
// Create a new parser from a source string
pub fn new_parser_from_source_str<'a>(sess: &'a ParseSess,
cfg: ast::CrateConfig,
- name: StrBuf,
- source: StrBuf)
+ name: String,
+ source: String)
-> Parser<'a> {
filemap_to_parser(sess, string_to_filemap(sess, source, name), cfg)
}
cfg: ast::CrateConfig,
path: &Path,
owns_directory: bool,
- module_name: Option<StrBuf>,
+ module_name: Option<String>,
sp: Span) -> Parser<'a> {
let mut p = filemap_to_parser(sess, file_to_filemap(sess, path, Some(sp)), cfg);
p.owns_directory = owns_directory;
// given a session and a string, add the string to
// the session's codemap and return the new filemap
-pub fn string_to_filemap(sess: &ParseSess, source: StrBuf, path: StrBuf)
+pub fn string_to_filemap(sess: &ParseSess, source: String, path: String)
-> Rc<FileMap> {
sess.span_diagnostic.cm.new_filemap(path, source)
}
use util::parser_testing::{string_to_expr, string_to_item};
use util::parser_testing::string_to_stmt;
- fn to_json_str<'a, E: Encodable<json::Encoder<'a>, io::IoError>>(val: &E) -> StrBuf {
+ fn to_json_str<'a, E: Encodable<json::Encoder<'a>, io::IoError>>(val: &E) -> String {
let mut writer = MemWriter::new();
let mut encoder = json::Encoder::new(&mut writer as &mut io::Writer);
let _ = val.encode(&mut encoder);
#[test] fn attrs_fix_bug () {
string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
- -> Result<@Writer, StrBuf> {
+ -> Result<@Writer, String> {
#[cfg(windows)]
fn wb() -> c_int {
(O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
use collections::HashSet;
use std::mem::replace;
use std::rc::Rc;
-use std::strbuf::StrBuf;
+use std::string::String;
#[allow(non_camel_case_types)]
#[deriving(Eq)]
/// Name of the root module this parser originated from. If `None`, then the
/// name is not known. This does not change while the parser is descending
/// into modules, and sub-parsers have new values for this name.
- pub root_module_name: Option<StrBuf>,
+ pub root_module_name: Option<String>,
}
fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
impl<'a> Parser<'a> {
// convert a token to a string using self's reader
- pub fn token_to_str(token: &token::Token) -> StrBuf {
+ pub fn token_to_str(token: &token::Token) -> String {
token::to_str(token)
}
// convert the current token to a string using self's reader
- pub fn this_token_to_str(&mut self) -> StrBuf {
+ pub fn this_token_to_str(&mut self) -> String {
Parser::token_to_str(&self.token)
}
pub fn expect_one_of(&mut self,
edible: &[token::Token],
inedible: &[token::Token]) {
- fn tokens_to_str(tokens: &[token::Token]) -> StrBuf {
+ fn tokens_to_str(tokens: &[token::Token]) -> String {
let mut i = tokens.iter();
// This might be a sign we need a connect method on Iterator.
let b = i.next()
(ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
}
- // parse a::B<StrBuf,int>
+ // parse a::B<String,int>
fn parse_trait_ref(&mut self) -> TraitRef {
ast::TraitRef {
path: self.parse_path(LifetimeAndTypesWithoutColons).path,
}
}
- // parse B + C<StrBuf,int> + D
+ // parse B + C<String,int> + D
fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
self.parse_seq_to_before_end(
ket,
fn eval_src_mod_from_path(&mut self,
path: Path,
owns_directory: bool,
- name: StrBuf,
+ name: String,
id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
match included_mod_stack.iter().position(|p| *p == path) {
Some(i) => {
- let mut err = StrBuf::from_str("circular modules: ");
+ let mut err = String::from_str("circular modules: ");
let len = included_mod_stack.len();
for p in included_mod_stack.slice(i, len).iter() {
err.push_str(p.display().as_maybe_owned().as_slice());
// FAILURE TO PARSE ITEM
if visibility != Inherited {
- let mut s = StrBuf::from_str("unmatched visibility `");
+ let mut s = String::from_str("unmatched visibility `");
if visibility == Public {
s.push_str("pub")
} else {
use std::path::BytesContainer;
use std::mem;
use std::rc::Rc;
-use std::strbuf::StrBuf;
+use std::string::String;
#[allow(non_camel_case_types)]
#[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash, Show)]
}
}
-pub fn binop_to_str(o: BinOp) -> StrBuf {
+pub fn binop_to_str(o: BinOp) -> String {
match o {
PLUS => "+".to_strbuf(),
MINUS => "-".to_strbuf(),
}
}
-pub fn to_str(t: &Token) -> StrBuf {
+pub fn to_str(t: &Token) -> String {
match *t {
EQ => "=".to_strbuf(),
LT => "<".to_strbuf(),
/* Literals */
LIT_CHAR(c) => {
- let mut res = StrBuf::from_str("'");
+ let mut res = String::from_str("'");
c.escape_default(|c| {
res.push_char(c);
});
ast_util::ForceSuffix),
LIT_INT_UNSUFFIXED(i) => { (i as u64).to_str().to_strbuf() }
LIT_FLOAT(s, t) => {
- let mut body = StrBuf::from_str(get_ident(s).get());
+ let mut body = String::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
body
}
LIT_FLOAT_UNSUFFIXED(s) => {
- let mut body = StrBuf::from_str(get_ident(s).get());
+ let mut body = String::from_str(get_ident(s).get());
if body.as_slice().ends_with(".") {
body.push_char('0'); // `10.f` is not a float literal
}
*/
use std::io;
-use std::strbuf::StrBuf;
+use std::string::String;
#[deriving(Clone, Eq)]
pub enum Breaks {
#[deriving(Clone)]
pub enum Token {
- String(StrBuf, int),
+ String(String, int),
Break(BreakToken),
Begin(BeginToken),
End,
}
}
-pub fn tok_str(t: Token) -> StrBuf {
+pub fn tok_str(t: Token) -> String {
match t {
String(s, len) => return format!("STR({},{})", s, len).to_strbuf(),
Break(_) => return "BREAK".to_strbuf(),
left: uint,
right: uint,
lim: uint)
- -> StrBuf {
+ -> String {
let n = toks.len();
assert_eq!(n, szs.len());
let mut i = left;
let mut l = lim;
- let mut s = StrBuf::from_str("[");
+ let mut s = String::from_str("[");
while i != right && l != 0u {
l -= 1u;
if i != left {
use std::mem;
use std::rc::Rc;
use std::str;
-use std::strbuf::StrBuf;
+use std::string::String;
pub enum AnnNode<'a> {
NodeBlock(&'a ast::Block),
pub fn print_crate<'a>(cm: &'a CodeMap,
span_diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate,
- filename: StrBuf,
+ filename: String,
input: &mut io::Reader,
out: Box<io::Writer>,
ann: &'a PpAnn,
eof(&mut s.s)
}
-pub fn to_str(f: |&mut State| -> IoResult<()>) -> StrBuf {
+pub fn to_str(f: |&mut State| -> IoResult<()>) -> String {
let mut s = rust_printer(box MemWriter::new());
f(&mut s).unwrap();
eof(&mut s.s).unwrap();
}
}
-pub fn ty_to_str(ty: &ast::Ty) -> StrBuf {
+pub fn ty_to_str(ty: &ast::Ty) -> String {
to_str(|s| s.print_type(ty))
}
-pub fn pat_to_str(pat: &ast::Pat) -> StrBuf {
+pub fn pat_to_str(pat: &ast::Pat) -> String {
to_str(|s| s.print_pat(pat))
}
-pub fn expr_to_str(e: &ast::Expr) -> StrBuf {
+pub fn expr_to_str(e: &ast::Expr) -> String {
to_str(|s| s.print_expr(e))
}
-pub fn lifetime_to_str(e: &ast::Lifetime) -> StrBuf {
+pub fn lifetime_to_str(e: &ast::Lifetime) -> String {
to_str(|s| s.print_lifetime(e))
}
-pub fn tt_to_str(tt: &ast::TokenTree) -> StrBuf {
+pub fn tt_to_str(tt: &ast::TokenTree) -> String {
to_str(|s| s.print_tt(tt))
}
-pub fn tts_to_str(tts: &[ast::TokenTree]) -> StrBuf {
+pub fn tts_to_str(tts: &[ast::TokenTree]) -> String {
to_str(|s| s.print_tts(tts))
}
-pub fn stmt_to_str(stmt: &ast::Stmt) -> StrBuf {
+pub fn stmt_to_str(stmt: &ast::Stmt) -> String {
to_str(|s| s.print_stmt(stmt))
}
-pub fn item_to_str(i: &ast::Item) -> StrBuf {
+pub fn item_to_str(i: &ast::Item) -> String {
to_str(|s| s.print_item(i))
}
-pub fn generics_to_str(generics: &ast::Generics) -> StrBuf {
+pub fn generics_to_str(generics: &ast::Generics) -> String {
to_str(|s| s.print_generics(generics))
}
-pub fn ty_method_to_str(p: &ast::TypeMethod) -> StrBuf {
+pub fn ty_method_to_str(p: &ast::TypeMethod) -> String {
to_str(|s| s.print_ty_method(p))
}
-pub fn method_to_str(p: &ast::Method) -> StrBuf {
+pub fn method_to_str(p: &ast::Method) -> String {
to_str(|s| s.print_method(p))
}
-pub fn fn_block_to_str(p: &ast::FnDecl) -> StrBuf {
+pub fn fn_block_to_str(p: &ast::FnDecl) -> String {
to_str(|s| s.print_fn_block_args(p))
}
-pub fn path_to_str(p: &ast::Path) -> StrBuf {
+pub fn path_to_str(p: &ast::Path) -> String {
to_str(|s| s.print_path(p, false))
}
pub fn fun_to_str(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
opt_explicit_self: Option<ast::ExplicitSelf_>,
- generics: &ast::Generics) -> StrBuf {
+ generics: &ast::Generics) -> String {
to_str(|s| {
try!(s.print_fn(decl, Some(fn_style), abi::Rust,
name, generics, opt_explicit_self, ast::Inherited));
})
}
-pub fn block_to_str(blk: &ast::Block) -> StrBuf {
+pub fn block_to_str(blk: &ast::Block) -> String {
to_str(|s| {
// containing cbox, will be closed by print-block at }
try!(s.cbox(indent_unit));
})
}
-pub fn meta_item_to_str(mi: &ast::MetaItem) -> StrBuf {
+pub fn meta_item_to_str(mi: &ast::MetaItem) -> String {
to_str(|s| s.print_meta_item(mi))
}
-pub fn attribute_to_str(attr: &ast::Attribute) -> StrBuf {
+pub fn attribute_to_str(attr: &ast::Attribute) -> String {
to_str(|s| s.print_attribute(attr))
}
-pub fn lit_to_str(l: &ast::Lit) -> StrBuf {
+pub fn lit_to_str(l: &ast::Lit) -> String {
to_str(|s| s.print_literal(l))
}
-pub fn explicit_self_to_str(explicit_self: ast::ExplicitSelf_) -> StrBuf {
+pub fn explicit_self_to_str(explicit_self: ast::ExplicitSelf_) -> String {
to_str(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
}
-pub fn variant_to_str(var: &ast::Variant) -> StrBuf {
+pub fn variant_to_str(var: &ast::Variant) -> String {
to_str(|s| s.print_variant(var))
}
-pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> StrBuf {
+pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
match vis {
ast::Public => format!("pub {}", s).to_strbuf(),
ast::Inherited => s.to_strbuf()
// Synthesizes a comment that was not textually present in the original source
// file.
- pub fn synth_comment(&mut self, text: StrBuf) -> IoResult<()> {
+ pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
try!(word(&mut self.s, "/*"));
try!(space(&mut self.s));
try!(word(&mut self.s, text.as_slice()));
match lit.node {
ast::LitStr(ref st, style) => self.print_string(st.get(), style),
ast::LitChar(ch) => {
- let mut res = StrBuf::from_str("'");
+ let mut res = String::from_str("'");
ch.escape_default(|c| res.push_char(c));
res.push_char('\'');
word(&mut self.s, res.as_slice())
#[deriving(Clone, Eq, Hash, Ord)]
pub struct RcStr {
- string: Rc<StrBuf>,
+ string: Rc<String>,
}
impl TotalEq for RcStr {}
use parse::token;
// map a string to tts, using a made-up filename:
-pub fn string_to_tts(source_str: StrBuf) -> Vec<ast::TokenTree> {
+pub fn string_to_tts(source_str: String) -> Vec<ast::TokenTree> {
let ps = new_parse_sess();
filemap_to_tts(&ps,
string_to_filemap(&ps, source_str, "bogofile".to_strbuf()))
}
// map string to parser (via tts)
-pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: StrBuf) -> Parser<'a> {
+pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> {
new_parser_from_source_str(ps,
Vec::new(),
"bogofile".to_strbuf(),
source_str)
}
-fn with_error_checking_parse<T>(s: StrBuf, f: |&mut Parser| -> T) -> T {
+fn with_error_checking_parse<T>(s: String, f: |&mut Parser| -> T) -> T {
let ps = new_parse_sess();
let mut p = string_to_parser(&ps, s);
let x = f(&mut p);
}
// parse a string, return a crate.
-pub fn string_to_crate (source_str : StrBuf) -> ast::Crate {
+pub fn string_to_crate (source_str : String) -> ast::Crate {
with_error_checking_parse(source_str, |p| {
p.parse_crate_mod()
})
}
// parse a string, return an expr
-pub fn string_to_expr (source_str : StrBuf) -> @ast::Expr {
+pub fn string_to_expr (source_str : String) -> @ast::Expr {
with_error_checking_parse(source_str, |p| {
p.parse_expr()
})
}
// parse a string, return an item
-pub fn string_to_item (source_str : StrBuf) -> Option<@ast::Item> {
+pub fn string_to_item (source_str : String) -> Option<@ast::Item> {
with_error_checking_parse(source_str, |p| {
p.parse_item(Vec::new())
})
}
// parse a string, return a stmt
-pub fn string_to_stmt(source_str : StrBuf) -> @ast::Stmt {
+pub fn string_to_stmt(source_str : String) -> @ast::Stmt {
with_error_checking_parse(source_str, |p| {
p.parse_stmt(Vec::new())
})
// parse a string, return a pat. Uses "irrefutable"... which doesn't
// (currently) affect parsing.
-pub fn string_to_pat(source_str: StrBuf) -> @ast::Pat {
+pub fn string_to_pat(source_str: String) -> @ast::Pat {
string_to_parser(&new_parse_sess(), source_str).parse_pat()
}
#[deriving(Show)]
pub struct TermInfo {
/// Names for the terminal
- pub names: Vec<StrBuf> ,
+ pub names: Vec<String> ,
/// Map of capability name to boolean value
- pub bools: HashMap<StrBuf, bool>,
+ pub bools: HashMap<String, bool>,
/// Map of capability name to numeric value
- pub numbers: HashMap<StrBuf, u16>,
+ pub numbers: HashMap<String, u16>,
/// Map of capability name to raw (unexpanded) string
- pub strings: HashMap<StrBuf, Vec<u8> >
+ pub strings: HashMap<String, Vec<u8> >
}
pub mod searcher;
#[allow(missing_doc)]
#[deriving(Clone)]
pub enum Param {
- String(StrBuf),
+ String(String),
Number(int)
}
multiple capabilities for the same terminal.
*/
pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
- -> Result<Vec<u8> , StrBuf> {
+ -> Result<Vec<u8> , String> {
let mut state = Nothing;
// expanded cap will only rarely be larger than the cap itself
}
}
-fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8> ,StrBuf> {
+fn format(val: Param, op: FormatOp, flags: Flags) -> Result<Vec<u8> ,String> {
let mut s = match val {
Number(d) => {
let s = match (op, flags.sign) {
/// Parse a compiled terminfo entry, using long capability names if `longnames` is true
pub fn parse(file: &mut io::Reader, longnames: bool)
- -> Result<Box<TermInfo>, StrBuf> {
+ -> Result<Box<TermInfo>, String> {
macro_rules! try( ($e:expr) => (
match $e {
Ok(e) => e,
None => return Err("input not utf-8".to_strbuf()),
};
- let term_names: Vec<StrBuf> = names_str.as_slice()
+ let term_names: Vec<String> = names_str.as_slice()
.split('|')
.map(|s| s.to_strbuf())
.collect();
}
/// Return open file for `term`
-pub fn open(term: &str) -> Result<File, StrBuf> {
+pub fn open(term: &str) -> Result<File, String> {
match get_dbpath_for_term(term) {
Some(x) => {
match File::open(x) {
// note: current tests won't work with non-standard terminfo hierarchies (e.g. OS X's)
use std::os::{setenv, unsetenv};
// FIXME (#9639): This needs to handle non-utf8 paths
- fn x(t: &str) -> StrBuf {
+ fn x(t: &str) -> String {
let p = get_dbpath_for_term(t).expect("no terminfo entry found");
p.as_str().unwrap().to_strbuf()
};
use std::io;
use std::os;
use std::str;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::task::TaskBuilder;
// to be used by rustc to compile tests in libtest
#[deriving(Clone, Eq, TotalEq, Hash)]
pub enum TestName {
StaticTestName(&'static str),
- DynTestName(StrBuf)
+ DynTestName(String)
}
impl TestName {
fn as_slice<'a>(&'a self) -> &'a str {
enum NamePadding { PadNone, PadOnLeft, PadOnRight }
impl TestDesc {
- fn padded_name(&self, column_count: uint, align: NamePadding) -> StrBuf {
+ fn padded_name(&self, column_count: uint, align: NamePadding) -> String {
use std::num::Saturating;
- let mut name = StrBuf::from_str(self.name.as_slice());
+ let mut name = String::from_str(self.name.as_slice());
let fill = column_count.saturating_sub(name.len());
- let mut pad = StrBuf::from_owned_str(" ".repeat(fill));
+ let mut pad = String::from_owned_str(" ".repeat(fill));
match align {
PadNone => name,
PadOnLeft => {
}
#[deriving(Eq)]
-pub struct MetricMap(TreeMap<StrBuf,Metric>);
+pub struct MetricMap(TreeMap<String,Metric>);
impl Clone for MetricMap {
fn clone(&self) -> MetricMap {
Regression(f64)
}
-pub type MetricDiff = TreeMap<StrBuf,MetricChange>;
+pub type MetricDiff = TreeMap<String,MetricChange>;
// The default console test runner. It accepts the command line
// arguments and a vector of test_descs.
-pub fn test_main(args: &[StrBuf], tests: Vec<TestDescAndFn> ) {
+pub fn test_main(args: &[String], tests: Vec<TestDescAndFn> ) {
let opts =
match parse_opts(args) {
Some(Ok(o)) => o,
// a ~[TestDescAndFn] is used in order to effect ownership-transfer
// semantics into parallel test runners, which in turn requires a ~[]
// rather than a &[].
-pub fn test_main_static(args: &[StrBuf], tests: &[TestDescAndFn]) {
+pub fn test_main_static(args: &[String], tests: &[TestDescAndFn]) {
let owned_tests = tests.iter().map(|t| {
match t.testfn {
StaticTestFn(f) => TestDescAndFn { testfn: StaticTestFn(f), desc: t.desc.clone() },
}
/// Result of parsing the options.
-pub type OptRes = Result<TestOpts, StrBuf>;
+pub type OptRes = Result<TestOpts, String>;
fn optgroups() -> Vec<getopts::OptGroup> {
vec!(getopts::optflag("", "ignored", "Run ignored tests"),
}
// Parses command line arguments into test options
-pub fn parse_opts(args: &[StrBuf]) -> Option<OptRes> {
+pub fn parse_opts(args: &[String]) -> Option<OptRes> {
let args_ = args.tail();
let matches =
match getopts::getopts(args_.as_slice(), optgroups().as_slice()) {
Some(Ok(test_opts))
}
-pub fn opt_shard(maybestr: Option<StrBuf>) -> Option<(uint,uint)> {
+pub fn opt_shard(maybestr: Option<String>) -> Option<(uint,uint)> {
match maybestr {
None => None,
Some(s) => {
pub fn write_failures(&mut self) -> io::IoResult<()> {
try!(self.write_plain("\nfailures:\n"));
let mut failures = Vec::new();
- let mut fail_out = StrBuf::new();
+ let mut fail_out = String::new();
for &(ref f, ref stdout) in self.failures.iter() {
failures.push(f.name.to_str());
if stdout.len() > 0 {
}
}
-pub fn fmt_metrics(mm: &MetricMap) -> StrBuf {
+pub fn fmt_metrics(mm: &MetricMap) -> String {
let MetricMap(ref mm) = *mm;
- let v : Vec<StrBuf> = mm.iter()
+ let v : Vec<String> = mm.iter()
.map(|(k,v)| format_strbuf!("{}: {} (+/- {})",
*k,
v.value as f64,
v.connect(", ").to_strbuf()
}
-pub fn fmt_bench_samples(bs: &BenchSamples) -> StrBuf {
+pub fn fmt_bench_samples(bs: &BenchSamples) -> String {
if bs.mb_s != 0 {
format_strbuf!("{:>9} ns/iter (+/- {}) = {} MB/s",
bs.ns_iter_summ.median as uint,
#[test]
fn test_boxplot_nonpositive() {
#[allow(deprecated_owned_vector)]
- fn t(s: &Summary<f64>, expected: StrBuf) {
+ fn t(s: &Summary<f64>, expected: String) {
use std::io::MemWriter;
let mut m = MemWriter::new();
write_boxplot(&mut m as &mut io::Writer, s, 30).unwrap();
use std::io::BufReader;
use std::num;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::str;
static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
* Return a string of the current time in the form
* "Thu Jan 1 00:00:00 1970".
*/
- pub fn ctime(&self) -> StrBuf { self.strftime("%c") }
+ pub fn ctime(&self) -> String { self.strftime("%c") }
/// Formats the time according to the format string.
- pub fn strftime(&self, format: &str) -> StrBuf {
+ pub fn strftime(&self, format: &str) -> String {
strftime(format, self)
}
* local: "Thu, 22 Mar 2012 07:53:18 PST"
* utc: "Thu, 22 Mar 2012 14:53:18 UTC"
*/
- pub fn rfc822(&self) -> StrBuf {
+ pub fn rfc822(&self) -> String {
if self.tm_gmtoff == 0_i32 {
self.strftime("%a, %d %b %Y %T GMT")
} else {
* local: "Thu, 22 Mar 2012 07:53:18 -0700"
* utc: "Thu, 22 Mar 2012 14:53:18 -0000"
*/
- pub fn rfc822z(&self) -> StrBuf {
+ pub fn rfc822z(&self) -> String {
self.strftime("%a, %d %b %Y %T %z")
}
* local: "2012-02-22T07:53:18-07:00"
* utc: "2012-02-22T14:53:18Z"
*/
- pub fn rfc3339(&self) -> StrBuf {
+ pub fn rfc3339(&self) -> String {
if self.tm_gmtoff == 0_i32 {
self.strftime("%Y-%m-%dT%H:%M:%SZ")
} else {
}
/// Parses the time from the string according to the format string.
-pub fn strptime(s: &str, format: &str) -> Result<Tm, StrBuf> {
+pub fn strptime(s: &str, format: &str) -> Result<Tm, String> {
fn match_str(s: &str, pos: uint, needle: &str) -> bool {
let mut i = pos;
for ch in needle.bytes() {
return true;
}
- fn match_strs(ss: &str, pos: uint, strs: &[(StrBuf, i32)])
+ fn match_strs(ss: &str, pos: uint, strs: &[(String, i32)])
-> Option<(i32, uint)> {
let mut i = 0u;
let len = strs.len();
}
}
- fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, StrBuf> {
+ fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, String> {
let range = s.char_range_at(pos);
if c == range.ch {
}
fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
- -> Result<uint, StrBuf> {
+ -> Result<uint, String> {
match ch {
'A' => match match_strs(s, pos, [
("Sunday".to_strbuf(), 0_i32),
}
/// Formats the time according to the format string.
-pub fn strftime(format: &str, tm: &Tm) -> StrBuf {
+pub fn strftime(format: &str, tm: &Tm) -> String {
fn days_in_year(year: int) -> i32 {
if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
366 /* Days in a leap year */
+ iso_week1_wday - iso_week_start_wday
}
- fn iso_week(ch:char, tm: &Tm) -> StrBuf {
+ fn iso_week(ch:char, tm: &Tm) -> String {
let mut year: int = tm.tm_year as int + 1900;
let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
}
}
- fn parse_type(ch: char, tm: &Tm) -> StrBuf {
+ fn parse_type(ch: char, tm: &Tm) -> String {
let die = || {
format_strbuf!("strftime: can't understand this format {} ", ch)
};
use std::from_str::FromStr;
use std::hash::Hash;
use std::io::BufReader;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::uint;
/// A Uniform Resource Locator (URL). A URL is a form of URI (Uniform Resource
#[deriving(Clone, Eq, TotalEq)]
pub struct Url {
/// The scheme part of a URL, such as `https` in the above example.
- pub scheme: StrBuf,
+ pub scheme: String,
/// A URL subcomponent for user authentication. `username` in the above example.
pub user: Option<UserInfo>,
/// A domain name or IP address. For example, `example.com`.
- pub host: StrBuf,
+ pub host: String,
/// A TCP port number, for example `8080`.
- pub port: Option<StrBuf>,
+ pub port: Option<String>,
/// The path component of a URL, for example `/foo/bar`.
- pub path: StrBuf,
+ pub path: String,
/// The query component of a URL.
/// `vec!(("baz".to_strbuf(), "qux".to_strbuf()))` represents the fragment
/// `baz=qux` in the above example.
pub query: Query,
/// The fragment component, such as `quz`. Doesn't include the leading `#` character.
- pub fragment: Option<StrBuf>
+ pub fragment: Option<String>
}
#[deriving(Clone, Eq)]
pub struct Path {
/// The path component of a URL, for example `/foo/bar`.
- pub path: StrBuf,
+ pub path: String,
/// The query component of a URL.
/// `vec!(("baz".to_strbuf(), "qux".to_strbuf()))` represents the fragment
/// `baz=qux` in the above example.
pub query: Query,
/// The fragment component, such as `quz`. Doesn't include the leading `#` character.
- pub fragment: Option<StrBuf>
+ pub fragment: Option<String>
}
/// An optional subcomponent of a URI authority component.
#[deriving(Clone, Eq, TotalEq)]
pub struct UserInfo {
/// The user name.
- pub user: StrBuf,
+ pub user: String,
/// Password or other scheme-specific authentication information.
- pub pass: Option<StrBuf>
+ pub pass: Option<String>
}
/// Represents the query component of a URI.
-pub type Query = Vec<(StrBuf, StrBuf)>;
+pub type Query = Vec<(String, String)>;
impl Url {
- pub fn new(scheme: StrBuf,
+ pub fn new(scheme: String,
user: Option<UserInfo>,
- host: StrBuf,
- port: Option<StrBuf>,
- path: StrBuf,
+ host: String,
+ port: Option<String>,
+ path: String,
query: Query,
- fragment: Option<StrBuf>)
+ fragment: Option<String>)
-> Url {
Url {
scheme: scheme,
}
impl Path {
- pub fn new(path: StrBuf,
+ pub fn new(path: String,
query: Query,
- fragment: Option<StrBuf>)
+ fragment: Option<String>)
-> Path {
Path {
path: path,
impl UserInfo {
#[inline]
- pub fn new(user: StrBuf, pass: Option<StrBuf>) -> UserInfo {
+ pub fn new(user: String, pass: Option<String>) -> UserInfo {
UserInfo { user: user, pass: pass }
}
}
-fn encode_inner(s: &str, full_url: bool) -> StrBuf {
+fn encode_inner(s: &str, full_url: bool) -> String {
let mut rdr = BufReader::new(s.as_bytes());
- let mut out = StrBuf::new();
+ let mut out = String::new();
loop {
let mut buf = [0];
* println!("{}", url); // https://example.com/Rust%20(programming%20language)
* ```
*/
-pub fn encode(s: &str) -> StrBuf {
+pub fn encode(s: &str) -> String {
encode_inner(s, true)
}
* This function is compliant with RFC 3986.
*/
-pub fn encode_component(s: &str) -> StrBuf {
+pub fn encode_component(s: &str) -> String {
encode_inner(s, false)
}
-fn decode_inner(s: &str, full_url: bool) -> StrBuf {
+fn decode_inner(s: &str, full_url: bool) -> String {
let mut rdr = BufReader::new(s.as_bytes());
- let mut out = StrBuf::new();
+ let mut out = String::new();
loop {
let mut buf = [0];
* println!("{}", url); // https://example.com/Rust (programming language)
* ```
*/
-pub fn decode(s: &str) -> StrBuf {
+pub fn decode(s: &str) -> String {
decode_inner(s, true)
}
/**
* Decode a string encoded with percent encoding.
*/
-pub fn decode_component(s: &str) -> StrBuf {
+pub fn decode_component(s: &str) -> String {
decode_inner(s, false)
}
-fn encode_plus(s: &str) -> StrBuf {
+fn encode_plus(s: &str) -> String {
let mut rdr = BufReader::new(s.as_bytes());
- let mut out = StrBuf::new();
+ let mut out = String::new();
loop {
let mut buf = [0];
/**
* Encode a hashmap to the 'application/x-www-form-urlencoded' media type.
*/
-pub fn encode_form_urlencoded(m: &HashMap<StrBuf, Vec<StrBuf>>) -> StrBuf {
- let mut out = StrBuf::new();
+pub fn encode_form_urlencoded(m: &HashMap<String, Vec<String>>) -> String {
+ let mut out = String::new();
let mut first = true;
for (key, values) in m.iter() {
* type into a hashmap.
*/
#[allow(experimental)]
-pub fn decode_form_urlencoded(s: &[u8]) -> HashMap<StrBuf, Vec<StrBuf>> {
+pub fn decode_form_urlencoded(s: &[u8]) -> HashMap<String, Vec<String>> {
let mut rdr = BufReader::new(s);
- let mut m: HashMap<StrBuf,Vec<StrBuf>> = HashMap::new();
- let mut key = StrBuf::new();
- let mut value = StrBuf::new();
+ let mut m: HashMap<String,Vec<String>> = HashMap::new();
+ let mut key = String::new();
+ let mut value = String::new();
let mut parsing_key = true;
loop {
}
parsing_key = true;
- key = StrBuf::new();
- value = StrBuf::new();
+ key = String::new();
+ value = String::new();
}
'=' => parsing_key = false,
ch => {
}
-fn split_char_first(s: &str, c: char) -> (StrBuf, StrBuf) {
+fn split_char_first(s: &str, c: char) -> (String, String) {
let len = s.len();
let mut index = len;
let mut mat = 0;
* ```
*/
#[allow(unused_must_use)]
-pub fn query_to_str(query: &Query) -> StrBuf {
+pub fn query_to_str(query: &Query) -> String {
use std::io::MemWriter;
use std::str;
* println!("Scheme in use: {}.", scheme); // Scheme in use: https.
* ```
*/
-pub fn get_scheme(rawurl: &str) -> Result<(StrBuf, StrBuf), StrBuf> {
+pub fn get_scheme(rawurl: &str) -> Result<(String, String), String> {
for (i,c) in rawurl.chars().enumerate() {
match c {
'A' .. 'Z' | 'a' .. 'z' => continue,
// returns userinfo, host, port, and unparsed part, or an error
fn get_authority(rawurl: &str) ->
- Result<(Option<UserInfo>, StrBuf, Option<StrBuf>, StrBuf), StrBuf> {
+ Result<(Option<UserInfo>, String, Option<String>, String), String> {
if !rawurl.starts_with("//") {
// there is no authority.
return Ok((None, "".to_strbuf(), None, rawurl.to_str().to_strbuf()));
// returns the path and unparsed part of url, or an error
fn get_path(rawurl: &str, authority: bool) ->
- Result<(StrBuf, StrBuf), StrBuf> {
+ Result<(String, String), String> {
let len = rawurl.len();
let mut end = len;
for (i,c) in rawurl.chars().enumerate() {
// returns the parsed query and the fragment, if present
fn get_query_fragment(rawurl: &str) ->
- Result<(Query, Option<StrBuf>), StrBuf> {
+ Result<(Query, Option<String>), String> {
if !rawurl.starts_with("?") {
if rawurl.starts_with("#") {
let f = decode_component(rawurl.slice(
*
* A `Url` struct type representing the URL.
*/
-pub fn from_str(rawurl: &str) -> Result<Url, StrBuf> {
+pub fn from_str(rawurl: &str) -> Result<Url, String> {
// scheme
let (scheme, rest) = match get_scheme(rawurl) {
Ok(val) => val,
Ok(Url::new(scheme, userinfo, host, port, path, query, fragment))
}
-pub fn path_from_str(rawpath: &str) -> Result<Path, StrBuf> {
+pub fn path_from_str(rawpath: &str) -> Result<Path, String> {
let (path, rest) = match get_path(rawpath, false) {
Ok(val) => val,
Err(e) => return Err(e)
/// Returns the UUID as a string of 16 hexadecimal digits
///
/// Example: `936DA01F9ABD4d9d80C702AF85C822A8`
- pub fn to_simple_str(&self) -> StrBuf {
+ pub fn to_simple_str(&self) -> String {
let mut s: Vec<u8> = Vec::from_elem(32, 0u8);
for i in range(0u, 16u) {
let digit = format!("{:02x}", self.bytes[i] as uint);
/// Returns a string of hexadecimal digits, separated into groups with a hyphen.
///
/// Example: `550e8400-e29b-41d4-a716-446655440000`
- pub fn to_hyphenated_str(&self) -> StrBuf {
+ pub fn to_hyphenated_str(&self) -> String {
use std::mem::{to_be16, to_be32};
// Convert to field-based struct as it matches groups in output.
// Ensure fields are in network byte order, as per RFC.
/// This is the same as the hyphenated format, but with the "urn:uuid:" prefix.
///
/// Example: `urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4`
- pub fn to_urn_str(&self) -> StrBuf {
+ pub fn to_urn_str(&self) -> String {
format_strbuf!("urn:uuid:{}", self.to_hyphenated_str())
}
#[deriving(Clone, Eq, Encodable, Decodable, Ord, TotalOrd, TotalEq)]
struct WorkKey {
- kind: StrBuf,
- name: StrBuf
+ kind: String,
+ name: String
}
impl WorkKey {
}
}
-// FIXME #8883: The key should be a WorkKey and not a StrBuf.
+// FIXME #8883: The key should be a WorkKey and not a String.
// This is working around some JSON weirdness.
#[deriving(Clone, Eq, Encodable, Decodable)]
-struct WorkMap(TreeMap<StrBuf, KindMap>);
+struct WorkMap(TreeMap<String, KindMap>);
#[deriving(Clone, Eq, Encodable, Decodable)]
-struct KindMap(TreeMap<StrBuf, StrBuf>);
+struct KindMap(TreeMap<String, String>);
impl WorkMap {
fn new() -> WorkMap { WorkMap(TreeMap::new()) }
- fn insert_work_key(&mut self, k: WorkKey, val: StrBuf) {
+ fn insert_work_key(&mut self, k: WorkKey, val: String) {
let WorkKey { kind, name } = k;
let WorkMap(ref mut map) = *self;
match map.find_mut(&name) {
pub struct Database {
db_filename: Path,
- db_cache: TreeMap<StrBuf, StrBuf>,
+ db_cache: TreeMap<String, String>,
pub db_dirty: bool,
}
pub fn prepare(&self,
fn_name: &str,
declared_inputs: &WorkMap)
- -> Option<(WorkMap, WorkMap, StrBuf)> {
+ -> Option<(WorkMap, WorkMap, String)> {
let k = json_encode(&(fn_name, declared_inputs));
match self.db_cache.find(&k) {
None => None,
}
}
-pub type FreshnessMap = TreeMap<StrBuf,extern fn(&str,&str)->bool>;
+pub type FreshnessMap = TreeMap<String,extern fn(&str,&str)->bool>;
#[deriving(Clone)]
pub struct Context {
WorkFromTask(&'a Prep<'a>, Receiver<(Exec, T)>),
}
-fn json_encode<'a, T:Encodable<json::Encoder<'a>, io::IoError>>(t: &T) -> StrBuf {
+fn json_encode<'a, T:Encodable<json::Encoder<'a>, io::IoError>>(t: &T) -> String {
let mut writer = MemWriter::new();
let mut encoder = json::Encoder::new(&mut writer as &mut io::Writer);
let _ = t.encode(&mut encoder);
}
// returns pairs of (kind, name)
- pub fn lookup_discovered_inputs(&self) -> Vec<(StrBuf, StrBuf)> {
+ pub fn lookup_discovered_inputs(&self) -> Vec<(String, String)> {
let mut rs = vec![];
let WorkMap(ref discovered_inputs) = self.discovered_inputs;
for (k, v) in discovered_inputs.iter() {
}
}
- pub fn lookup_declared_inputs(&self) -> Vec<StrBuf> {
+ pub fn lookup_declared_inputs(&self) -> Vec<String> {
let mut rs = vec![];
let WorkMap(ref declared_inputs) = self.declared_inputs;
for (_, v) in declared_inputs.iter() {
// Create a path to a new file 'filename' in the directory in which
// this test is running.
- fn make_path(filename: StrBuf) -> Path {
+ fn make_path(filename: String) -> Path {
let pth = os::self_exe_path().expect("workcache::test failed").with_filename(filename);
if pth.exists() {
fs::unlink(&pth).unwrap();
meows : uint,
pub how_hungry : int,
- pub name : StrBuf,
+ pub name : String,
}
impl cat {
}
}
- pub fn cat(in_x : uint, in_y : int, in_name: StrBuf) -> cat {
+ pub fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
pub struct cat {
meows : uint,
pub how_hungry : int,
- pub name : StrBuf,
+ pub name : String,
}
impl fmt::Show for cat {
}
}
- pub fn cat(in_x : uint, in_y : int, in_name: StrBuf) -> cat {
+ pub fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
pub type name_pool = ();
pub trait add {
- fn add(&self, s: StrBuf);
+ fn add(&self, s: String);
}
impl add for name_pool {
- fn add(&self, _s: StrBuf) {
+ fn add(&self, _s: String) {
}
}
}
#![crate_type = "lib"]
-pub struct NameVal { pub name: StrBuf, pub val: int }
+pub struct NameVal { pub name: String, pub val: int }
pub fn struct_nameval() -> NameVal {
NameVal { name: "crateresolve5".to_strbuf(), val: 10 }
#![crate_type = "lib"]
-pub struct NameVal { pub name: StrBuf, pub val: int }
+pub struct NameVal { pub name: String, pub val: int }
pub fn struct_nameval() -> NameVal {
NameVal { name: "crateresolve5".to_strbuf(), val: 10 }
}
}
pub struct Bar {
- pub x: StrBuf
+ pub x: String
}
impl Foo for Bar {
fn foo(&self);
}
-impl foo for StrBuf {
+impl foo for String {
fn foo(&self) {}
}
use std::cell::RefCell;
use collections::HashMap;
-pub type header_map = HashMap<StrBuf, @RefCell<Vec<@StrBuf>>>;
+pub type header_map = HashMap<String, @RefCell<Vec<@String>>>;
// the unused ty param is necessary so this gets monomorphized
pub fn request<T>(req: &header_map) {
// Tests ty_float (does not test all variants of FloatTy)
pub type FooFloat = f64;
- // For ty_str, what kind of string should I use? &'static str? StrBuf? Raw str?
+ // For ty_str, what kind of string should I use? &'static str? String? Raw str?
// Tests ty_enum
pub enum FooEnum {
#![crate_type = "lib"]
trait to_strz {
- fn to_strz() -> StrBuf;
+ fn to_strz() -> String;
}
-impl to_strz for StrBuf {
- fn to_strz() -> StrBuf { self.clone() }
+impl to_strz for String {
+ fn to_strz() -> String { self.clone() }
}
use a::to_strz;
impl to_strz for bool {
- fn to_strz() -> StrBuf { fmt!("%b", self) }
+ fn to_strz() -> String { fmt!("%b", self) }
}
}
pub struct Boz {
- unused_str: StrBuf
+ unused_str: String
}
impl Boz {
}
impl Bort {
- pub fn bort() -> StrBuf {
+ pub fn bort() -> String {
"bort()".to_strbuf()
}
}
use std::int;
pub trait read {
- fn readMaybe(s: StrBuf) -> Option<Self>;
+ fn readMaybe(s: String) -> Option<Self>;
}
impl read for int {
- fn readMaybe(s: StrBuf) -> Option<int> {
+ fn readMaybe(s: String) -> Option<int> {
from_str::<int>(s.as_slice())
}
}
impl read for bool {
- fn readMaybe(s: StrBuf) -> Option<bool> {
+ fn readMaybe(s: String) -> Option<bool> {
match s.as_slice() {
"true" => Some(true),
"false" => Some(false),
}
}
-pub fn read<T:read>(s: StrBuf) -> T {
+pub fn read<T:read>(s: String) -> T {
match read::readMaybe(s) {
Some(x) => x,
_ => fail!("read failed!")
}
}
- pub fn bench_str<T:MutableSet<StrBuf>,
+ pub fn bench_str<T:MutableSet<String>,
R:rand::Rng>(
&mut self,
rng: &mut R,
s
});
results.bench_str(&mut rng, num_keys, || {
- let s: HashSet<StrBuf> = HashSet::new();
+ let s: HashSet<String> = HashSet::new();
s
});
write_results("collections::HashSet", &results);
s
});
results.bench_str(&mut rng, num_keys, || {
- let s: TreeSet<StrBuf> = TreeSet::new();
+ let s: TreeSet<String> = TreeSet::new();
s
});
write_results("collections::TreeSet", &results);
)
fn main() {
- let argv = os::args().move_iter().map(|x| x.to_strbuf()).collect::<Vec<StrBuf>>();
+ let argv = os::args().move_iter().map(|x| x.to_strbuf()).collect::<Vec<String>>();
let _tests = argv.slice(1, argv.len());
bench!(argv, shift_push);
bench!(argv, is_utf8_multibyte);
}
-fn maybe_run_test(argv: &[StrBuf], name: StrBuf, test: ||) {
+fn maybe_run_test(argv: &[String], name: String, test: ||) {
let mut run_test = false;
if os::getenv("RUST_BENCH").is_some() {
//println!("server exiting");
}
-fn run(args: &[StrBuf]) {
+fn run(args: &[String]) {
let (to_parent, from_child) = channel();
let (to_child, from_parent) = channel();
//println!("server exiting");
}
-fn run(args: &[StrBuf]) {
+fn run(args: &[String]) {
let (to_parent, from_child) = channel();
let size = from_str::<uint>(args[1].as_slice()).unwrap();
format_strbuf!("{}\t trees of depth {}\t check: {}",
iterations * 2, depth, chk)
})
- }).collect::<Vec<Future<StrBuf>>>();
+ }).collect::<Vec<Future<String>>>();
for message in messages.mut_iter() {
println!("{}", *message.get_ref());
#![feature(phase)]
#[phase(syntax)] extern crate green;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::fmt;
green_start!(main)
color: Color
}
-fn show_color_list(set: Vec<Color>) -> StrBuf {
- let mut out = StrBuf::new();
+fn show_color_list(set: Vec<Color>) -> String {
+ let mut out = String::new();
for col in set.iter() {
out.push_char(' ');
out.push_str(col.to_str().as_slice());
mut color: Color,
from_rendezvous: Receiver<CreatureInfo>,
to_rendezvous: Sender<CreatureInfo>,
- to_rendezvous_log: Sender<StrBuf>
+ to_rendezvous_log: Sender<String>
) {
let mut creatures_met = 0;
let mut evil_clones_met = 0;
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
- let (to_rendezvous_log, from_creatures_log) = channel::<StrBuf>();
+ let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to talk to each creature by 'name'/index
let mut to_creature: Vec<Sender<CreatureInfo>> =
use std::mem::replace;
use std::option;
use std::os;
-use std::strbuf::StrBuf;
+use std::string::String;
fn f64_cmp(x: f64, y: f64) -> Ordering {
// arbitrarily decide that NaNs are larger than everything.
}
// given a map, print a sorted version of it
-fn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> StrBuf {
+fn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> String {
fn pct(xx: uint, yy: uint) -> f64 {
return (xx as f64) * 100.0 / (yy as f64);
}
let pairs_sorted = sortKV(pairs);
- let mut buffer = StrBuf::new();
+ let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{} {:0.3f}\n",
k.as_slice()
}
// given a map, search for the frequency of a pattern
-fn find(mm: &HashMap<Vec<u8> , uint>, key: StrBuf) -> uint {
+fn find(mm: &HashMap<Vec<u8> , uint>, key: String) -> uint {
let key = key.to_owned().into_ascii().as_slice().to_lower().into_str();
match mm.find_equiv(&key.as_bytes()) {
option::None => { return 0u; }
fn make_sequence_processor(sz: uint,
from_parent: &Receiver<Vec<u8>>,
- to_parent: &Sender<StrBuf>) {
+ to_parent: &Sender<String>) {
let mut freqs: HashMap<Vec<u8>, uint> = HashMap::new();
let mut carry = Vec::new();
let mut total: uint = 0u;
// initialize each sequence sorter
let sizes = vec!(1u,2,3,4,6,12,18);
- let mut streams = Vec::from_fn(sizes.len(), |_| Some(channel::<StrBuf>()));
+ let mut streams = Vec::from_fn(sizes.len(), |_| Some(channel::<String>()));
let mut from_child = Vec::new();
let to_child = sizes.iter().zip(streams.mut_iter()).map(|(sz, stream_ref)| {
let sz = *sz;
extern crate sync;
-use std::strbuf::StrBuf;
+use std::string::String;
use std::slice;
use sync::Arc;
use sync::Future;
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
- fn unpack(&self, frame: uint) -> StrBuf {
+ fn unpack(&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
}
result.reverse();
- StrBuf::from_utf8(result).unwrap()
+ String::from_utf8(result).unwrap()
}
}
fail!("{:016x} does not have a valid identifier", m);
}
-// Converts a list of mask to a StrBuf.
+// Converts a list of mask to a String.
fn to_vec(raw_sol: &List<u64>) -> Vec<u8> {
let mut sol = Vec::from_elem(50, '.' as u8);
for &m in raw_sol.iter() {
sol
}
-// Prints a solution in StrBuf form.
+// Prints a solution in String form.
fn print_sol(sol: &Vec<u8>) {
for (i, c) in sol.iter().enumerate() {
if (i) % 5 == 0 { println!(""); }
stress: bool
}
-fn parse_opts(argv: Vec<StrBuf> ) -> Config {
+fn parse_opts(argv: Vec<String> ) -> Config {
let opts = vec!(getopts::optflag("", "stress", ""));
let argv = argv.iter().map(|x| x.to_strbuf()).collect::<Vec<_>>();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// error-pattern:expected `std::strbuf::StrBuf` but found `int`
+// error-pattern:expected `std::string::String` but found `int`
-static i: StrBuf = 10i;
+static i: String = 10i;
fn main() { println!("{}", i); }
mod m1 {}
-fn main(args: Vec<StrBuf>) { log(debug, m1::a); }
+fn main(args: Vec<String>) { log(debug, m1::a); }
pub mod a {}
}
-fn main(args: Vec<StrBuf>) {
+fn main(args: Vec<String>) {
log(debug, m1::a);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// error-pattern:`^` cannot be applied to type `std::strbuf::StrBuf`
+// error-pattern:`^` cannot be applied to type `std::string::String`
fn main() { let x = "a".to_strbuf() ^ "b".to_strbuf(); }
}
struct S {
- f: StrBuf,
- g: StrBuf
+ f: String,
+ g: String
}
impl Drop for S {
fn drop(&mut self) { println!("{}", self.f); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn with(f: |&StrBuf|) {}
+fn with(f: |&String|) {}
-fn arg_item(&_x: &StrBuf) {}
+fn arg_item(&_x: &String) {}
//~^ ERROR cannot move out of dereference of `&`-pointer
fn arg_closure() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-struct S {f:StrBuf}
+struct S {f:String}
impl Drop for S {
fn drop(&mut self) { println!("{}", self.f); }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-struct S(StrBuf);
+struct S(String);
impl Drop for S {
fn drop(&mut self) { }
}
#[deriving(Clone)]
struct Foo {
- string: StrBuf
+ string: String
}
pub fn main() {
// except according to those terms.
struct Foo {
- t: StrBuf
+ t: String
}
fn cond() -> bool { true }
enum E {
Foo,
- Bar(StrBuf)
+ Bar(String)
}
struct S {
x: E
}
-fn f(x: StrBuf) {}
+fn f(x: String) {}
fn main() {
let s = S { x: Bar("hello".to_strbuf()) };
Variant1,
Variant2(int),
Variant3(WithDtor),
- Variant4(StrBuf)
+ Variant4(String)
}
// These should be ok
#[path = "circular_modules_hello.rs"]
mod circular_modules_hello; //~ERROR: circular modules
-pub fn hi_str() -> StrBuf {
+pub fn hi_str() -> String {
"Hi!".to_owned()
}
meows : uint,
how_hungry : int,
- name : StrBuf,
+ name : String,
}
impl cat {
}
}
-fn cat(in_x : uint, in_y : int, in_name: StrBuf) -> cat {
+fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
// except according to those terms.
struct X {
- x: StrBuf,
+ x: String,
}
impl Drop for X {
}
}
-fn unwrap(x: X) -> StrBuf {
+fn unwrap(x: X) -> String {
let X { x: y } = x; //~ ERROR cannot move out of type
y
}
// except according to those terms.
struct X {
- x: StrBuf,
+ x: String,
}
impl Drop for X {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn wants_uniq(x: StrBuf) { }
+fn wants_uniq(x: String) { }
fn wants_slice(x: &str) { }
-fn has_uniq(x: StrBuf) {
+fn has_uniq(x: String) {
wants_uniq(x);
wants_slice(x.as_slice());
}
//~^ ERROR mismatched types: expected `Foo<int>` but found `()`
// Including cases where the default is using previous type params.
- let _: HashMap<StrBuf, int> = ();
- //~^ ERROR mismatched types: expected `HashMap<std::strbuf::StrBuf,int>` but found `()`
- let _: HashMap<StrBuf, int, Hash<StrBuf>> = ();
- //~^ ERROR mismatched types: expected `HashMap<std::strbuf::StrBuf,int>` but found `()`
+ let _: HashMap<String, int> = ();
+ //~^ ERROR mismatched types: expected `HashMap<std::string::String,int>` but found `()`
+ let _: HashMap<String, int, Hash<String>> = ();
+ //~^ ERROR mismatched types: expected `HashMap<std::string::String,int>` but found `()`
// But not when there's a different type in between.
let _: Foo<A, int, C> = ();
mod zed {
pub fn bar() { println!("bar"); }
}
-fn main(args: Vec<StrBuf>) { bar(); }
+fn main(args: Vec<String>) { bar(); }
mod zed {
pub fn bar() { println!("bar3"); }
}
-fn main(args: Vec<StrBuf>) { bar(); }
+fn main(args: Vec<String>) { bar(); }
pub fn main() {
let v: Vec<int> = vec!(0, 1, 2, 3, 4, 5);
- let s: StrBuf = "abcdef".to_strbuf();
+ let s: String = "abcdef".to_strbuf();
assert_eq!(v.as_slice()[3u], 3);
assert_eq!(v.as_slice()[3u8], 3); //~ ERROR: mismatched types
assert_eq!(v.as_slice()[3i8], 3); //~ ERROR: mismatched types
fn main() {
let x = Some(3);
let y = x.as_ref().unwrap_or(&5); //~ ERROR: borrowed value does not live long enough
-}
\ No newline at end of file
+}
// Regression test for #13428
-fn foo() -> StrBuf { //~ ERROR not all control paths return a value
+fn foo() -> String { //~ ERROR not all control paths return a value
format_strbuf!("Hello {}",
"world")
// Put the trailing semicolon on its own line to test that the
; //~ NOTE consider removing this semicolon
}
-fn bar() -> StrBuf { //~ ERROR not all control paths return a value
+fn bar() -> String { //~ ERROR not all control paths return a value
"foobar".to_strbuf()
; //~ NOTE consider removing this semicolon
}
struct t(Box<t>); //~ ERROR this type cannot be instantiated
trait to_str_2 {
- fn my_to_str() -> StrBuf;
+ fn my_to_str() -> String;
}
// I use an impl here because it will cause
// the compiler to attempt autoderef and then
// try to resolve the method.
impl to_str_2 for t {
- fn my_to_str() -> StrBuf { "t".to_strbuf() }
+ fn my_to_str() -> String { "t".to_strbuf() }
}
fn new_t(x: t) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn a(x: StrBuf) -> StrBuf {
+fn a(x: String) -> String {
format!("First function with {}", x)
}
-fn a(x: StrBuf, y: StrBuf) -> StrBuf { //~ ERROR duplicate definition of value `a`
+fn a(x: String, y: String) -> String { //~ ERROR duplicate definition of value `a`
format!("Second function with {} and {}", x, y)
}
struct HTMLImageData {
- image: Option<StrBuf>
+ image: Option<String>
}
struct ElementData {
Point { x: x, y: y }
}
- fn to_str(&self) -> StrBuf {
+ fn to_str(&self) -> String {
format!("({}, {})", self.x, self.y)
}
}
use std::io::ReaderUtil;
use std::io::Reader;
-fn bar(r:@ReaderUtil) -> StrBuf { r.read_line() }
+fn bar(r:@ReaderUtil) -> String { r.read_line() }
fn main() {
let r : @Reader = io::stdin();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn foo(b: bool) -> Result<bool,StrBuf> {
+fn foo(b: bool) -> Result<bool,String> {
Err("bar".to_owned());
//~^ ERROR: cannot determine a type for this expression: unconstrained type
}
pub struct CrateId {
- local_path: StrBuf,
- junk: StrBuf
+ local_path: String,
+ junk: String
}
impl CrateId {
}
}
-impl ManyImplTrait for StrBuf {
+impl ManyImplTrait for String {
fn is_str() -> bool {
true
}
}
fn main() {
-}
\ No newline at end of file
+}
// ~ pointers are not ok
assert_copy::<Box<int>>(); //~ ERROR does not fulfill
- assert_copy::<StrBuf>(); //~ ERROR does not fulfill
+ assert_copy::<String>(); //~ ERROR does not fulfill
assert_copy::<Vec<int> >(); //~ ERROR does not fulfill
assert_copy::<Box<&'a mut int>>(); //~ ERROR does not fulfill
// boxes are ok
assert_send::<Box<int>>();
- assert_send::<StrBuf>();
+ assert_send::<String>();
assert_send::<Vec<int> >();
// but not if they own a bad thing
sure that when purity is inherited that the source of the unsafe-ness
is tracked correctly */
unsafe {
- unsafe fn what() -> Vec<StrBuf> { fail!() }
+ unsafe fn what() -> Vec<String> { fail!() }
callback(|| {
what();
// of the various arms, particularly in the case where regions are
// involved.
-pub fn opt_str0<'a>(maybestr: &'a Option<StrBuf>) -> &'a str {
+pub fn opt_str0<'a>(maybestr: &'a Option<String>) -> &'a str {
if maybestr.is_none() {
"(none)"
} else {
}
}
-pub fn opt_str1<'a>(maybestr: &'a Option<StrBuf>) -> &'a str {
+pub fn opt_str1<'a>(maybestr: &'a Option<String>) -> &'a str {
if maybestr.is_some() {
let s: &'a str = maybestr.get_ref().as_slice();
s
}
}
-pub fn opt_str2<'a>(maybestr: &'a Option<StrBuf>) -> &'static str {
+pub fn opt_str2<'a>(maybestr: &'a Option<String>) -> &'static str {
if maybestr.is_none() { //~ ERROR mismatched types
"(none)"
} else {
}
}
-pub fn opt_str3<'a>(maybestr: &'a Option<StrBuf>) -> &'static str {
+pub fn opt_str3<'a>(maybestr: &'a Option<String>) -> &'static str {
if maybestr.is_some() { //~ ERROR mismatched types
let s: &'a str = maybestr.get_ref().as_slice();
s
// of the various arms, particularly in the case where regions are
// involved.
-pub fn opt_str0<'a>(maybestr: &'a Option<StrBuf>) -> &'a str {
+pub fn opt_str0<'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
Some(ref s) => {
let s: &'a str = s.as_slice();
}
}
-pub fn opt_str1<'a>(maybestr: &'a Option<StrBuf>) -> &'a str {
+pub fn opt_str1<'a>(maybestr: &'a Option<String>) -> &'a str {
match *maybestr {
None => "(none)",
Some(ref s) => {
}
}
-pub fn opt_str2<'a>(maybestr: &'a Option<StrBuf>) -> &'static str {
+pub fn opt_str2<'a>(maybestr: &'a Option<String>) -> &'static str {
match *maybestr { //~ ERROR mismatched types
None => "(none)",
Some(ref s) => {
}
}
-pub fn opt_str3<'a>(maybestr: &'a Option<StrBuf>) -> &'static str {
+pub fn opt_str3<'a>(maybestr: &'a Option<String>) -> &'static str {
match *maybestr { //~ ERROR mismatched types
Some(ref s) => {
let s: &'a str = s.as_slice();
_ => ()
}
- let x: Vec<StrBuf> = vec!["foo".to_strbuf(),
+ let x: Vec<String> = vec!["foo".to_strbuf(),
"bar".to_strbuf(),
"baz".to_strbuf()];
- let x: &[StrBuf] = x.as_slice();
+ let x: &[String] = x.as_slice();
match x {
[a, _, _, ..] => { println!("{}", a); }
[_, _, _, _, _] => { } //~ ERROR unreachable pattern
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// error-pattern:cannot apply unary operator `-` to type `std::strbuf::StrBuf`
+// error-pattern:cannot apply unary operator `-` to type `std::string::String`
fn main() { -"foo".to_strbuf(); }
// Tests that if you move from `x.f` or `x[0]`, `x` is inaccessible.
// Also tests that we give a more specific error message.
-struct Foo { f: StrBuf, y: int }
-fn consume(_s: StrBuf) {}
+struct Foo { f: String, y: int }
+fn consume(_s: String) {}
fn touch<A>(_a: &A) {}
fn f10() {
#![feature(managed_boxes)]
struct Foo<A> { f: A }
-fn guard(_s: StrBuf) -> bool {fail!()}
+fn guard(_s: String) -> bool {fail!()}
fn touch<A>(_a: &A) {}
fn f10() {
// terms of the binding, not the discriminant.
struct Foo<A> { f: A }
-fn guard(_s: StrBuf) -> bool {fail!()}
+fn guard(_s: String) -> bool {fail!()}
fn touch<A>(_a: &A) {}
fn f10() {
impl Cmp, ToStr for S { //~ ERROR: expected `{` but found `,`
fn eq(&&other: S) { false }
- fn to_str(&self) -> StrBuf { "hi".to_owned() }
+ fn to_str(&self) -> String { "hi".to_owned() }
}
struct foo {
i: int,
- j: @StrBuf,
+ j: @String,
}
-fn foo(i:int, j: @StrBuf) -> foo {
+fn foo(i:int, j: @String) -> foo {
foo {
i: i,
j: j
// gdb-command:run
// gdb-command:finish
// gdb-command:print string1.length
-// gdb-check:$1 = 48
+// gdb-check:$1 = 49
// gdb-command:print string2.length
-// gdb-check:$2 = 48
+// gdb-check:$2 = 49
// gdb-command:print string3.length
-// gdb-check:$3 = 48
+// gdb-check:$3 = 49
// gdb-command:continue
#![allow(unused_variable)]
// ignore-test
fn main() {
- let args : ~[StrBuf] = ::std::os::args();
+ let args : ~[String] = ::std::os::args();
::std::io::println(args[0]);
}
// compile-flags:-g
// gdb-command:list
// gdb-check:1[...]fn main() {
-// gdb-check:2[...]let args : ~[StrBuf] = ::std::os::args();
+// gdb-check:2[...]let args : ~[String] = ::std::os::args();
// gdb-check:3[...]::std::io::println(args[0]);
// gdb-check:4[...]}
-some text to include in another file as string 1
\ No newline at end of file
+some text to include in another file as string 1
-some text to include in another file as string 2
\ No newline at end of file
+some text to include in another file as string 2
-some text to include in another file as string 3
\ No newline at end of file
+some text to include in another file as string 3
// pp-exact
-fn call_it(f: proc(StrBuf) -> StrBuf) { }
+fn call_it(f: proc(String) -> String) { }
fn call_this(f: |&str|: Send) { }
// except according to those terms.
// error-pattern:quux
-fn my_err(s: StrBuf) -> ! { println!("{}", s); fail!("quux"); }
+fn my_err(s: String) -> ! { println!("{}", s); fail!("quux"); }
fn main() { 3u == my_err("bye".to_strbuf()); }
// except according to those terms.
// error-pattern:quux
-fn my_err(s: StrBuf) -> ! { println!("{}", s); fail!("quux"); }
+fn my_err(s: String) -> ! { println!("{}", s); fail!("quux"); }
fn main() { 3u == my_err("bye".to_strbuf()); }
// error-pattern:meh
fn main() {
- let str_var: StrBuf = "meh".to_strbuf();
+ let str_var: String = "meh".to_strbuf();
fail!("{}", str_var);
}
// except according to those terms.
// error-pattern:quux
-fn my_err(s: StrBuf) -> ! { println!("{}", s); fail!("quux"); }
+fn my_err(s: String) -> ! { println!("{}", s); fail!("quux"); }
fn main() { if my_err("bye".to_strbuf()) { } }
#![allow(unreachable_code)]
#![allow(unused_variable)]
-fn foo(s: StrBuf) { }
+fn foo(s: String) { }
fn main() {
let i =
use std::result;
fn main() {
- println!("{:?}", result::Err::<int,StrBuf>("kitty".to_strbuf()).unwrap());
+ println!("{:?}", result::Err::<int,String>("kitty".to_strbuf()).unwrap());
}
#![allow(unreachable_code)]
#![allow(unused_variable)]
-struct T { t: StrBuf }
+struct T { t: String }
fn main() {
let pth = fail!("bye");
// error-pattern:index out of bounds: the len is 5 but the index is 5
fn main() {
- let s: StrBuf = "hello".to_strbuf();
+ let s: String = "hello".to_strbuf();
// Bounds-check failure.
assert_eq!(s.as_slice()[5], 0x0 as u8);
let cheese = "roquefort".to_strbuf();
let carrots = @"crunchy".to_strbuf();
- let result: |@StrBuf, |StrBuf||: 'static = (|tasties, macerate| {
+ let result: |@String, |String||: 'static = (|tasties, macerate| {
macerate((*tasties).clone());
});
result(carrots, |food| {
let _ = write!(&mut File::create(&main_file).unwrap(),
r"\#![feature(non_ascii_idents)] fn main() \{ {} \}",
// random string of length n
- range(0, n).map(|_| random_char()).collect::<StrBuf>());
+ range(0, n).map(|_| random_char()).collect::<String>());
}
// rustc is passed to us with --out-dir and -L etc., so we
}
fn check_pp<T>(cx: fake_ext_ctxt,
- expr: T, f: |pprust::ps, T|, expect: StrBuf) {
+ expr: T, f: |pprust::ps, T|, expect: String) {
let s = io::with_str_writer(|wr| {
let pp = pprust::rust_printer(wr, cx.parse_sess().interner);
f(pp, expr);
enum sty { ty_nil, }
-struct RawT {struct_: sty, cname: Option<StrBuf>, hash: uint}
+struct RawT {struct_: sty, cname: Option<String>, hash: uint}
-fn mk_raw_ty(st: sty, cname: Option<StrBuf>) -> RawT {
+fn mk_raw_ty(st: sty, cname: Option<String>) -> RawT {
return RawT {struct_: st, cname: cname, hash: 0u};
}
-pub fn main() { mk_raw_ty(ty_nil, None::<StrBuf>); }
+pub fn main() { mk_raw_ty(ty_nil, None::<String>); }
pub fn main() {
assert_eq!(g(f), 1);
- let f1: |Vec<StrBuf>| -> StrBuf = f;
+ let f1: |Vec<String>| -> String = f;
assert_eq!(f1(vec!["x".to_strbuf(), "y".to_strbuf(), "z".to_strbuf()]),
"x".to_strbuf());
}
#![feature(managed_boxes)]
trait Foo {
- fn foo(&self) -> StrBuf;
+ fn foo(&self) -> String;
}
impl<T:Foo> Foo for @T {
- fn foo(&self) -> StrBuf {
+ fn foo(&self) -> String {
format_strbuf!("@{}", (**self).foo())
}
}
impl Foo for uint {
- fn foo(&self) -> StrBuf {
+ fn foo(&self) -> String {
format_strbuf!("{}", *self)
}
}
let mut env = os::env().move_iter()
.map(|(ref k, ref v)| {
(k.to_strbuf(), v.to_strbuf())
- }).collect::<Vec<(StrBuf,StrBuf)>>();
+ }).collect::<Vec<(String,String)>>();
match env.iter()
.position(|&(ref s, _)| "RUST_BACKTRACE" == s.as_slice()) {
Some(i) => { env.remove(i); }
// except according to those terms.
pub fn main() {
- fn as_buf<T>(s: StrBuf, f: |StrBuf| -> T) -> T { f(s) }
- as_buf("foo".to_strbuf(), |foo: StrBuf| -> () println!("{}", foo) );
+ fn as_buf<T>(s: String, f: |String| -> T) -> T { f(s) }
+ as_buf("foo".to_strbuf(), |foo: String| -> () println!("{}", foo) );
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn foo(s: &StrBuf) -> bool {
+fn foo(s: &String) -> bool {
match s.as_slice() {
"kitty" => true,
_ => false
// except according to those terms.
trait Speak {
- fn say(&self, s:&str) -> StrBuf;
- fn hi(&self) -> StrBuf { hello(self) }
+ fn say(&self, s:&str) -> String;
+ fn hi(&self) -> String { hello(self) }
}
-fn hello<S:Speak>(s:&S) -> StrBuf{
+fn hello<S:Speak>(s:&S) -> String{
s.say("hello")
}
impl Speak for int {
- fn say(&self, s:&str) -> StrBuf {
+ fn say(&self, s:&str) -> String {
format_strbuf!("{}: {}", s, *self)
}
}
impl<T: Speak> Speak for Option<T> {
- fn say(&self, s:&str) -> StrBuf {
+ fn say(&self, s:&str) -> String {
match *self {
None => format_strbuf!("{} - none", s),
Some(ref x) => { format_strbuf!("something!{}", x.say(s)) }
}
}
-fn atol(s: StrBuf) -> int {
+fn atol(s: String) -> int {
s.as_slice().with_c_str(|x| unsafe { mlibc::atol(x) as int })
}
-fn atoll(s: StrBuf) -> i64 {
+fn atoll(s: String) -> i64 {
s.as_slice().with_c_str(|x| unsafe { mlibc::atoll(x) as i64 })
}
use std::task;
-fn child2(_s: StrBuf) { }
+fn child2(_s: String) { }
pub fn main() {
let _x = task::spawn(proc() child2("hi".to_strbuf()));
#![allow(unused_attribute)]
struct cat {
- name: StrBuf,
+ name: String,
}
impl Drop for cat {
#[cat_maker]
-fn cat(name: StrBuf) -> cat { cat{name: name,} }
+fn cat(name: String) -> cat { cat{name: name,} }
pub fn main() { let _kitty = cat("Spotty".to_strbuf()); }
#![allow(unused_attribute)]
struct cat {
- name: StrBuf,
+ name: String,
}
impl Drop for cat {
/**
Maybe it should technically be a kitten_maker.
*/
-fn cat(name: StrBuf) -> cat {
+fn cat(name: String) -> cat {
cat {
name: name
}
use std::to_str::ToStr;
use cci_class_cast::kitty::cat;
-fn print_out(thing: Box<ToStr>, expected: StrBuf) {
+fn print_out(thing: Box<ToStr>, expected: String) {
let actual = thing.to_str();
println!("{}", actual);
assert_eq!(actual.to_strbuf(), expected);
meows: uint,
how_hungry: int,
- name: StrBuf,
+ name: String,
}
impl noisy for cat {
}
}
-fn cat(in_x: uint, in_y: int, in_name: StrBuf) -> cat {
+fn cat(in_x: uint, in_y: int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
struct cat {
meows: uint,
how_hungry: int,
- name: StrBuf,
+ name: String,
}
impl noisy for cat {
}
}
-fn cat(in_x : uint, in_y : int, in_name: StrBuf) -> cat {
+fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
mod kitty {
pub struct cat {
meows: uint,
- name: StrBuf,
+ name: String,
}
impl cat {
- pub fn get_name(&self) -> StrBuf { self.name.clone() }
+ pub fn get_name(&self) -> String { self.name.clone() }
}
- pub fn cat(in_name: StrBuf) -> cat {
+ pub fn cat(in_name: String) -> cat {
cat {
name: in_name,
meows: 0u
}
pub fn main() {
- let mut nyan: cat<StrBuf> = cat::new(0, 2, "nyan".to_strbuf());
+ let mut nyan: cat<String> = cat::new(0, 2, "nyan".to_strbuf());
for _ in range(1u, 5) { nyan.speak(); }
assert!(*nyan.find(&1).unwrap() == "nyan".to_strbuf());
assert_eq!(nyan.find(&10), None);
meows: uint,
how_hungry : int,
- name : StrBuf,
+ name : String,
}
impl cat {
}
}
-fn cat(in_x : uint, in_y : int, in_name: StrBuf) -> cat {
+fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
meows : uint,
how_hungry : int,
- name : StrBuf,
+ name : String,
}
impl cat {
fn speak(&mut self) { self.meow(); }
}
-fn cat(in_x : uint, in_y : int, in_name: StrBuf) -> cat {
+fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
meows : uint,
how_hungry : int,
- name : StrBuf,
+ name : String,
}
impl cat {
}
}
-fn cat(in_x : uint, in_y : int, in_name: StrBuf) -> cat {
+fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
}
}
-fn print_out(thing: Box<ToStr>, expected: StrBuf) {
+fn print_out(thing: Box<ToStr>, expected: String) {
let actual = thing.to_str();
println!("{}", actual);
assert_eq!(actual.to_strbuf(), expected);
struct cat {
- name : StrBuf,
+ name : String,
}
-fn cat(in_name: StrBuf) -> cat {
+fn cat(in_name: String) -> cat {
cat {
name: in_name
}
meows : uint,
how_hungry : int,
- name : StrBuf,
+ name : String,
}
impl cat {
}
}
-fn cat(in_x : uint, in_y : int, in_name: StrBuf) -> cat {
+fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
use std::mem;
use std::io::stdio::println;
-fn call_it(f: proc(StrBuf) -> StrBuf) {
+fn call_it(f: proc(String) -> String) {
println!("{}", f("Fred".to_strbuf()))
}
call_it(proc(s) format_strbuf!("{}{}", greeting, s));
let greeting = "How's life, ".to_strbuf();
- call_it(proc(s: StrBuf) -> StrBuf {
+ call_it(proc(s: String) -> String {
format_strbuf!("{}{}", greeting, s)
});
fn nothing() { }
-fn putstr(_s: StrBuf) { }
+fn putstr(_s: String) { }
fn putint(_i: int) {
let mut i: int = 33;
pub mod rustrt {
extern {
#[cfg(bogus)]
- pub fn write() -> StrBuf;
- pub fn write() -> StrBuf;
+ pub fn write() -> String;
+ pub fn write() -> String;
}
}
}
#![feature(struct_variant)]
enum E {
- S0 { s: StrBuf },
+ S0 { s: String },
S1 { u: uint }
}
#[deriving(Hash)]
struct Person {
id: uint,
- name: StrBuf,
+ name: String,
phone: uint,
}
#[deriving(Show)]
enum B { B1, B2, B3 }
#[deriving(Show)]
-enum C { C1(int), C2(B), C3(StrBuf) }
+enum C { C1(int), C2(B), C3(String) }
#[deriving(Show)]
enum D { D1{ a: int } }
#[deriving(Show)]
// except according to those terms.
#[deriving(Eq, Show)]
-struct Foo(int, int, StrBuf);
+struct Foo(int, int, String);
pub fn main() {
let a1 = Foo(5, 6, "abc".to_strbuf());
fn f() -> int {
if true {
- let _s: StrBuf = "should not leak".to_strbuf();
+ let _s: String = "should not leak".to_strbuf();
return 1;
}
return 0;
test_color(imaginary, -1, "imaginary".to_strbuf());
}
-fn test_color(color: color, val: int, _name: StrBuf) {
+fn test_color(color: color, val: int, _name: String) {
assert!(color as int == val);
assert!(color as f64 == val as f64);
}
#![feature(struct_variant)]
enum Animal {
- Dog (StrBuf, f64),
- Cat { name: StrBuf, weight: f64 }
+ Dog (String, f64),
+ Cat { name: String, weight: f64 }
}
pub fn main() {
#![allow(dead_assignment)]
pub fn main() {
- let x : StrBuf = "hello".to_strbuf();
- let _y : StrBuf = "there".to_strbuf();
+ let x : String = "hello".to_strbuf();
+ let _y : String = "there".to_strbuf();
let mut z = "thing".to_strbuf();
z = x;
assert_eq!(z.as_slice()[0], ('h' as u8));
}
}
-fn strlen(str: StrBuf) -> uint {
+fn strlen(str: String) -> uint {
// C string is terminated with a zero
str.as_slice().with_c_str(|buf| {
unsafe {
This originally came from the word-count benchmark.
*/
-pub fn map(filename: StrBuf, emit: map_reduce::putter) {
+pub fn map(filename: String, emit: map_reduce::putter) {
emit(filename, "1".to_strbuf());
}
use std::str;
use std::task;
- pub type putter<'a> = |StrBuf, StrBuf|: 'a;
+ pub type putter<'a> = |String, String|: 'a;
- pub type mapper = extern fn(StrBuf, putter);
+ pub type mapper = extern fn(String, putter);
enum ctrl_proto { find_reducer(Vec<u8>, Sender<int>), mapper_done, }
- fn start_mappers(ctrl: Sender<ctrl_proto>, inputs: Vec<StrBuf>) {
+ fn start_mappers(ctrl: Sender<ctrl_proto>, inputs: Vec<String>) {
for i in inputs.iter() {
let ctrl = ctrl.clone();
let i = i.clone();
}
}
- fn map_task(ctrl: Sender<ctrl_proto>, input: StrBuf) {
+ fn map_task(ctrl: Sender<ctrl_proto>, input: String) {
let mut intermediates = HashMap::new();
- fn emit(im: &mut HashMap<StrBuf, int>,
- ctrl: Sender<ctrl_proto>, key: StrBuf,
- _val: StrBuf) {
+ fn emit(im: &mut HashMap<String, int>,
+ ctrl: Sender<ctrl_proto>, key: String,
+ _val: String) {
if im.contains_key(&key) {
return;
}
ctrl_clone.send(mapper_done);
}
- pub fn map_reduce(inputs: Vec<StrBuf>) {
+ pub fn map_reduce(inputs: Vec<String>) {
let (tx, rx) = channel();
// This task becomes the master control task. It spawns others
// to do the rest.
- let mut reducers: HashMap<StrBuf, int>;
+ let mut reducers: HashMap<String, int>;
reducers = HashMap::new();
}
enum HTMLFragment {
- tag(StrBuf, Vec<HTMLFragment> ),
- text(StrBuf),
+ tag(String, Vec<HTMLFragment> ),
+ text(String),
}
}
struct Test<'a> {
- args: &'a [StrBuf],
+ args: &'a [String],
io: &'a [StdioContainer]
}
}
}
-fn parent(flavor: StrBuf) {
+fn parent(flavor: String) {
let args = os::args();
let args = args.as_slice();
let mut p = io::process::Command::new(args[0].as_slice())
enum pattern { tabby, tortoiseshell, calico }
enum breed { beagle, rottweiler, pug }
-type name = StrBuf;
+type name = String;
enum ear_kind { lop, upright }
enum animal { cat(pattern), dog(breed), rabbit(name, ear_kind), tiger }
-fn noise(a: animal) -> Option<StrBuf> {
+fn noise(a: animal) -> Option<String> {
match a {
cat(..) => { Some("meow".to_strbuf()) }
dog(..) => { Some("woof".to_strbuf()) }
use collections::HashMap;
-fn add_interfaces(managed_ip: StrBuf, device: HashMap<StrBuf, int>) {
+fn add_interfaces(managed_ip: String, device: HashMap<String, int>) {
println!("{}, {:?}", managed_ip, device.get(&"interfaces".to_strbuf()));
}
int_value(i64),
}
-fn lookup(table: Box<json::Object>, key: StrBuf, default: StrBuf) -> StrBuf
+fn lookup(table: Box<json::Object>, key: String, default: String) -> String
{
match table.find(&key.to_strbuf()) {
option::Some(&json::String(ref s)) => {
}
}
-fn add_interface(_store: int, managed_ip: StrBuf, data: json::Json) -> (StrBuf, object)
+fn add_interface(_store: int, managed_ip: String, data: json::Json) -> (String, object)
{
match &data {
&json::Object(ref interface) => {
}
}
-fn add_interfaces(store: int, managed_ip: StrBuf, device: HashMap<StrBuf, json::Json>)
--> Vec<(StrBuf, object)> {
+fn add_interfaces(store: int, managed_ip: String, device: HashMap<String, json::Json>)
+-> Vec<(String, object)> {
match device.get(&"interfaces".to_strbuf())
{
&json::List(ref interfaces) =>
enum what { }
-fn what_to_str(x: what) -> StrBuf
+fn what_to_str(x: what) -> String
{
match x {
}
struct trie_node {
- content: Vec<StrBuf> ,
+ content: Vec<String> ,
children: Vec<trie_node> ,
}
-fn print_str_vector(vector: Vec<StrBuf> ) {
+fn print_str_vector(vector: Vec<String> ) {
for string in vector.iter() {
println!("{}", *string);
}
use std::path;
use std::result;
-type rsrc_loader = proc(path: &Path) -> result::Result<StrBuf, StrBuf>;
+type rsrc_loader = proc(path: &Path) -> result::Result<String, String>;
fn tester()
{
#![feature(managed_boxes)]
enum Token {
- Text(@StrBuf),
- ETag(@Vec<StrBuf> , @StrBuf),
- UTag(@Vec<StrBuf> , @StrBuf),
- Section(@Vec<StrBuf> , bool, @Vec<Token> , @StrBuf, @StrBuf, @StrBuf, @StrBuf, @StrBuf),
- IncompleteSection(@Vec<StrBuf> , bool, @StrBuf, bool),
- Partial(@StrBuf, @StrBuf, @StrBuf),
+ Text(@String),
+ ETag(@Vec<String> , @String),
+ UTag(@Vec<String> , @String),
+ Section(@Vec<String> , bool, @Vec<Token> , @String, @String, @String, @String, @String),
+ IncompleteSection(@Vec<String> , bool, @String, bool),
+ Partial(@String, @String, @String),
}
fn check_strs(actual: &str, expected: &str) -> bool
.map(|line| {
str::from_chars(line.as_slice()).to_strbuf()
})
- .collect::<Vec<StrBuf>>();
+ .collect::<Vec<String>>();
// Concatenate the lines together using a new-line.
write!(f, "{}", lines.connect("\n"))
enum Msg
{
- GetSamples(StrBuf, SamplesFn), // sample set name, callback which receives samples
+ GetSamples(String, SamplesFn), // sample set name, callback which receives samples
}
-fn foo(name: StrBuf, samples_chan: Sender<Msg>) {
+fn foo(name: String, samples_chan: Sender<Msg>) {
task::spawn(proc() {
let mut samples_chan = samples_chan;
let callback: SamplesFn = proc(buffer) {
pub fn main() {
trait Text {
- fn to_str(&self) -> StrBuf;
+ fn to_str(&self) -> String;
}
fn to_string(t: Box<Text>) {
#[deriving(Eq)]
struct Bike {
- name: StrBuf,
+ name: String,
}
pub fn main() {
Int(int),
Data(~[u8]),
List(~[Result]),
- Error(StrBuf),
- Status(StrBuf)
+ Error(String),
+ Status(String)
}
priv fn parse_data(len: uint, io: @io::Reader) -> Result {
return List(list);
}
-priv fn chop(s: StrBuf) -> StrBuf {
+priv fn chop(s: String) -> String {
s.slice(0, s.len() - 1).to_owned()
}
}
}
-priv fn cmd_to_str(cmd: ~[StrBuf]) -> StrBuf {
+priv fn cmd_to_str(cmd: ~[String]) -> String {
let mut res = "*".to_owned();
res.push_str(cmd.len().to_str());
res.push_str("\r\n");
res
}
-fn query(cmd: ~[StrBuf], sb: TcpSocketBuf) -> Result {
+fn query(cmd: ~[String], sb: TcpSocketBuf) -> Result {
let cmd = cmd_to_str(cmd);
//println!("{}", cmd);
sb.write_str(cmd);
res
}
-fn query2(cmd: ~[StrBuf]) -> Result {
+fn query2(cmd: ~[String]) -> Result {
let _cmd = cmd_to_str(cmd);
io::with_str_reader("$3\r\nXXX\r\n".to_owned())(|sb| {
let res = parse_response(@sb as @io::Reader);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn parse_args() -> StrBuf {
+fn parse_args() -> String {
let args = ::std::os::args();
let args = args.as_slice();
let mut n = 0;
*/
trait Debuggable {
- fn debug_name(&self) -> StrBuf;
+ fn debug_name(&self) -> String;
}
#[deriving(Clone)]
struct Thing {
- name: StrBuf,
+ name: String,
}
impl Thing {
}
impl Debuggable for Thing {
- fn debug_name(&self) -> StrBuf { self.name.clone() }
+ fn debug_name(&self) -> String { self.name.clone() }
}
fn print_name(x: &Debuggable)
static INVALID_ENUM : u32 = 0;
static INVALID_VALUE : u32 = 1;
-fn gl_err_str(err: u32) -> StrBuf
+fn gl_err_str(err: u32) -> String
{
match err
{
#![allow(dead_assignment)]
pub fn main() {
- let s: StrBuf = "foobar".to_strbuf();
+ let s: String = "foobar".to_strbuf();
let mut t: &str = s.as_slice();
t = t.slice(0, 3); // for master: str::view(t, 0, 3) maybe
}
struct Dog {
- name : StrBuf
+ name : String
}
trait Barks {
- fn bark(&self) -> StrBuf;
+ fn bark(&self) -> String;
}
impl Barks for Dog {
- fn bark(&self) -> StrBuf {
+ fn bark(&self) -> String {
return format!("woof! (I'm {})", self.name).to_strbuf();
}
}
fn main() {
let b = f::<int>();
assert!(b);
-}
\ No newline at end of file
+}
fn main() {
assert!(1i.new());
-}
\ No newline at end of file
+}
enum Either {
One,
- Other(StrBuf,StrBuf)
+ Other(String,String)
}
static one : Either = One;
// except according to those terms.
pub struct UninterpretedOption_NamePart {
- name_part: Option<StrBuf>,
+ name_part: Option<String>,
}
impl<'a> UninterpretedOption_NamePart {
#![feature(managed_boxes)]
-fn assert_repr_eq<T>(obj : T, expected : StrBuf) {
+fn assert_repr_eq<T>(obj : T, expected : String) {
assert_eq!(expected, format_strbuf!("{:?}", obj));
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn decode() -> StrBuf {
+fn decode() -> String {
'outer: loop {
let mut ch_start: uint;
break 'outer;
// except according to those terms.
struct A<'a> {
- a: &'a [StrBuf],
- b: Option<&'a [StrBuf]>,
+ a: &'a [String],
+ b: Option<&'a [String]>,
}
pub fn main() {
// except according to those terms.
trait Base: Base2 + Base3{
- fn foo(&self) -> StrBuf;
- fn foo1(&self) -> StrBuf;
- fn foo2(&self) -> StrBuf{
+ fn foo(&self) -> String;
+ fn foo1(&self) -> String;
+ fn foo2(&self) -> String{
"base foo2".to_strbuf()
}
}
trait Base2: Base3{
- fn baz(&self) -> StrBuf;
+ fn baz(&self) -> String;
}
trait Base3{
- fn root(&self) -> StrBuf;
+ fn root(&self) -> String;
}
trait Super: Base{
- fn bar(&self) -> StrBuf;
+ fn bar(&self) -> String;
}
struct X;
impl Base for X {
- fn foo(&self) -> StrBuf{
+ fn foo(&self) -> String{
"base foo".to_strbuf()
}
- fn foo1(&self) -> StrBuf{
+ fn foo1(&self) -> String{
"base foo1".to_strbuf()
}
}
impl Base2 for X {
- fn baz(&self) -> StrBuf{
+ fn baz(&self) -> String{
"base2 baz".to_strbuf()
}
}
impl Base3 for X {
- fn root(&self) -> StrBuf{
+ fn root(&self) -> String{
"base3 root".to_strbuf()
}
}
impl Super for X {
- fn bar(&self) -> StrBuf{
+ fn bar(&self) -> String{
"super bar".to_strbuf()
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-struct Wrapper(StrBuf);
+struct Wrapper(String);
impl Wrapper {
- pub fn new(wrapped: StrBuf) -> Wrapper {
+ pub fn new(wrapped: String) -> Wrapper {
Wrapper(wrapped)
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::strbuf::StrBuf;
+use std::string::String;
fn test_stack_assign() {
- let s: StrBuf = "a".to_strbuf();
+ let s: String = "a".to_strbuf();
println!("{}", s.clone());
- let t: StrBuf = "a".to_strbuf();
+ let t: String = "a".to_strbuf();
assert!(s == t);
- let u: StrBuf = "b".to_strbuf();
+ let u: String = "b".to_strbuf();
assert!((s != u));
}
fn test_heap_lit() { "a big string".to_strbuf(); }
fn test_heap_assign() {
- let s: StrBuf = "a big ol' string".to_strbuf();
- let t: StrBuf = "a big ol' string".to_strbuf();
+ let s: String = "a big ol' string".to_strbuf();
+ let t: String = "a big ol' string".to_strbuf();
assert!(s == t);
- let u: StrBuf = "a bad ol' string".to_strbuf();
+ let u: String = "a bad ol' string".to_strbuf();
assert!((s != u));
}
}
fn test_append() {
- let mut s = StrBuf::new();
+ let mut s = String::new();
s.push_str("a");
assert_eq!(s.as_slice(), "a");
- let mut s = StrBuf::from_str("a");
+ let mut s = String::from_str("a");
s.push_str("b");
println!("{}", s.clone());
assert_eq!(s.as_slice(), "ab");
- let mut s = StrBuf::from_str("c");
+ let mut s = String::from_str("c");
s.push_str("offee");
assert!(s.as_slice() == "coffee");
// Issue #1818
-fn lp<T>(s: StrBuf, f: |StrBuf| -> T) -> T {
+fn lp<T>(s: String, f: |String| -> T) -> T {
while false {
let r = f(s);
return (r);
fail!();
}
-fn apply<T>(s: StrBuf, f: |StrBuf| -> T) -> T {
- fn g<T>(s: StrBuf, f: |StrBuf| -> T) -> T {f(s)}
+fn apply<T>(s: String, f: |String| -> T) -> T {
+ fn g<T>(s: String, f: |String| -> T) -> T {f(s)}
g(s, |v| { let r = f(v); r })
}
#[deriving(Clone)]
enum foo {
a(uint),
- b(StrBuf),
+ b(String),
}
-fn check_log<T>(exp: StrBuf, v: T) {
+fn check_log<T>(exp: String, v: T) {
assert_eq!(exp, format_strbuf!("{:?}", v));
}
enum foo {
a(uint),
- b(StrBuf),
+ b(String),
c,
}
#![allow(unnecessary_allocation)]
-fn f1(ref_string: &str) -> StrBuf {
+fn f1(ref_string: &str) -> String {
match ref_string {
"a" => "found a".to_strbuf(),
"b" => "found b".to_strbuf(),
}
}
-fn f2(ref_string: &str) -> StrBuf {
+fn f2(ref_string: &str) -> String {
match ref_string {
"a" => "found a".to_strbuf(),
"b" => "found b".to_strbuf(),
}
}
-fn g1(ref_1: &str, ref_2: &str) -> StrBuf {
+fn g1(ref_1: &str, ref_2: &str) -> String {
match (ref_1, ref_2) {
("a", "b") => "found a,b".to_strbuf(),
("b", "c") => "found b,c".to_strbuf(),
}
}
-fn g2(ref_1: &str, ref_2: &str) -> StrBuf {
+fn g2(ref_1: &str, ref_2: &str) -> String {
match (ref_1, ref_2) {
("a", "b") => "found a,b".to_strbuf(),
("b", "c") => "found b,c".to_strbuf(),
pub fn main() {
match "test" { "not-test" => fail!(), "test" => (), _ => fail!() }
- enum t { tag1(StrBuf), tag2, }
+ enum t { tag1(String), tag2, }
match tag1("test".to_strbuf()) {
}
}
-fn transform(x: Option<int>) -> Option<StrBuf> {
+fn transform(x: Option<int>) -> Option<String> {
x.bind(|n| Some(*n + 1) ).bind(|n| Some(n.to_str().to_strbuf()) )
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::strbuf::StrBuf;
+use std::string::String;
struct StringBuffer {
- s: StrBuf,
+ s: String,
}
impl StringBuffer {
}
}
-fn to_str(sb: StringBuffer) -> StrBuf {
+fn to_str(sb: StringBuffer) -> String {
sb.s
}
pub fn main() {
let mut sb = StringBuffer {
- s: StrBuf::new(),
+ s: String::new(),
};
sb.append("Hello, ");
sb.append("World!");
// except according to those terms.
struct S {
- x: StrBuf
+ x: String
}
impl S {
check_type!(&17: &int);
check_type!(box 18: Box<int>);
check_type!(@19: @int);
- check_type!("foo".to_strbuf(): StrBuf);
+ check_type!("foo".to_strbuf(): String);
check_type!(vec!(20, 22): Vec<int> );
let mint: uint = unsafe { mem::transmute(main) };
check_type!(main: fn(), |pthing| {
use std::cell::RefCell;
use std::rc::Rc;
-use std::strbuf::StrBuf;
+use std::string::String;
#[deriving(Eq, Show)]
struct Point {
assert!(s.equiv(&("foo")));
assert_eq!(s.as_slice(), "foo");
- let mut_s = Rc::new(RefCell::new(StrBuf::from_str("foo")));
+ let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
mut_s.borrow_mut().push_str("bar");
// HACK assert_eq! would fail here because it stores the LHS and RHS in two locals.
assert!(mut_s.borrow().as_slice() == "foobar");
use std::cell::RefCell;
use std::rc::Rc;
-use std::strbuf::StrBuf;
+use std::string::String;
#[deriving(Eq, Show)]
struct Point {
assert_eq!(*s, "foo".to_owned());
assert_eq!((*s).as_slice(), "foo");
- let mut_s = Rc::new(RefCell::new(StrBuf::from_str("foo")));
+ let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
(*(*mut_s).borrow_mut()).push_str("bar");
// assert_eq! would fail here because it stores the LHS and RHS in two locals.
assert!((*(*mut_s).borrow()).as_slice() == "foobar");
// Issue #50.
-struct X { foo: StrBuf, bar: StrBuf }
+struct X { foo: String, bar: String }
pub fn main() {
let x = X {foo: "hello".to_strbuf(), bar: "world".to_strbuf()};
use std::intrinsics::{TyDesc, get_tydesc, visit_tydesc, TyVisitor, Disr, Opaque};
struct MyVisitor {
- types: Vec<StrBuf> ,
+ types: Vec<String> ,
}
impl TyVisitor for MyVisitor {
println!("type: {}", (*s).clone());
}
- let vec_types: Vec<StrBuf> = v.types.clone().move_iter().collect();
+ let vec_types: Vec<String> = v.types.clone().move_iter().collect();
assert_eq!(vec_types, vec!("bool".to_strbuf(), "int".to_strbuf(),
"i8".to_strbuf(), "i16".to_strbuf()));
}
-fn my_err(s: StrBuf) -> ! { println!("{}", s); fail!(); }
+fn my_err(s: String) -> ! { println!("{}", s); fail!(); }
fn okay(i: uint) -> int {
if i == 3u {
assert!(map.pop(&Slice("foo")).is_some());
assert_eq!(map.move_iter().map(|(k, v)| format_strbuf!("{}{}", k, v))
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.concat(),
"abc50bcd51cde52def53".to_owned());
}
#[deriving(Clone)]
struct Path_ {
global: bool,
- idents: Vec<StrBuf> ,
+ idents: Vec<String> ,
types: Vec<@ty>,
}
use std::task;
-fn x(s: StrBuf, n: int) {
+fn x(s: String, n: int) {
println!("{:?}", s);
println!("{:?}", n);
}
type ctx = Sender<int>;
-fn iotask(_tx: &ctx, ip: StrBuf) {
+fn iotask(_tx: &ctx, ip: String) {
assert_eq!(ip, "localhost".to_strbuf());
}
mod b {
use plus;
- impl plus for StrBuf { fn plus(&self) -> int { 200 } }
+ impl plus for String { fn plus(&self) -> int { 200 } }
}
trait uint_utils {
- fn str(&self) -> StrBuf;
+ fn str(&self) -> String;
fn multi(&self, f: |uint|);
}
impl uint_utils for uint {
- fn str(&self) -> StrBuf {
+ fn str(&self) -> String {
self.to_str().to_strbuf()
}
fn multi(&self, f: |uint|) {
pub fn main() {
- let a: StrBuf = "hello".to_strbuf();
- let b: StrBuf = "world".to_strbuf();
- let s: StrBuf = format_strbuf!("{}{}", a, b);
+ let a: String = "hello".to_strbuf();
+ let b: String = "world".to_strbuf();
+ let s: String = format_strbuf!("{}{}", a, b);
println!("{}", s.clone());
assert_eq!(s.as_slice()[9], 'd' as u8);
}
// except according to those terms.
pub fn main() {
- let a: StrBuf = "this \
+ let a: String = "this \
is a test".to_strbuf();
- let b: StrBuf =
+ let b: String =
"this \
is \
another \
pub fn main() {
// Make sure we properly handle repeated self-appends.
- let mut a: StrBuf = "A".to_strbuf();
+ let mut a: String = "A".to_strbuf();
let mut i = 20;
let mut expected_len = 1u;
while i > 0 {
// except according to those terms.
struct foo {
- x: StrBuf,
+ x: String,
}
impl Drop for foo {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-struct S { f0: StrBuf, f1: int }
+struct S { f0: String, f1: int }
pub fn main() {
let s = "Hello, world!".to_strbuf();
// except according to those terms.
struct S {
- f0: StrBuf,
- f1: StrBuf,
+ f0: String,
+ f1: String,
}
pub fn main() {
}
pub enum TestName {
- DynTestName(StrBuf)
+ DynTestName(String)
}
pub enum TestFn {
pub mod m1 {
pub mod m2 {
- pub fn where_am_i() -> StrBuf {
+ pub fn where_am_i() -> String {
(module_path!()).to_strbuf()
}
}
test_color(orange, 4, "orange".to_strbuf());
}
-fn test_color(color: color, val: int, name: StrBuf) {
+fn test_color(color: color, val: int, name: String) {
//assert!(unsafe::transmute(color) == val);
assert_eq!(color as int, val);
assert_eq!(color as f64, val as f64);
assert!(get_color_if(color) == name);
}
-fn get_color_alt(color: color) -> StrBuf {
+fn get_color_alt(color: color) -> String {
match color {
red => {"red".to_strbuf()}
green => {"green".to_strbuf()}
}
}
-fn get_color_if(color: color) -> StrBuf {
+fn get_color_if(color: color) -> String {
if color == red {"red".to_strbuf()}
else if color == green {"green".to_strbuf()}
else if color == blue {"blue".to_strbuf()}
// use of tail calls causes arg slot leaks, issue #160.
-fn inner(dummy: StrBuf, b: bool) { if b { return inner(dummy, false); } }
+fn inner(dummy: String, b: bool) { if b { return inner(dummy, false); } }
pub fn main() {
inner("hi".to_strbuf(), true);
use std::task;
-fn start(tx: &Sender<Sender<StrBuf>>) {
+fn start(tx: &Sender<Sender<String>>) {
let (tx2, rx) = channel();
tx.send(tx2);
task::spawn(proc() child("Hello".to_strbuf()) );
}
-fn child(_s: StrBuf) {
+fn child(_s: String) {
}
struct Catte {
num_whiskers: uint,
- name: StrBuf,
+ name: String,
}
struct Dogge {
bark_decibels: uint,
tricks_known: uint,
- name: StrBuf,
+ name: String,
}
struct Goldfyshe {
swim_speed: uint,
- name: StrBuf,
+ name: String,
}
impl Pet for Catte {
}
trait to_str {
- fn to_str_(&self) -> StrBuf;
+ fn to_str_(&self) -> String;
}
impl<T:to_str> to_str for Option<T> {
- fn to_str_(&self) -> StrBuf {
+ fn to_str_(&self) -> String {
match *self {
None => { "none".to_strbuf() }
Some(ref t) => format_strbuf!("some({})", t.to_str_()),
}
impl to_str for int {
- fn to_str_(&self) -> StrBuf {
+ fn to_str_(&self) -> String {
self.to_str().to_strbuf()
}
}
impl to_str for Tree {
- fn to_str_(&self) -> StrBuf {
+ fn to_str_(&self) -> String {
let Tree(t) = *self;
let this = t.borrow();
let (l, r) = (this.left, this.right);
}
}
-fn foo<T:to_str>(x: T) -> StrBuf { x.to_str_() }
+fn foo<T:to_str>(x: T) -> String { x.to_str_() }
pub fn main() {
let t1 = Tree(@RefCell::new(TreeR{left: None,
trait to_str {
- fn to_string(&self) -> StrBuf;
+ fn to_string(&self) -> String;
}
impl to_str for int {
- fn to_string(&self) -> StrBuf { self.to_str().to_strbuf() }
+ fn to_string(&self) -> String { self.to_str().to_strbuf() }
}
-impl to_str for StrBuf {
- fn to_string(&self) -> StrBuf { self.clone() }
+impl to_str for String {
+ fn to_string(&self) -> String { self.clone() }
}
impl to_str for () {
- fn to_string(&self) -> StrBuf { "()".to_strbuf() }
+ fn to_string(&self) -> String { "()".to_strbuf() }
}
trait map<T> {
}
}
-fn foo<U, T: map<U>>(x: T) -> Vec<StrBuf> {
+fn foo<U, T: map<U>>(x: T) -> Vec<String> {
x.map(|_e| "hi".to_strbuf() )
}
-fn bar<U:to_str,T:map<U>>(x: T) -> Vec<StrBuf> {
+fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> {
x.map(|_e| _e.to_string() )
}
pub fn main() {
assert_eq!(foo(vec!(1)), vec!("hi".to_strbuf()));
assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_strbuf(), "5".to_strbuf()));
- assert_eq!(bar::<StrBuf, Vec<StrBuf> >(vec!("x".to_strbuf(), "y".to_strbuf())),
+ assert_eq!(bar::<String, Vec<String> >(vec!("x".to_strbuf(), "y".to_strbuf())),
vec!("x".to_strbuf(), "y".to_strbuf()));
assert_eq!(bar::<(), Vec<()>>(vec!(())), vec!("()".to_strbuf()));
}
trait to_str {
- fn to_string(&self) -> StrBuf;
+ fn to_string(&self) -> String;
}
impl to_str for int {
- fn to_string(&self) -> StrBuf { self.to_str().to_strbuf() }
+ fn to_string(&self) -> String { self.to_str().to_strbuf() }
}
impl<T:to_str> to_str for Vec<T> {
- fn to_string(&self) -> StrBuf {
+ fn to_string(&self) -> String {
format_strbuf!("[{}]",
self.iter()
.map(|e| e.to_string())
- .collect::<Vec<StrBuf>>()
+ .collect::<Vec<String>>()
.connect(", "))
}
}
assert!(1.to_string() == "1".to_strbuf());
assert!((vec!(2, 3, 4)).to_string() == "[2, 3, 4]".to_strbuf());
- fn indirect<T:to_str>(x: T) -> StrBuf {
+ fn indirect<T:to_str>(x: T) -> String {
format_strbuf!("{}!", x.to_string())
}
assert!(indirect(vec!(10, 20)) == "[10, 20]!".to_strbuf());
- fn indirect2<T:to_str>(x: T) -> StrBuf {
+ fn indirect2<T:to_str>(x: T) -> String {
indirect(x)
}
assert!(indirect2(vec!(1)) == "[1]!".to_strbuf());
trait Foo {
- fn bar(&self) -> StrBuf {
+ fn bar(&self) -> String {
format_strbuf!("test")
}
}
assert_eq!(pi as int, '\u03a0' as int);
assert_eq!('\x0a' as int, '\n' as int);
- let bhutan: StrBuf = "འབྲུག་ཡུལ།".to_strbuf();
- let japan: StrBuf = "日本".to_strbuf();
- let uzbekistan: StrBuf = "Ўзбекистон".to_strbuf();
- let austria: StrBuf = "Österreich".to_strbuf();
+ let bhutan: String = "འབྲུག་ཡུལ།".to_strbuf();
+ let japan: String = "日本".to_strbuf();
+ let uzbekistan: String = "Ўзбекистон".to_strbuf();
+ let austria: String = "Österreich".to_strbuf();
- let bhutan_e: StrBuf =
+ let bhutan_e: String =
"\u0f60\u0f56\u0fb2\u0f74\u0f42\u0f0b\u0f61\u0f74\u0f63\u0f0d".to_strbuf();
- let japan_e: StrBuf = "\u65e5\u672c".to_strbuf();
- let uzbekistan_e: StrBuf =
+ let japan_e: String = "\u65e5\u672c".to_strbuf();
+ let uzbekistan_e: String =
"\u040e\u0437\u0431\u0435\u043a\u0438\u0441\u0442\u043e\u043d".to_strbuf();
- let austria_e: StrBuf = "\u00d6sterreich".to_strbuf();
+ let austria_e: String = "\u00d6sterreich".to_strbuf();
let oo: char = 'Ö';
assert_eq!(oo as int, 0xd6);
- fn check_str_eq(a: StrBuf, b: StrBuf) {
+ fn check_str_eq(a: String, b: String) {
let mut i: int = 0;
for ab in a.as_slice().bytes() {
println!("{}", i);
pub fn main() {
// Chars of 1, 2, 3, and 4 bytes
let chs: Vec<char> = vec!('e', 'é', '€', '\U00010000');
- let s: StrBuf = str::from_chars(chs.as_slice()).to_strbuf();
+ let s: String = str::from_chars(chs.as_slice()).to_strbuf();
let schs: Vec<char> = s.as_slice().chars().collect();
assert!(s.len() == 10u);
geordi_la_forge,
}
-fn boldly_go(_crew_member: crew_of_enterprise_d, _where: StrBuf) { }
+fn boldly_go(_crew_member: crew_of_enterprise_d, _where: String) { }
pub fn main() { boldly_go(worf, "where no one has gone before".to_strbuf()); }
struct Foo {
- string: StrBuf
+ string: String
}
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::strbuf::StrBuf;
+use std::string::String;
#[deriving(Eq)]
-enum t { a, b(StrBuf), }
+enum t { a, b(String), }
fn make(i: int) -> t {
if i > 10 { return a; }
- let mut s = StrBuf::from_str("hello");
+ let mut s = String::from_str("hello");
// Ensure s is non-const.
s.push_str("there");