std: remove str::{len, slice, is_empty} in favour of methods.

This commit is contained in:
Huon Wilson 2013-06-10 00:44:58 +10:00
parent b29cd22bce
commit c32fb53cf9
35 changed files with 185 additions and 207 deletions

View File

@ -803,7 +803,7 @@ An example of `use` declarations:
~~~~ ~~~~
use std::float::sin; use std::float::sin;
use std::str::{slice, contains}; use std::str::{from_chars, contains};
use std::option::Some; use std::option::Some;
fn main() { fn main() {
@ -814,8 +814,8 @@ fn main() {
info!(Some(1.0)); info!(Some(1.0));
// Equivalent to // Equivalent to
// 'info!(std::str::contains(std::str::slice("foo", 0, 1), "oo"));' // 'info!(std::str::contains(std::str::from_chars(&['f','o','o']), "oo"));'
info!(contains(slice("foo", 0, 1), "oo")); info!(contains(from_chars(&['f','o','o']), "oo"));
} }
~~~~ ~~~~

View File

@ -33,13 +33,13 @@ fn parse_expected(line_num: uint, line: ~str) -> ~[ExpectedError] {
let mut idx; let mut idx;
match str::find_str(line, error_tag) { match str::find_str(line, error_tag) {
None => return ~[], None => return ~[],
Some(nn) => { idx = (nn as uint) + str::len(error_tag); } Some(nn) => { idx = (nn as uint) + error_tag.len(); }
} }
// "//~^^^ kind msg" denotes a message expected // "//~^^^ kind msg" denotes a message expected
// three lines above current line: // three lines above current line:
let mut adjust_line = 0u; let mut adjust_line = 0u;
let len = str::len(line); let len = line.len();
while idx < len && line[idx] == ('^' as u8) { while idx < len && line[idx] == ('^' as u8) {
adjust_line += 1u; adjust_line += 1u;
idx += 1u; idx += 1u;
@ -52,12 +52,12 @@ fn parse_expected(line_num: uint, line: ~str) -> ~[ExpectedError] {
// FIXME: #4318 Instead of to_ascii and to_str_ascii, could use // FIXME: #4318 Instead of to_ascii and to_str_ascii, could use
// to_ascii_consume and to_str_consume to not do a unnecessary copy. // to_ascii_consume and to_str_consume to not do a unnecessary copy.
let kind = str::slice(line, start_kind, idx); let kind = line.slice(start_kind, idx);
let kind = kind.to_ascii().to_lower().to_str_ascii(); let kind = kind.to_ascii().to_lower().to_str_ascii();
// Extract msg: // Extract msg:
while idx < len && line[idx] == (' ' as u8) { idx += 1u; } while idx < len && line[idx] == (' ' as u8) { idx += 1u; }
let msg = str::slice(line, idx, len).to_owned(); let msg = line.slice(idx, len).to_owned();
debug!("line=%u kind=%s msg=%s", line_num - adjust_line, kind, msg); debug!("line=%u kind=%s msg=%s", line_num - adjust_line, kind, msg);

View File

@ -177,8 +177,8 @@ fn parse_name_value_directive(line: &str,
let keycolon = directive + ":"; let keycolon = directive + ":";
match str::find_str(line, keycolon) { match str::find_str(line, keycolon) {
Some(colon) => { Some(colon) => {
let value = str::slice(line, colon + str::len(keycolon), let value = line.slice(colon + keycolon.len(),
str::len(line)).to_owned(); line.len()).to_owned();
debug!("%s: %s", directive, value); debug!("%s: %s", directive, value);
Some(value) Some(value)
} }

View File

@ -247,7 +247,7 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result {
let mut names; let mut names;
let mut i_arg = None; let mut i_arg = None;
if cur[1] == '-' as u8 { if cur[1] == '-' as u8 {
let tail = str::slice(cur, 2, curlen); let tail = cur.slice(2, curlen);
let tail_eq: ~[&str] = tail.split_iter('=').collect(); let tail_eq: ~[&str] = tail.split_iter('=').collect();
if tail_eq.len() <= 1 { if tail_eq.len() <= 1 {
names = ~[Long(tail.to_owned())]; names = ~[Long(tail.to_owned())];

View File

@ -1809,7 +1809,7 @@ mod test {
} }
fn buf_write<W:io::Writer>(w: &W, val: &str) { fn buf_write<W:io::Writer>(w: &W, val: &str) {
debug!("BUF_WRITE: val len %?", str::len(val)); debug!("BUF_WRITE: val len %?", val.len());
do str::byte_slice(val) |b_slice| { do str::byte_slice(val) |b_slice| {
debug!("BUF_WRITE: b_slice len %?", debug!("BUF_WRITE: b_slice len %?",
b_slice.len()); b_slice.len());

View File

@ -291,7 +291,7 @@ pub fn decode_form_urlencoded(s: &[u8]) -> HashMap<~str, ~[~str]> {
fn split_char_first(s: &str, c: char) -> (~str, ~str) { fn split_char_first(s: &str, c: char) -> (~str, ~str) {
let len = str::len(s); let len = s.len();
let mut index = len; let mut index = len;
let mut mat = 0; let mut mat = 0;
do io::with_str_reader(s) |rdr| { do io::with_str_reader(s) |rdr| {
@ -307,16 +307,16 @@ fn split_char_first(s: &str, c: char) -> (~str, ~str) {
} }
} }
if index+mat == len { if index+mat == len {
return (str::slice(s, 0, index).to_owned(), ~""); return (s.slice(0, index).to_owned(), ~"");
} else { } else {
return (str::slice(s, 0, index).to_owned(), return (s.slice(0, index).to_owned(),
str::slice(s, index + mat, str::len(s)).to_owned()); s.slice(index + mat, s.len()).to_owned());
} }
} }
fn userinfo_from_str(uinfo: &str) -> UserInfo { fn userinfo_from_str(uinfo: &str) -> UserInfo {
let (user, p) = split_char_first(uinfo, ':'); let (user, p) = split_char_first(uinfo, ':');
let pass = if str::len(p) == 0 { let pass = if p.is_empty() {
None None
} else { } else {
Some(p) Some(p)
@ -333,7 +333,7 @@ fn userinfo_to_str(userinfo: &UserInfo) -> ~str {
fn query_from_str(rawquery: &str) -> Query { fn query_from_str(rawquery: &str) -> Query {
let mut query: Query = ~[]; let mut query: Query = ~[];
if str::len(rawquery) != 0 { if !rawquery.is_empty() {
for rawquery.split_iter('&').advance |p| { for rawquery.split_iter('&').advance |p| {
let (k, v) = split_char_first(p, '='); let (k, v) = split_char_first(p, '=');
query.push((decode_component(k), decode_component(v))); query.push((decode_component(k), decode_component(v)));
@ -373,7 +373,7 @@ pub fn get_scheme(rawurl: &str) -> Result<(~str, ~str), ~str> {
return Err(~"url: Scheme cannot be empty."); return Err(~"url: Scheme cannot be empty.");
} else { } else {
return Ok((rawurl.slice(0,i).to_owned(), return Ok((rawurl.slice(0,i).to_owned(),
rawurl.slice(i+1,str::len(rawurl)).to_owned())); rawurl.slice(i+1,rawurl.len()).to_owned()));
} }
} }
_ => { _ => {
@ -475,7 +475,7 @@ fn get_authority(rawurl: &str) ->
} }
Ip6Host => { Ip6Host => {
if colon_count > 7 { if colon_count > 7 {
host = str::slice(rawurl, begin, i).to_owned(); host = rawurl.slice(begin, i).to_owned();
pos = i; pos = i;
st = InPort; st = InPort;
} }
@ -492,13 +492,13 @@ fn get_authority(rawurl: &str) ->
colon_count = 0; // reset count colon_count = 0; // reset count
match st { match st {
Start => { Start => {
let user = str::slice(rawurl, begin, i).to_owned(); let user = rawurl.slice(begin, i).to_owned();
userinfo = Some(UserInfo::new(user, None)); userinfo = Some(UserInfo::new(user, None));
st = InHost; st = InHost;
} }
PassHostPort => { PassHostPort => {
let user = str::slice(rawurl, begin, pos).to_owned(); let user = rawurl.slice(begin, pos).to_owned();
let pass = str::slice(rawurl, pos+1, i).to_owned(); let pass = rawurl.slice(pos+1, i).to_owned();
userinfo = Some(UserInfo::new(user, Some(pass))); userinfo = Some(UserInfo::new(user, Some(pass)));
st = InHost; st = InHost;
} }
@ -529,31 +529,31 @@ fn get_authority(rawurl: &str) ->
match st { match st {
Start => { Start => {
if host_is_end_plus_one() { if host_is_end_plus_one() {
host = str::slice(rawurl, begin, end+1).to_owned(); host = rawurl.slice(begin, end+1).to_owned();
} else { } else {
host = str::slice(rawurl, begin, end).to_owned(); host = rawurl.slice(begin, end).to_owned();
} }
} }
PassHostPort | Ip6Port => { PassHostPort | Ip6Port => {
if in != Digit { if in != Digit {
return Err(~"Non-digit characters in port."); return Err(~"Non-digit characters in port.");
} }
host = str::slice(rawurl, begin, pos).to_owned(); host = rawurl.slice(begin, pos).to_owned();
port = Some(str::slice(rawurl, pos+1, end).to_owned()); port = Some(rawurl.slice(pos+1, end).to_owned());
} }
Ip6Host | InHost => { Ip6Host | InHost => {
host = str::slice(rawurl, begin, end).to_owned(); host = rawurl.slice(begin, end).to_owned();
} }
InPort => { InPort => {
if in != Digit { if in != Digit {
return Err(~"Non-digit characters in port."); return Err(~"Non-digit characters in port.");
} }
port = Some(str::slice(rawurl, pos+1, end).to_owned()); port = Some(rawurl.slice(pos+1, end).to_owned());
} }
} }
let rest = if host_is_end_plus_one() { ~"" } let rest = if host_is_end_plus_one() { ~"" }
else { str::slice(rawurl, end, len).to_owned() }; else { rawurl.slice(end, len).to_owned() };
return Ok((userinfo, host, port, rest)); return Ok((userinfo, host, port, rest));
} }
@ -561,7 +561,7 @@ fn get_authority(rawurl: &str) ->
// returns the path and unparsed part of url, or an error // returns the path and unparsed part of url, or an error
fn get_path(rawurl: &str, authority: bool) -> fn get_path(rawurl: &str, authority: bool) ->
Result<(~str, ~str), ~str> { Result<(~str, ~str), ~str> {
let len = str::len(rawurl); let len = rawurl.len();
let mut end = len; let mut end = len;
for rawurl.iter().enumerate().advance |(i,c)| { for rawurl.iter().enumerate().advance |(i,c)| {
match c { match c {
@ -585,8 +585,8 @@ fn get_path(rawurl: &str, authority: bool) ->
} }
} }
return Ok((decode_component(str::slice(rawurl, 0, end)), return Ok((decode_component(rawurl.slice(0, end)),
str::slice(rawurl, end, len).to_owned())); rawurl.slice(end, len).to_owned()));
} }
// returns the parsed query and the fragment, if present // returns the parsed query and the fragment, if present
@ -594,16 +594,16 @@ fn get_query_fragment(rawurl: &str) ->
Result<(Query, Option<~str>), ~str> { Result<(Query, Option<~str>), ~str> {
if !str::starts_with(rawurl, "?") { if !str::starts_with(rawurl, "?") {
if str::starts_with(rawurl, "#") { if str::starts_with(rawurl, "#") {
let f = decode_component(str::slice(rawurl, let f = decode_component(rawurl.slice(
1, 1,
str::len(rawurl))); rawurl.len()));
return Ok((~[], Some(f))); return Ok((~[], Some(f)));
} else { } else {
return Ok((~[], None)); return Ok((~[], None));
} }
} }
let (q, r) = split_char_first(str::slice(rawurl, 1, rawurl.len()), '#'); let (q, r) = split_char_first(rawurl.slice(1, rawurl.len()), '#');
let f = if str::len(r) != 0 { let f = if r.len() != 0 {
Some(decode_component(r)) } else { None }; Some(decode_component(r)) } else { None };
return Ok((query_from_str(q), f)); return Ok((query_from_str(q), f));
} }

View File

@ -71,7 +71,7 @@ pub fn empty() -> Rope {
* * the function runs in linear time. * * the function runs in linear time.
*/ */
pub fn of_str(str: @~str) -> Rope { pub fn of_str(str: @~str) -> Rope {
return of_substr(str, 0u, str::len(*str)); return of_substr(str, 0u, str.len());
} }
/** /**
@ -98,7 +98,7 @@ pub fn of_str(str: @~str) -> Rope {
*/ */
pub fn of_substr(str: @~str, byte_offset: uint, byte_len: uint) -> Rope { pub fn of_substr(str: @~str, byte_offset: uint, byte_len: uint) -> Rope {
if byte_len == 0u { return node::Empty; } if byte_len == 0u { return node::Empty; }
if byte_offset + byte_len > str::len(*str) { fail!(); } if byte_offset + byte_len > str.len() { fail!(); }
return node::Content(node::of_substr(str, byte_offset, byte_len)); return node::Content(node::of_substr(str, byte_offset, byte_len));
} }
@ -657,7 +657,7 @@ pub mod node {
* the length of `str`. * the length of `str`.
*/ */
pub fn of_str(str: @~str) -> @Node { pub fn of_str(str: @~str) -> @Node {
return of_substr(str, 0u, str::len(*str)); return of_substr(str, 0u, str.len());
} }
/** /**
@ -705,7 +705,7 @@ pub mod node {
*/ */
pub fn of_substr_unsafer(str: @~str, byte_start: uint, byte_len: uint, pub fn of_substr_unsafer(str: @~str, byte_start: uint, byte_len: uint,
char_len: uint) -> @Node { char_len: uint) -> @Node {
assert!((byte_start + byte_len <= str::len(*str))); assert!((byte_start + byte_len <= str.len()));
let candidate = @Leaf(Leaf { let candidate = @Leaf(Leaf {
byte_offset: byte_start, byte_offset: byte_start,
byte_len: byte_len, byte_len: byte_len,
@ -1292,9 +1292,7 @@ mod tests {
node::Leaf(x) => { node::Leaf(x) => {
str::push_str( str::push_str(
str, str,
str::slice( x.content.slice(x.byte_offset, x.byte_offset + x.byte_len));
*x.content, x.byte_offset,
x.byte_offset + x.byte_len));
} }
node::Concat(ref x) => { node::Concat(ref x) => {
aux(str, x.left); aux(str, x.left);
@ -1340,7 +1338,7 @@ mod tests {
assert!(rope_to_string(r) == *sample); assert!(rope_to_string(r) == *sample);
let mut string_iter = 0u; let mut string_iter = 0u;
let string_len = str::len(*sample); let string_len = sample.len();
let mut rope_iter = iterator::char::start(r); let mut rope_iter = iterator::char::start(r);
let mut equal = true; let mut equal = true;
while equal { while equal {

View File

@ -281,7 +281,6 @@ pub fn sha1() -> @Sha1 {
mod tests { mod tests {
use sha1; use sha1;
use core::str;
use core::vec; use core::vec;
#[test] #[test]
@ -396,7 +395,7 @@ mod tests {
// Test that it works when accepting the message in pieces // Test that it works when accepting the message in pieces
for tests.each |t| { for tests.each |t| {
let len = str::len(t.input); let len = t.input.len();
let mut left = len; let mut left = len;
while left > 0u { while left > 0u {
let take = (left + 1u) / 2u; let take = (left + 1u) / 2u;

View File

@ -279,7 +279,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
match strs[i] { // can't use let due to stage0 bugs match strs[i] { // can't use let due to stage0 bugs
(ref needle, value) => { (ref needle, value) => {
if match_str(ss, pos, *needle) { if match_str(ss, pos, *needle) {
return Some((value, pos + str::len(*needle))); return Some((value, pos + needle.len()));
} }
} }
} }
@ -598,7 +598,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
// It's odd, but to maintain compatibility with c's // It's odd, but to maintain compatibility with c's
// strptime we ignore the timezone. // strptime we ignore the timezone.
let mut pos = pos; let mut pos = pos;
let len = str::len(s); let len = s.len();
while pos < len { while pos < len {
let range = str::char_range_at(s, pos); let range = str::char_range_at(s, pos);
pos = range.next; pos = range.next;
@ -651,7 +651,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result<Tm, ~str> {
tm_nsec: 0_i32, tm_nsec: 0_i32,
}; };
let mut pos = 0u; let mut pos = 0u;
let len = str::len(s); let len = s.len();
let mut result = Err(~"Invalid time"); let mut result = Err(~"Invalid time");
while !rdr.eof() && pos < len { while !rdr.eof() && pos < len {

View File

@ -376,7 +376,7 @@ pub fn check_variants_T<T:Copy>(crate: @ast::crate,
pub fn last_part(filename: ~str) -> ~str { pub fn last_part(filename: ~str) -> ~str {
let ix = str::rfind_char(filename, '/').get(); let ix = str::rfind_char(filename, '/').get();
str::slice(filename, ix + 1u, str::len(filename) - 3u).to_owned() filename.slice(ix + 1u, filename.len() - 3u).to_owned()
} }
pub enum happiness { pub enum happiness {
@ -434,7 +434,7 @@ pub fn check_running(exe_filename: &Path) -> happiness {
"/Users/jruderman/scripts/timed_run_rust_program.py", "/Users/jruderman/scripts/timed_run_rust_program.py",
[exe_filename.to_str()]); [exe_filename.to_str()]);
let comb = str::from_bytes(p.output) + "\n" + str::from_bytes(p.error); let comb = str::from_bytes(p.output) + "\n" + str::from_bytes(p.error);
if str::len(comb) > 1u { if comb.len() > 1u {
error!("comb comb comb: %?", comb); error!("comb comb comb: %?", comb);
} }
@ -712,4 +712,3 @@ pub mod core {
pub use std::cmp; pub use std::cmp;
pub use std::sys; pub use std::sys;
} }

View File

@ -686,7 +686,7 @@ pub fn mangle(sess: Session, ss: path) -> ~str {
for ss.each |s| { for ss.each |s| {
match *s { path_name(s) | path_mod(s) => { match *s { path_name(s) | path_mod(s) => {
let sani = sanitize(*sess.str_of(s)); let sani = sanitize(*sess.str_of(s));
n += fmt!("%u%s", str::len(sani), sani); n += fmt!("%u%s", sani.len(), sani);
} } } }
} }
n += "E"; // End name-sequence. n += "E"; // End name-sequence.

View File

@ -186,7 +186,7 @@ fn get_rustpkg_lib_path_nearest() -> Result<Path, ~str> {
// On Unix should be "lib", on windows "bin" // On Unix should be "lib", on windows "bin"
pub fn libdir() -> ~str { pub fn libdir() -> ~str {
let libdir = env!("CFG_LIBDIR"); let libdir = env!("CFG_LIBDIR");
if str::is_empty(libdir) { if libdir.is_empty() {
fail!("rustc compiled without CFG_LIBDIR environment variable"); fail!("rustc compiled without CFG_LIBDIR environment variable");
} }
libdir.to_owned() libdir.to_owned()

View File

@ -849,14 +849,14 @@ fn check_item_non_camel_case_types(cx: &Context, it: @ast::item) {
fn ident_without_trailing_underscores<'r>(ident: &'r str) -> &'r str { fn ident_without_trailing_underscores<'r>(ident: &'r str) -> &'r str {
match str::rfind(ident, |c| c != '_') { match str::rfind(ident, |c| c != '_') {
Some(idx) => str::slice(ident, 0, idx + 1), Some(idx) => ident.slice(0, idx + 1),
None => ident, // all underscores None => ident, // all underscores
} }
} }
fn ident_without_leading_underscores<'r>(ident: &'r str) -> &'r str { fn ident_without_leading_underscores<'r>(ident: &'r str) -> &'r str {
match str::find(ident, |c| c != '_') { match str::find(ident, |c| c != '_') {
Some(idx) => str::slice(ident, idx, ident.len()), Some(idx) => ident.slice(idx, ident.len()),
None => ident // all underscores None => ident // all underscores
} }
} }

View File

@ -2575,7 +2575,7 @@ impl Resolver {
if "???" == module_name { if "???" == module_name {
let span = span { let span = span {
lo: span.lo, lo: span.lo,
hi: span.lo + BytePos(str::len(*segment_name)), hi: span.lo + BytePos(segment_name.len()),
expn_info: span.expn_info, expn_info: span.expn_info,
}; };
self.session.span_err(span, self.session.span_err(span,
@ -4830,7 +4830,7 @@ impl Resolver {
if values.len() > 0 && if values.len() > 0 &&
values[smallest] != uint::max_value && values[smallest] != uint::max_value &&
values[smallest] < str::len(name) + 2 && values[smallest] < name.len() + 2 &&
values[smallest] <= max_distance && values[smallest] <= max_distance &&
maybes[smallest] != name.to_owned() { maybes[smallest] != name.to_owned() {

View File

@ -1221,7 +1221,7 @@ pub fn C_estr_slice(cx: @CrateContext, s: @~str) -> ValueRef {
pub fn C_postr(s: &str) -> ValueRef { pub fn C_postr(s: &str) -> ValueRef {
unsafe { unsafe {
return do str::as_c_str(s) |buf| { return do str::as_c_str(s) |buf| {
llvm::LLVMConstString(buf, str::len(s) as c_uint, False) llvm::LLVMConstString(buf, s.len() as c_uint, False)
}; };
} }
} }

View File

@ -245,8 +245,8 @@ fn get_cache(cx: @CrateContext) -> metadata_cache {
fn get_file_path_and_dir(work_dir: &str, full_path: &str) -> (~str, ~str) { fn get_file_path_and_dir(work_dir: &str, full_path: &str) -> (~str, ~str) {
(if str::starts_with(full_path, work_dir) { (if str::starts_with(full_path, work_dir) {
str::slice(full_path, str::len(work_dir) + 1u, full_path.slice(work_dir.len() + 1u,
str::len(full_path)).to_owned() full_path.len()).to_owned()
} else { } else {
full_path.to_owned() full_path.to_owned()
}, work_dir.to_owned()) }, work_dir.to_owned())

View File

@ -485,7 +485,7 @@ pub fn parameterized(cx: ctxt,
pub fn ty_to_short_str(cx: ctxt, typ: t) -> ~str { pub fn ty_to_short_str(cx: ctxt, typ: t) -> ~str {
let mut s = encoder::encoded_ty(cx, typ); let mut s = encoder::encoded_ty(cx, typ);
if str::len(s) >= 32u { s = str::slice(s, 0u, 32u).to_owned(); } if s.len() >= 32u { s = s.slice(0u, 32u).to_owned(); }
return s; return s;
} }

View File

@ -94,7 +94,7 @@ fn parse_desc(desc: ~str) -> Option<~str> {
match first_sentence(copy desc) { match first_sentence(copy desc) {
Some(first_sentence) => { Some(first_sentence) => {
if str::len(first_sentence) <= max_brief_len { if first_sentence.len() <= max_brief_len {
Some(first_sentence) Some(first_sentence)
} else { } else {
None None
@ -133,7 +133,7 @@ fn first_sentence_(s: &str) -> ~str {
}; };
match idx { match idx {
Some(idx) if idx > 2u => { Some(idx) if idx > 2u => {
str::to_owned(str::slice(s, 0, idx - 1)) str::to_owned(s.slice(0, idx - 1))
} }
_ => { _ => {
if str::ends_with(s, ".") { if str::ends_with(s, ".") {
@ -165,7 +165,7 @@ pub fn paragraphs(s: &str) -> ~[~str] {
whitespace_lines = 0; whitespace_lines = 0;
accum = if str::is_empty(accum) { accum = if accum.is_empty() {
copy *line copy *line
} else { } else {
accum + "\n" + *line accum + "\n" + *line

View File

@ -154,7 +154,7 @@ fn sectionalize(desc: Option<~str>) -> (Option<~str>, ~[doc::Section]) {
fn parse_header(line: ~str) -> Option<~str> { fn parse_header(line: ~str) -> Option<~str> {
if str::starts_with(line, "# ") { if str::starts_with(line, "# ") {
Some(str::slice(line, 2u, str::len(line)).to_owned()) Some(line.slice(2u, line.len()).to_owned())
} else { } else {
None None
} }

View File

@ -83,8 +83,8 @@ fn unindent(s: &str) -> ~str {
if str::is_whitespace(*line) { if str::is_whitespace(*line) {
copy *line copy *line
} else { } else {
assert!(str::len(*line) >= min_indent); assert!(line.len() >= min_indent);
str::slice(*line, min_indent, str::len(*line)).to_owned() line.slice(min_indent, line.len()).to_owned()
} }
}; };
str::connect(unindented, "\n") str::connect(unindented, "\n")

View File

@ -748,7 +748,7 @@ impl<T:Reader> ReaderUtil for T {
if self.eof() && line.is_empty() { break; } if self.eof() && line.is_empty() { break; }
// trim the \n, so that each_line is consistent with read_line // trim the \n, so that each_line is consistent with read_line
let n = str::len(line); let n = line.len();
if line[n-1] == '\n' as u8 { if line[n-1] == '\n' as u8 {
unsafe { str::raw::set_len(&mut line, n-1); } unsafe { str::raw::set_len(&mut line, n-1); }
} }

View File

@ -525,7 +525,7 @@ pub fn self_exe_path() -> Option<Path> {
*/ */
pub fn homedir() -> Option<Path> { pub fn homedir() -> Option<Path> {
return match getenv("HOME") { return match getenv("HOME") {
Some(ref p) => if !str::is_empty(*p) { Some(ref p) => if !p.is_empty() {
Some(Path(*p)) Some(Path(*p))
} else { } else {
secondary() secondary()
@ -541,7 +541,7 @@ pub fn homedir() -> Option<Path> {
#[cfg(windows)] #[cfg(windows)]
fn secondary() -> Option<Path> { fn secondary() -> Option<Path> {
do getenv(~"USERPROFILE").chain |p| { do getenv(~"USERPROFILE").chain |p| {
if !str::is_empty(p) { if !p.is_empty() {
Some(Path(p)) Some(Path(p))
} else { } else {
None None
@ -566,7 +566,7 @@ pub fn tmpdir() -> Path {
fn getenv_nonempty(v: &str) -> Option<Path> { fn getenv_nonempty(v: &str) -> Option<Path> {
match getenv(v) { match getenv(v) {
Some(x) => Some(x) =>
if str::is_empty(x) { if x.is_empty() {
None None
} else { } else {
Some(Path(x)) Some(Path(x))
@ -1449,6 +1449,7 @@ mod tests {
use rand; use rand;
use run; use run;
use str; use str;
use str::StrSlice;
use vec; use vec;
use libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR}; use libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR};
@ -1606,7 +1607,7 @@ mod tests {
#[test] #[test]
fn tmpdir() { fn tmpdir() {
assert!(!str::is_empty(os::tmpdir().to_str())); assert!(!os::tmpdir().to_str().is_empty());
} }
// Issue #712 // Issue #712
@ -1671,7 +1672,7 @@ mod tests {
unsafe { unsafe {
let tempdir = getcwd(); // would like to use $TMPDIR, let tempdir = getcwd(); // would like to use $TMPDIR,
// doesn't seem to work on Linux // doesn't seem to work on Linux
assert!((str::len(tempdir.to_str()) > 0u)); assert!((tempdir.to_str().len() > 0u));
let in = tempdir.push("in.txt"); let in = tempdir.push("in.txt");
let out = tempdir.push("out.txt"); let out = tempdir.push("out.txt");
@ -1686,7 +1687,7 @@ mod tests {
let mut buf = str::to_bytes(s) + [0 as u8]; let mut buf = str::to_bytes(s) + [0 as u8];
do vec::as_mut_buf(buf) |b, _len| { do vec::as_mut_buf(buf) |b, _len| {
assert!((libc::fwrite(b as *c_void, 1u as size_t, assert!((libc::fwrite(b as *c_void, 1u as size_t,
(str::len(s) + 1u) as size_t, ostream) (s.len() + 1u) as size_t, ostream)
== buf.len() as size_t)) == buf.len() as size_t))
} }
assert_eq!(libc::fclose(ostream), (0u as c_int)); assert_eq!(libc::fclose(ostream), (0u as c_int));

View File

@ -110,7 +110,7 @@ pub fn from_bytes_slice<'a>(vector: &'a [u8]) -> &'a str {
/// Copy a slice into a new unique str /// Copy a slice into a new unique str
#[inline(always)] #[inline(always)]
pub fn to_owned(s: &str) -> ~str { pub fn to_owned(s: &str) -> ~str {
unsafe { raw::slice_bytes_owned(s, 0, len(s)) } unsafe { raw::slice_bytes_owned(s, 0, s.len()) }
} }
impl ToStr for ~str { impl ToStr for ~str {
@ -148,7 +148,7 @@ pub fn push_char(s: &mut ~str, ch: char) {
else if code < max_four_b { 4u } else if code < max_four_b { 4u }
else if code < max_five_b { 5u } else if code < max_five_b { 5u }
else { 6u }; else { 6u };
let len = len(*s); let len = s.len();
let new_len = len + nb; let new_len = len + nb;
reserve_at_least(&mut *s, new_len); reserve_at_least(&mut *s, new_len);
let off = len; let off = len;
@ -453,7 +453,7 @@ Section: Adding to and removing from a string
* If the string does not contain any characters * If the string does not contain any characters
*/ */
pub fn pop_char(s: &mut ~str) -> char { pub fn pop_char(s: &mut ~str) -> char {
let end = len(*s); let end = s.len();
assert!(end > 0u); assert!(end > 0u);
let CharRange {ch, next} = char_range_at_reverse(*s, end); let CharRange {ch, next} = char_range_at_reverse(*s, end);
unsafe { raw::set_len(s, next); } unsafe { raw::set_len(s, next); }
@ -469,7 +469,7 @@ pub fn pop_char(s: &mut ~str) -> char {
*/ */
pub fn shift_char(s: &mut ~str) -> char { pub fn shift_char(s: &mut ~str) -> char {
let CharRange {ch, next} = char_range_at(*s, 0u); let CharRange {ch, next} = char_range_at(*s, 0u);
*s = unsafe { raw::slice_bytes_owned(*s, next, len(*s)) }; *s = unsafe { raw::slice_bytes_owned(*s, next, s.len()) };
return ch; return ch;
} }
@ -485,7 +485,7 @@ pub fn shift_char(s: &mut ~str) -> char {
#[inline] #[inline]
pub fn slice_shift_char<'a>(s: &'a str) -> (char, &'a str) { pub fn slice_shift_char<'a>(s: &'a str) -> (char, &'a str) {
let CharRange {ch, next} = char_range_at(s, 0u); let CharRange {ch, next} = char_range_at(s, 0u);
let next_s = unsafe { raw::slice_bytes(s, next, len(s)) }; let next_s = unsafe { raw::slice_bytes(s, next, s.len()) };
return (ch, next_s); return (ch, next_s);
} }
@ -554,7 +554,7 @@ pub fn trim_chars<'a>(s: &'a str, chars_to_trim: &[char]) -> &'a str {
pub fn trim_left<'a>(s: &'a str) -> &'a str { pub fn trim_left<'a>(s: &'a str) -> &'a str {
match find(s, |c| !char::is_whitespace(c)) { match find(s, |c| !char::is_whitespace(c)) {
None => "", None => "",
Some(first) => unsafe { raw::slice_bytes(s, first, len(s)) } Some(first) => unsafe { raw::slice_bytes(s, first, s.len()) }
} }
} }
@ -584,7 +584,7 @@ Section: Transforming strings
pub fn to_bytes(s: &str) -> ~[u8] { pub fn to_bytes(s: &str) -> ~[u8] {
unsafe { unsafe {
let mut v: ~[u8] = ::cast::transmute(to_owned(s)); let mut v: ~[u8] = ::cast::transmute(to_owned(s));
vec::raw::set_len(&mut v, len(s)); vec::raw::set_len(&mut v, s.len());
v v
} }
} }
@ -618,19 +618,7 @@ pub fn to_chars(s: &str) -> ~[char] {
* `begin`. * `begin`.
*/ */
pub fn substr<'a>(s: &'a str, begin: uint, n: uint) -> &'a str { pub fn substr<'a>(s: &'a str, begin: uint, n: uint) -> &'a str {
slice(s, begin, begin + count_bytes(s, begin, n)) s.slice(begin, begin + count_bytes(s, begin, n))
}
/**
* Returns a slice of the given string from the byte range [`begin`..`end`)
*
* Fails when `begin` and `end` do not point to valid characters or beyond
* the last character of the string
*/
pub fn slice<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
assert!(is_char_boundary(s, begin));
assert!(is_char_boundary(s, end));
unsafe { raw::slice_bytes(s, begin, end) }
} }
/// An iterator over the substrings of a string, separated by `sep`. /// An iterator over the substrings of a string, separated by `sep`.
@ -724,7 +712,7 @@ impl<'self, Sep: StrCharSplitSeparator> Iterator<&'self str> for StrCharSplitIte
// See Issue #1932 for why this is a naive search // See Issue #1932 for why this is a naive search
fn iter_matches<'a,'b>(s: &'a str, sep: &'b str, fn iter_matches<'a,'b>(s: &'a str, sep: &'b str,
f: &fn(uint, uint) -> bool) -> bool { f: &fn(uint, uint) -> bool) -> bool {
let (sep_len, l) = (len(sep), len(s)); let (sep_len, l) = (sep.len(), s.len());
assert!(sep_len > 0u); assert!(sep_len > 0u);
let mut (i, match_start, match_i) = (0u, 0u, 0u); let mut (i, match_start, match_i) = (0u, 0u, 0u);
@ -759,7 +747,7 @@ fn iter_between_matches<'a,'b>(s: &'a str,
if !f(last_end, from) { return false; } if !f(last_end, from) { return false; }
last_end = to; last_end = to;
} }
return f(last_end, len(s)); return f(last_end, s.len());
} }
/** /**
@ -889,7 +877,7 @@ pub fn each_split_within<'a>(ss: &'a str,
let mut state = A; let mut state = A;
let mut cont = true; let mut cont = true;
let slice: &fn() = || { cont = it(slice(ss, slice_start, last_end)) }; let slice: &fn() = || { cont = it(ss.slice(slice_start, last_end)) };
let machine: &fn((uint, char)) -> bool = |(i, c)| { let machine: &fn((uint, char)) -> bool = |(i, c)| {
let whitespace = if char::is_whitespace(c) { Ws } else { Cr }; let whitespace = if char::is_whitespace(c) { Ws } else { Cr };
@ -902,7 +890,7 @@ pub fn each_split_within<'a>(ss: &'a str,
(B, Cr, UnderLim) => { B } (B, Cr, UnderLim) => { B }
(B, Cr, OverLim) if (i - last_start + 1) > lim (B, Cr, OverLim) if (i - last_start + 1) > lim
=> fail!("word starting with %? longer than limit!", => fail!("word starting with %? longer than limit!",
self::slice(ss, last_start, i + 1)), ss.slice(last_start, i + 1)),
(B, Cr, OverLim) => { slice(); slice_start = last_start; B } (B, Cr, OverLim) => { slice(); slice_start = last_start; B }
(B, Ws, UnderLim) => { last_end = i; C } (B, Ws, UnderLim) => { last_end = i; C }
(B, Ws, OverLim) => { last_end = i; slice(); A } (B, Ws, OverLim) => { last_end = i; slice(); A }
@ -1178,7 +1166,7 @@ Section: Iterating through strings
/// Apply a function to each character /// Apply a function to each character
pub fn map(ss: &str, ff: &fn(char) -> char) -> ~str { pub fn map(ss: &str, ff: &fn(char) -> char) -> ~str {
let mut result = ~""; let mut result = ~"";
reserve(&mut result, len(ss)); reserve(&mut result, ss.len());
for ss.iter().advance |cc| { for ss.iter().advance |cc| {
str::push_char(&mut result, ff(cc)); str::push_char(&mut result, ff(cc));
} }
@ -1203,7 +1191,7 @@ Section: Searching
* or `none` if there is no match * or `none` if there is no match
*/ */
pub fn find_char(s: &str, c: char) -> Option<uint> { pub fn find_char(s: &str, c: char) -> Option<uint> {
find_char_between(s, c, 0u, len(s)) find_char_between(s, c, 0u, s.len())
} }
/** /**
@ -1223,11 +1211,11 @@ pub fn find_char(s: &str, c: char) -> Option<uint> {
* *
* # Failure * # Failure
* *
* `start` must be less than or equal to `len(s)`. `start` must be the * `start` must be less than or equal to `s.len()`. `start` must be the
* index of a character boundary, as defined by `is_char_boundary`. * index of a character boundary, as defined by `is_char_boundary`.
*/ */
pub fn find_char_from(s: &str, c: char, start: uint) -> Option<uint> { pub fn find_char_from(s: &str, c: char, start: uint) -> Option<uint> {
find_char_between(s, c, start, len(s)) find_char_between(s, c, start, s.len())
} }
/** /**
@ -1248,14 +1236,14 @@ pub fn find_char_from(s: &str, c: char, start: uint) -> Option<uint> {
* # Failure * # Failure
* *
* `start` must be less than or equal to `end` and `end` must be less than * `start` must be less than or equal to `end` and `end` must be less than
* or equal to `len(s)`. `start` must be the index of a character boundary, * or equal to `s.len()`. `start` must be the index of a character boundary,
* as defined by `is_char_boundary`. * as defined by `is_char_boundary`.
*/ */
pub fn find_char_between(s: &str, c: char, start: uint, end: uint) pub fn find_char_between(s: &str, c: char, start: uint, end: uint)
-> Option<uint> { -> Option<uint> {
if c < 128u as char { if c < 128u as char {
assert!(start <= end); assert!(start <= end);
assert!(end <= len(s)); assert!(end <= s.len());
let mut i = start; let mut i = start;
let b = c as u8; let b = c as u8;
while i < end { while i < end {
@ -1282,7 +1270,7 @@ pub fn find_char_between(s: &str, c: char, start: uint, end: uint)
* or `none` if there is no match * or `none` if there is no match
*/ */
pub fn rfind_char(s: &str, c: char) -> Option<uint> { pub fn rfind_char(s: &str, c: char) -> Option<uint> {
rfind_char_between(s, c, len(s), 0u) rfind_char_between(s, c, s.len(), 0u)
} }
/** /**
@ -1302,7 +1290,7 @@ pub fn rfind_char(s: &str, c: char) -> Option<uint> {
* *
* # Failure * # Failure
* *
* `start` must be less than or equal to `len(s)`. `start` must be * `start` must be less than or equal to `s.len()`. `start` must be
* the index of a character boundary, as defined by `is_char_boundary`. * the index of a character boundary, as defined by `is_char_boundary`.
*/ */
pub fn rfind_char_from(s: &str, c: char, start: uint) -> Option<uint> { pub fn rfind_char_from(s: &str, c: char, start: uint) -> Option<uint> {
@ -1327,13 +1315,13 @@ pub fn rfind_char_from(s: &str, c: char, start: uint) -> Option<uint> {
* # Failure * # Failure
* *
* `end` must be less than or equal to `start` and `start` must be less than * `end` must be less than or equal to `start` and `start` must be less than
* or equal to `len(s)`. `start` must be the index of a character boundary, * or equal to `s.len()`. `start` must be the index of a character boundary,
* as defined by `is_char_boundary`. * as defined by `is_char_boundary`.
*/ */
pub fn rfind_char_between(s: &str, c: char, start: uint, end: uint) -> Option<uint> { pub fn rfind_char_between(s: &str, c: char, start: uint, end: uint) -> Option<uint> {
if c < 128u as char { if c < 128u as char {
assert!(start >= end); assert!(start >= end);
assert!(start <= len(s)); assert!(start <= s.len());
let mut i = start; let mut i = start;
let b = c as u8; let b = c as u8;
while i > end { while i > end {
@ -1361,7 +1349,7 @@ pub fn rfind_char_between(s: &str, c: char, start: uint, end: uint) -> Option<ui
* or `none` if there is no match * or `none` if there is no match
*/ */
pub fn find(s: &str, f: &fn(char) -> bool) -> Option<uint> { pub fn find(s: &str, f: &fn(char) -> bool) -> Option<uint> {
find_between(s, 0u, len(s), f) find_between(s, 0u, s.len(), f)
} }
/** /**
@ -1381,12 +1369,12 @@ pub fn find(s: &str, f: &fn(char) -> bool) -> Option<uint> {
* *
* # Failure * # Failure
* *
* `start` must be less than or equal to `len(s)`. `start` must be the * `start` must be less than or equal to `s.len()`. `start` must be the
* index of a character boundary, as defined by `is_char_boundary`. * index of a character boundary, as defined by `is_char_boundary`.
*/ */
pub fn find_from(s: &str, start: uint, f: &fn(char) pub fn find_from(s: &str, start: uint, f: &fn(char)
-> bool) -> Option<uint> { -> bool) -> Option<uint> {
find_between(s, start, len(s), f) find_between(s, start, s.len(), f)
} }
/** /**
@ -1408,12 +1396,12 @@ pub fn find_from(s: &str, start: uint, f: &fn(char)
* # Failure * # Failure
* *
* `start` must be less than or equal to `end` and `end` must be less than * `start` must be less than or equal to `end` and `end` must be less than
* or equal to `len(s)`. `start` must be the index of a character * or equal to `s.len()`. `start` must be the index of a character
* boundary, as defined by `is_char_boundary`. * boundary, as defined by `is_char_boundary`.
*/ */
pub fn find_between(s: &str, start: uint, end: uint, f: &fn(char) -> bool) -> Option<uint> { pub fn find_between(s: &str, start: uint, end: uint, f: &fn(char) -> bool) -> Option<uint> {
assert!(start <= end); assert!(start <= end);
assert!(end <= len(s)); assert!(end <= s.len());
assert!(is_char_boundary(s, start)); assert!(is_char_boundary(s, start));
let mut i = start; let mut i = start;
while i < end { while i < end {
@ -1439,7 +1427,7 @@ pub fn find_between(s: &str, start: uint, end: uint, f: &fn(char) -> bool) -> Op
* or `none` if there is no match * or `none` if there is no match
*/ */
pub fn rfind(s: &str, f: &fn(char) -> bool) -> Option<uint> { pub fn rfind(s: &str, f: &fn(char) -> bool) -> Option<uint> {
rfind_between(s, len(s), 0u, f) rfind_between(s, s.len(), 0u, f)
} }
/** /**
@ -1459,7 +1447,7 @@ pub fn rfind(s: &str, f: &fn(char) -> bool) -> Option<uint> {
* *
* # Failure * # Failure
* *
* `start` must be less than or equal to `len(s)', `start` must be the * `start` must be less than or equal to `s.len()', `start` must be the
* index of a character boundary, as defined by `is_char_boundary` * index of a character boundary, as defined by `is_char_boundary`
*/ */
pub fn rfind_from(s: &str, start: uint, f: &fn(char) -> bool) -> Option<uint> { pub fn rfind_from(s: &str, start: uint, f: &fn(char) -> bool) -> Option<uint> {
@ -1485,12 +1473,12 @@ pub fn rfind_from(s: &str, start: uint, f: &fn(char) -> bool) -> Option<uint> {
* # Failure * # Failure
* *
* `end` must be less than or equal to `start` and `start` must be less * `end` must be less than or equal to `start` and `start` must be less
* than or equal to `len(s)`. `start` must be the index of a character * than or equal to `s.len()`. `start` must be the index of a character
* boundary, as defined by `is_char_boundary` * boundary, as defined by `is_char_boundary`
*/ */
pub fn rfind_between(s: &str, start: uint, end: uint, f: &fn(char) -> bool) -> Option<uint> { pub fn rfind_between(s: &str, start: uint, end: uint, f: &fn(char) -> bool) -> Option<uint> {
assert!(start >= end); assert!(start >= end);
assert!(start <= len(s)); assert!(start <= s.len());
assert!(is_char_boundary(s, start)); assert!(is_char_boundary(s, start));
let mut i = start; let mut i = start;
while i > end { while i > end {
@ -1522,7 +1510,7 @@ fn match_at<'a,'b>(haystack: &'a str, needle: &'b str, at: uint) -> bool {
* or `none` if there is no match * or `none` if there is no match
*/ */
pub fn find_str<'a,'b>(haystack: &'a str, needle: &'b str) -> Option<uint> { pub fn find_str<'a,'b>(haystack: &'a str, needle: &'b str) -> Option<uint> {
find_str_between(haystack, needle, 0u, len(haystack)) find_str_between(haystack, needle, 0u, haystack.len())
} }
/** /**
@ -1542,13 +1530,13 @@ pub fn find_str<'a,'b>(haystack: &'a str, needle: &'b str) -> Option<uint> {
* *
* # Failure * # Failure
* *
* `start` must be less than or equal to `len(s)` * `start` must be less than or equal to `s.len()`
*/ */
pub fn find_str_from<'a,'b>(haystack: &'a str, pub fn find_str_from<'a,'b>(haystack: &'a str,
needle: &'b str, needle: &'b str,
start: uint) start: uint)
-> Option<uint> { -> Option<uint> {
find_str_between(haystack, needle, start, len(haystack)) find_str_between(haystack, needle, start, haystack.len())
} }
/** /**
@ -1569,7 +1557,7 @@ pub fn find_str_from<'a,'b>(haystack: &'a str,
* # Failure * # Failure
* *
* `start` must be less than or equal to `end` and `end` must be less than * `start` must be less than or equal to `end` and `end` must be less than
* or equal to `len(s)`. * or equal to `s.len()`.
*/ */
pub fn find_str_between<'a,'b>(haystack: &'a str, pub fn find_str_between<'a,'b>(haystack: &'a str,
needle: &'b str, needle: &'b str,
@ -1577,8 +1565,8 @@ pub fn find_str_between<'a,'b>(haystack: &'a str,
end:uint) end:uint)
-> Option<uint> { -> Option<uint> {
// See Issue #1932 for why this is a naive search // See Issue #1932 for why this is a naive search
assert!(end <= len(haystack)); assert!(end <= haystack.len());
let needle_len = len(needle); let needle_len = needle.len();
if needle_len == 0u { return Some(start); } if needle_len == 0u { return Some(start); }
if needle_len > end { return None; } if needle_len > end { return None; }
@ -1624,7 +1612,7 @@ pub fn contains_char(haystack: &str, needle: char) -> bool {
* * needle - The string to look for * * needle - The string to look for
*/ */
pub fn starts_with<'a,'b>(haystack: &'a str, needle: &'b str) -> bool { pub fn starts_with<'a,'b>(haystack: &'a str, needle: &'b str) -> bool {
let (haystack_len, needle_len) = (len(haystack), len(needle)); let (haystack_len, needle_len) = (haystack.len(), needle.len());
if needle_len == 0u { true } if needle_len == 0u { true }
else if needle_len > haystack_len { false } else if needle_len > haystack_len { false }
else { match_at(haystack, needle, 0u) } else { match_at(haystack, needle, 0u) }
@ -1639,7 +1627,7 @@ pub fn starts_with<'a,'b>(haystack: &'a str, needle: &'b str) -> bool {
* * needle - The string to look for * * needle - The string to look for
*/ */
pub fn ends_with<'a,'b>(haystack: &'a str, needle: &'b str) -> bool { pub fn ends_with<'a,'b>(haystack: &'a str, needle: &'b str) -> bool {
let (haystack_len, needle_len) = (len(haystack), len(needle)); let (haystack_len, needle_len) = (haystack.len(), needle.len());
if needle_len == 0u { true } if needle_len == 0u { true }
else if needle_len > haystack_len { false } else if needle_len > haystack_len { false }
else { match_at(haystack, needle, haystack_len - needle_len) } else { match_at(haystack, needle, haystack_len - needle_len) }
@ -1649,10 +1637,6 @@ pub fn ends_with<'a,'b>(haystack: &'a str, needle: &'b str) -> bool {
Section: String properties Section: String properties
*/ */
/// Returns true if the string has length 0
#[inline(always)]
pub fn is_empty(s: &str) -> bool { len(s) == 0u }
/** /**
* Returns true if the string contains only whitespace * Returns true if the string contains only whitespace
* *
@ -1671,15 +1655,9 @@ fn is_alphanumeric(s: &str) -> bool {
s.iter().all(char::is_alphanumeric) s.iter().all(char::is_alphanumeric)
} }
/// Returns the string length/size in bytes not counting the null terminator
#[inline(always)]
pub fn len(s: &str) -> uint {
do as_buf(s) |_p, n| { n - 1u }
}
/// Returns the number of characters that a string holds /// Returns the number of characters that a string holds
#[inline(always)] #[inline(always)]
pub fn char_len(s: &str) -> uint { count_chars(s, 0u, len(s)) } pub fn char_len(s: &str) -> uint { count_chars(s, 0u, s.len()) }
/* /*
Section: Misc Section: Misc
@ -1828,7 +1806,7 @@ pub fn count_chars(s: &str, start: uint, end: uint) -> uint {
pub fn count_bytes<'b>(s: &'b str, start: uint, n: uint) -> uint { pub fn count_bytes<'b>(s: &'b str, start: uint, n: uint) -> uint {
assert!(is_char_boundary(s, start)); assert!(is_char_boundary(s, start));
let mut (end, cnt) = (start, n); let mut (end, cnt) = (start, n);
let l = len(s); let l = s.len();
while cnt > 0u { while cnt > 0u {
assert!(end < l); assert!(end < l);
let next = char_range_at(s, end).next; let next = char_range_at(s, end).next;
@ -1856,7 +1834,7 @@ pub fn utf8_char_width(b: u8) -> uint {
* character sequence. * character sequence.
*/ */
pub fn is_char_boundary(s: &str, index: uint) -> bool { pub fn is_char_boundary(s: &str, index: uint) -> bool {
if index == len(s) { return true; } if index == s.len() { return true; }
let b = s[index]; let b = s[index];
return b < 128u8 || b >= 192u8; return b < 128u8 || b >= 192u8;
} }
@ -1873,7 +1851,7 @@ pub fn is_char_boundary(s: &str, index: uint) -> bool {
* ~~~ {.rust} * ~~~ {.rust}
* let s = "中华Việt Nam"; * let s = "中华Việt Nam";
* let i = 0u; * let i = 0u;
* while i < str::len(s) { * while i < s.len() {
* let CharRange {ch, next} = str::char_range_at(s, i); * let CharRange {ch, next} = str::char_range_at(s, i);
* std::io::println(fmt!("%u: %c",i,ch)); * std::io::println(fmt!("%u: %c",i,ch));
* i = next; * i = next;
@ -2242,7 +2220,7 @@ pub fn capacity(s: &const ~str) -> uint {
/// Escape each char in `s` with char::escape_default. /// Escape each char in `s` with char::escape_default.
pub fn escape_default(s: &str) -> ~str { pub fn escape_default(s: &str) -> ~str {
let mut out: ~str = ~""; let mut out: ~str = ~"";
reserve_at_least(&mut out, str::len(s)); reserve_at_least(&mut out, s.len());
for s.iter().advance |c| { for s.iter().advance |c| {
push_str(&mut out, char::escape_default(c)); push_str(&mut out, char::escape_default(c));
} }
@ -2252,7 +2230,7 @@ pub fn escape_default(s: &str) -> ~str {
/// Escape each char in `s` with char::escape_unicode. /// Escape each char in `s` with char::escape_unicode.
pub fn escape_unicode(s: &str) -> ~str { pub fn escape_unicode(s: &str) -> ~str {
let mut out: ~str = ~""; let mut out: ~str = ~"";
reserve_at_least(&mut out, str::len(s)); reserve_at_least(&mut out, s.len());
for s.iter().advance |c| { for s.iter().advance |c| {
push_str(&mut out, char::escape_unicode(c)); push_str(&mut out, char::escape_unicode(c));
} }
@ -2265,7 +2243,7 @@ pub mod raw {
use libc; use libc;
use ptr; use ptr;
use str::raw; use str::raw;
use str::{as_buf, is_utf8, len, reserve_at_least}; use str::{as_buf, is_utf8, reserve_at_least};
use vec; use vec;
/// Create a Rust string from a null-terminated *u8 buffer /// Create a Rust string from a null-terminated *u8 buffer
@ -2394,7 +2372,7 @@ pub mod raw {
/// Removes the last byte from a string and returns it. (Not UTF-8 safe). /// Removes the last byte from a string and returns it. (Not UTF-8 safe).
pub unsafe fn pop_byte(s: &mut ~str) -> u8 { pub unsafe fn pop_byte(s: &mut ~str) -> u8 {
let len = len(*s); let len = s.len();
assert!((len > 0u)); assert!((len > 0u));
let b = s[len - 1u]; let b = s[len - 1u];
set_len(s, len - 1u); set_len(s, len - 1u);
@ -2403,7 +2381,7 @@ pub mod raw {
/// Removes the first byte from a string and returns it. (Not UTF-8 safe). /// Removes the first byte from a string and returns it. (Not UTF-8 safe).
pub unsafe fn shift_byte(s: &mut ~str) -> u8 { pub unsafe fn shift_byte(s: &mut ~str) -> u8 {
let len = len(*s); let len = s.len();
assert!((len > 0u)); assert!((len > 0u));
let b = s[0]; let b = s[0];
*s = raw::slice_bytes_owned(*s, 1u, len); *s = raw::slice_bytes_owned(*s, 1u, len);
@ -2567,7 +2545,7 @@ impl<'self> StrSlice<'self> for &'self str {
} }
/// Returns true if the string has length 0 /// Returns true if the string has length 0
#[inline] #[inline]
fn is_empty(&self) -> bool { is_empty(*self) } fn is_empty(&self) -> bool { self.len() == 0 }
/** /**
* Returns true if the string contains only whitespace * Returns true if the string contains only whitespace
* *
@ -2584,7 +2562,9 @@ impl<'self> StrSlice<'self> for &'self str {
fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) } fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) }
/// Returns the size in bytes not counting the null terminator /// Returns the size in bytes not counting the null terminator
#[inline(always)] #[inline(always)]
fn len(&self) -> uint { len(*self) } fn len(&self) -> uint {
do as_buf(*self) |_p, n| { n - 1u }
}
/// Returns the number of characters that a string holds /// Returns the number of characters that a string holds
#[inline] #[inline]
fn char_len(&self) -> uint { char_len(*self) } fn char_len(&self) -> uint { char_len(*self) }
@ -2597,7 +2577,9 @@ impl<'self> StrSlice<'self> for &'self str {
*/ */
#[inline] #[inline]
fn slice(&self, begin: uint, end: uint) -> &'self str { fn slice(&self, begin: uint, end: uint) -> &'self str {
slice(*self, begin, end) assert!(is_char_boundary(*self, begin));
assert!(is_char_boundary(*self, end));
unsafe { raw::slice_bytes(*self, begin, end) }
} }
/** /**
* Splits a string into a vector of the substrings separated by a given * Splits a string into a vector of the substrings separated by a given
@ -2788,8 +2770,8 @@ mod tests {
#[test] #[test]
fn test_eq_slice() { fn test_eq_slice() {
assert!((eq_slice(slice("foobar", 0, 3), "foo"))); assert!((eq_slice("foobar".slice(0, 3), "foo")));
assert!((eq_slice(slice("barfoo", 3, 6), "foo"))); assert!((eq_slice("barfoo".slice(3, 6), "foo")));
assert!((!eq_slice("foo1", "foo2"))); assert!((!eq_slice("foo1", "foo2")));
} }
@ -2803,13 +2785,13 @@ mod tests {
#[test] #[test]
fn test_len() { fn test_len() {
assert_eq!(len(""), 0u); assert_eq!("".len(), 0u);
assert_eq!(len("hello world"), 11u); assert_eq!("hello world".len(), 11u);
assert_eq!(len("\x63"), 1u); assert_eq!("\x63".len(), 1u);
assert_eq!(len("\xa2"), 2u); assert_eq!("\xa2".len(), 2u);
assert_eq!(len("\u03c0"), 2u); assert_eq!("\u03c0".len(), 2u);
assert_eq!(len("\u2620"), 3u); assert_eq!("\u2620".len(), 3u);
assert_eq!(len("\U0001d11e"), 4u); assert_eq!("\U0001d11e".len(), 4u);
assert_eq!(char_len(""), 0u); assert_eq!(char_len(""), 0u);
assert_eq!(char_len("hello world"), 11u); assert_eq!(char_len("hello world"), 11u);
@ -2937,7 +2919,7 @@ mod tests {
#[test] #[test]
fn test_substr() { fn test_substr() {
fn t(a: &str, b: &str, start: int) { fn t(a: &str, b: &str, start: int) {
assert_eq!(substr(a, start as uint, len(b)), b); assert_eq!(substr(a, start as uint, b.len()), b);
} }
t("hello", "llo", 2); t("hello", "llo", 2);
t("hello", "el", 1); t("hello", "el", 1);
@ -3044,8 +3026,8 @@ mod tests {
#[test] #[test]
fn test_is_empty() { fn test_is_empty() {
assert!((is_empty(""))); assert!("".is_empty());
assert!((!is_empty("a"))); assert!(!"a".is_empty());
} }
#[test] #[test]
@ -3101,16 +3083,16 @@ mod tests {
#[test] #[test]
fn test_slice() { fn test_slice() {
assert_eq!("ab", slice("abc", 0, 2)); assert_eq!("ab", "abc".slice(0, 2));
assert_eq!("bc", slice("abc", 1, 3)); assert_eq!("bc", "abc".slice(1, 3));
assert_eq!("", slice("abc", 1, 1)); assert_eq!("", "abc".slice(1, 1));
assert_eq!("\u65e5", slice("\u65e5\u672c", 0, 3)); assert_eq!("\u65e5", "\u65e5\u672c".slice(0, 3));
let data = "ประเทศไทย中华"; let data = "ประเทศไทย中华";
assert_eq!("", slice(data, 0, 3)); assert_eq!("", data.slice(0, 3));
assert_eq!("", slice(data, 3, 6)); assert_eq!("", data.slice(3, 6));
assert_eq!("", slice(data, 3, 3)); assert_eq!("", data.slice(3, 3));
assert_eq!("", slice(data, 30, 33)); assert_eq!("", data.slice(30, 33));
fn a_million_letter_X() -> ~str { fn a_million_letter_X() -> ~str {
let mut i = 0; let mut i = 0;
@ -3129,23 +3111,23 @@ mod tests {
} }
let letters = a_million_letter_X(); let letters = a_million_letter_X();
assert!(half_a_million_letter_X() == assert!(half_a_million_letter_X() ==
slice(letters, 0u, 3u * 500000u).to_owned()); letters.slice(0u, 3u * 500000u).to_owned());
} }
#[test] #[test]
fn test_slice_2() { fn test_slice_2() {
let ss = "中华Việt Nam"; let ss = "中华Việt Nam";
assert_eq!("", slice(ss, 3u, 6u)); assert_eq!("", ss.slice(3u, 6u));
assert_eq!("Việt Nam", slice(ss, 6u, 16u)); assert_eq!("Việt Nam", ss.slice(6u, 16u));
assert_eq!("ab", slice("abc", 0u, 2u)); assert_eq!("ab", "abc".slice(0u, 2u));
assert_eq!("bc", slice("abc", 1u, 3u)); assert_eq!("bc", "abc".slice(1u, 3u));
assert_eq!("", slice("abc", 1u, 1u)); assert_eq!("", "abc".slice(1u, 1u));
assert_eq!("", slice(ss, 0u, 3u)); assert_eq!("", ss.slice(0u, 3u));
assert_eq!("华V", slice(ss, 3u, 7u)); assert_eq!("华V", ss.slice(3u, 7u));
assert_eq!("", slice(ss, 3u, 3u)); assert_eq!("", ss.slice(3u, 3u));
/*0: 中 /*0: 中
3: 3:
6: V 6: V
@ -3162,7 +3144,7 @@ mod tests {
#[should_fail] #[should_fail]
#[ignore(cfg(windows))] #[ignore(cfg(windows))]
fn test_slice_fail() { fn test_slice_fail() {
slice("中华Việt Nam", 0u, 2u); "中华Việt Nam".slice(0u, 2u);
} }
#[test] #[test]
@ -3420,8 +3402,8 @@ mod tests {
#[test] #[test]
fn test_subslice_offset() { fn test_subslice_offset() {
let a = "kernelsprite"; let a = "kernelsprite";
let b = slice(a, 7, len(a)); let b = a.slice(7, a.len());
let c = slice(a, 0, len(a) - 6); let c = a.slice(0, a.len() - 6);
assert_eq!(subslice_offset(a, b), 7); assert_eq!(subslice_offset(a, b), 7);
assert_eq!(subslice_offset(a, c), 0); assert_eq!(subslice_offset(a, c), 0);
@ -3448,7 +3430,7 @@ mod tests {
let v: ~[u8] = to_bytes(s1); let v: ~[u8] = to_bytes(s1);
let s2: ~str = from_bytes(v); let s2: ~str = from_bytes(v);
let mut i: uint = 0u; let mut i: uint = 0u;
let n1: uint = len(s1); let n1: uint = s1.len();
let n2: uint = v.len(); let n2: uint = v.len();
assert_eq!(n1, n2); assert_eq!(n1, n2);
while i < n1 { while i < n1 {
@ -3601,7 +3583,7 @@ mod tests {
#[test] #[test]
fn test_to_managed() { fn test_to_managed() {
assert_eq!("abc".to_managed(), @"abc"); assert_eq!("abc".to_managed(), @"abc");
assert_eq!(slice("abcdef", 1, 5).to_managed(), @"bcde"); assert_eq!("abcdef".slice(1, 5).to_managed(), @"bcde");
} }
#[test] #[test]

View File

@ -547,7 +547,7 @@ pub mod rt {
let unpadded = match cv.precision { let unpadded = match cv.precision {
CountImplied => s, CountImplied => s,
CountIs(max) => if (max as uint) < str::char_len(s) { CountIs(max) => if (max as uint) < str::char_len(s) {
str::slice(s, 0, max as uint) s.slice(0, max as uint)
} else { } else {
s s
} }

View File

@ -290,9 +290,9 @@ impl FileMap {
let begin = begin.to_uint(); let begin = begin.to_uint();
let end = match str::find_char_from(*self.src, '\n', begin) { let end = match str::find_char_from(*self.src, '\n', begin) {
Some(e) => e, Some(e) => e,
None => str::len(*self.src) None => self.src.len()
}; };
str::slice(*self.src, begin, end).to_owned() self.src.slice(begin, end).to_owned()
} }
pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) { pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) {
@ -418,7 +418,7 @@ impl CodeMap {
let begin = self.lookup_byte_offset(sp.lo); let begin = self.lookup_byte_offset(sp.lo);
let end = self.lookup_byte_offset(sp.hi); let end = self.lookup_byte_offset(sp.hi);
assert_eq!(begin.fm.start_pos, end.fm.start_pos); assert_eq!(begin.fm.start_pos, end.fm.start_pos);
return str::slice(*begin.fm.src, return begin.fm.src.slice(
begin.pos.to_uint(), end.pos.to_uint()).to_owned(); begin.pos.to_uint(), end.pos.to_uint()).to_owned();
} }

View File

@ -14,7 +14,6 @@ use codemap::{Pos, span};
use codemap; use codemap;
use core::io; use core::io;
use core::str;
use core::uint; use core::uint;
use core::vec; use core::vec;
use extra::term; use extra::term;
@ -259,7 +258,7 @@ fn highlight_lines(cm: @codemap::CodeMap,
if elided { if elided {
let last_line = display_lines[display_lines.len() - 1u]; let last_line = display_lines[display_lines.len() - 1u];
let s = fmt!("%s:%u ", fm.name, last_line + 1u); let s = fmt!("%s:%u ", fm.name, last_line + 1u);
let mut indent = str::len(s); let mut indent = s.len();
let mut out = ~""; let mut out = ~"";
while indent > 0u { out += " "; indent -= 1u; } while indent > 0u { out += " "; indent -= 1u; }
out += "...\n"; out += "...\n";
@ -277,11 +276,11 @@ fn highlight_lines(cm: @codemap::CodeMap,
while num > 0u { num /= 10u; digits += 1u; } while num > 0u { num /= 10u; digits += 1u; }
// indent past |name:## | and the 0-offset column location // indent past |name:## | and the 0-offset column location
let left = str::len(fm.name) + digits + lo.col.to_uint() + 3u; let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
let mut s = ~""; let mut s = ~"";
// Skip is the number of characters we need to skip because they are // Skip is the number of characters we need to skip because they are
// part of the 'filename:line ' part of the previous line. // part of the 'filename:line ' part of the previous line.
let skip = str::len(fm.name) + digits + 3u; let skip = fm.name.len() + digits + 3u;
for skip.times() { for skip.times() {
s += " "; s += " ";
} }

View File

@ -215,7 +215,7 @@ fn trim_whitespace_prefix_and_push_line(lines: &mut ~[~str],
let col = col.to_uint(); let col = col.to_uint();
let s1 = if all_whitespace(s, 0, uint::min(len, col)) { let s1 = if all_whitespace(s, 0, uint::min(len, col)) {
if col < len { if col < len {
str::slice(s, col, len).to_owned() s.slice(col, len).to_owned()
} else { ~"" } } else { ~"" }
} else { s }; } else { s };
debug!("pushing line: %s", s1); debug!("pushing line: %s", s1);
@ -277,7 +277,7 @@ fn read_block_comment(rdr: @mut StringReader,
} }
} }
} }
if str::len(curr_line) != 0 { if curr_line.len() != 0 {
trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col); trim_whitespace_prefix_and_push_line(&mut lines, curr_line, col);
} }
} }

View File

@ -366,7 +366,7 @@ fn scan_exponent(rdr: @mut StringReader) -> Option<~str> {
bump(rdr); bump(rdr);
} }
let exponent = scan_digits(rdr, 10u); let exponent = scan_digits(rdr, 10u);
if str::len(exponent) > 0u { if exponent.len() > 0u {
return Some(rslt + exponent); return Some(rslt + exponent);
} else { rdr.fatal(~"scan_exponent: bad fp literal"); } } else { rdr.fatal(~"scan_exponent: bad fp literal"); }
} else { return None::<~str>; } } else { return None::<~str>; }
@ -434,7 +434,7 @@ fn scan_number(c: char, rdr: @mut StringReader) -> token::Token {
tp = if signed { either::Left(ast::ty_i64) } tp = if signed { either::Left(ast::ty_i64) }
else { either::Right(ast::ty_u64) }; else { either::Right(ast::ty_u64) };
} }
if str::len(num_str) == 0u { if num_str.len() == 0u {
rdr.fatal(~"no valid digits found for number"); rdr.fatal(~"no valid digits found for number");
} }
let parsed = match u64::from_str_radix(num_str, base as uint) { let parsed = match u64::from_str_radix(num_str, base as uint) {
@ -499,7 +499,7 @@ fn scan_number(c: char, rdr: @mut StringReader) -> token::Token {
} }
return token::LIT_FLOAT_UNSUFFIXED(str_to_ident(num_str)); return token::LIT_FLOAT_UNSUFFIXED(str_to_ident(num_str));
} else { } else {
if str::len(num_str) == 0u { if num_str.len() == 0u {
rdr.fatal(~"no valid digits found for number"); rdr.fatal(~"no valid digits found for number");
} }
let parsed = match u64::from_str_radix(num_str, base as uint) { let parsed = match u64::from_str_radix(num_str, base as uint) {

View File

@ -249,7 +249,7 @@ pub fn head(s: @ps, w: &str) {
// outer-box is consistent // outer-box is consistent
cbox(s, indent_unit); cbox(s, indent_unit);
// head-box is inconsistent // head-box is inconsistent
ibox(s, str::len(w) + 1); ibox(s, w.len() + 1);
// keyword that starts the head // keyword that starts the head
if !w.is_empty() { if !w.is_empty() {
word_nbsp(s, w); word_nbsp(s, w);

View File

@ -81,27 +81,27 @@ fn make_random_fasta(wr: @io::Writer,
for uint::range(0u, n as uint) |_i| { for uint::range(0u, n as uint) |_i| {
str::push_char(&mut op, select_random(myrandom_next(rng, 100u32), str::push_char(&mut op, select_random(myrandom_next(rng, 100u32),
copy genelist)); copy genelist));
if str::len(op) >= LINE_LENGTH() { if op.len() >= LINE_LENGTH() {
wr.write_line(op); wr.write_line(op);
op = ~""; op = ~"";
} }
} }
if str::len(op) > 0u { wr.write_line(op); } if op.len() > 0u { wr.write_line(op); }
} }
fn make_repeat_fasta(wr: @io::Writer, id: ~str, desc: ~str, s: ~str, n: int) { fn make_repeat_fasta(wr: @io::Writer, id: ~str, desc: ~str, s: ~str, n: int) {
unsafe { unsafe {
wr.write_line(~">" + id + " " + desc); wr.write_line(~">" + id + " " + desc);
let mut op: ~str = ~""; let mut op: ~str = ~"";
let sl: uint = str::len(s); let sl: uint = s.len();
for uint::range(0u, n as uint) |i| { for uint::range(0u, n as uint) |i| {
str::raw::push_byte(&mut op, s[i % sl]); str::raw::push_byte(&mut op, s[i % sl]);
if str::len(op) >= LINE_LENGTH() { if op.len() >= LINE_LENGTH() {
wr.write_line(op); wr.write_line(op);
op = ~""; op = ~"";
} }
} }
if str::len(op) > 0u { wr.write_line(op); } if op.len() > 0u { wr.write_line(op); }
} }
} }

View File

@ -191,7 +191,7 @@ fn main() {
while !rdr.eof() { while !rdr.eof() {
let line: ~str = rdr.read_line(); let line: ~str = rdr.read_line();
if str::len(line) == 0u { loop; } if line.len() == 0u { loop; }
match (line[0] as char, proc_mode) { match (line[0] as char, proc_mode) {

View File

@ -2,7 +2,7 @@ use std::str;
fn main() { fn main() {
let v = ~"test"; let v = ~"test";
let sslice = str::slice(v, 0, v.len()); let sslice = v.slice(0, v.len());
//~^ ERROR borrowed value does not live long enough //~^ ERROR borrowed value does not live long enough
fail!(sslice); fail!(sslice);
} }

View File

@ -20,5 +20,5 @@ fn main() {
} }
fn startfn() { fn startfn() {
assert!(str::is_empty(~"Ensure that the child task runs by failing")); assert!("Ensure that the child task runs by failing".is_empty());
} }

View File

@ -18,8 +18,8 @@ pub fn main() {
let mut i = 20; let mut i = 20;
let mut expected_len = 1u; let mut expected_len = 1u;
while i > 0 { while i > 0 {
error!(str::len(a)); error!(a.len());
assert_eq!(str::len(a), expected_len); assert_eq!(a.len(), expected_len);
a = a + a; // FIXME(#3387)---can't write a += a a = a + a; // FIXME(#3387)---can't write a += a
i -= 1; i -= 1;
expected_len *= 2u; expected_len *= 2u;

View File

@ -18,7 +18,7 @@ pub fn main() {
let chs: ~[char] = ~['e', 'é', '€', 0x10000 as char]; let chs: ~[char] = ~['e', 'é', '€', 0x10000 as char];
let s: ~str = str::from_chars(chs); let s: ~str = str::from_chars(chs);
assert!(str::len(s) == 10u); assert!(s.len() == 10u);
assert!(str::char_len(s) == 4u); assert!(str::char_len(s) == 4u);
assert!(str::to_chars(s).len() == 4u); assert!(str::to_chars(s).len() == 4u);
assert!(str::from_chars(str::to_chars(s)) == s); assert!(str::from_chars(str::to_chars(s)) == s);