From 7434080dd7c0cd072d7e51fbb1e174e954bdc011 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Sat, 29 Jun 2013 18:47:47 -0700 Subject: [PATCH 01/17] rustc: remove some dead functions --- src/librustc/middle/trans/common.rs | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 995cda92d9b..60c2bad4a65 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -788,15 +788,6 @@ pub fn C_estr_slice(cx: &mut CrateContext, s: @str) -> ValueRef { } } -// Returns a Plain Old LLVM String: -pub fn C_postr(s: &str) -> ValueRef { - unsafe { - do s.as_c_str |buf| { - llvm::LLVMConstStringInContext(base::task_llcx(), buf, s.len() as c_uint, False) - } - } -} - pub fn C_zero_byte_arr(size: uint) -> ValueRef { unsafe { let mut i = 0u; @@ -844,14 +835,6 @@ pub fn C_bytes(bytes: &[u8]) -> ValueRef { } } -pub fn C_bytes_plus_null(bytes: &[u8]) -> ValueRef { - unsafe { - return llvm::LLVMConstStringInContext(base::task_llcx(), - cast::transmute(vec::raw::to_ptr(bytes)), - bytes.len() as c_uint, False); - } -} - pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef { unsafe { llvm::LLVMGetParam(fndecl, param as c_uint) From 9ad815e063e8c7785cc10ea1afac55a19ea4e51a Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Tue, 23 Jul 2013 16:56:17 -0700 Subject: [PATCH 02/17] std: rename str.as_bytes_with_null_consume to str.to_bytes_with_null --- src/libextra/terminfo/parm.rs | 2 +- src/libstd/str.rs | 13 ++++++------- src/test/run-pass/foreign-fn-linkname.rs | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/libextra/terminfo/parm.rs b/src/libextra/terminfo/parm.rs index b182a9057bd..114ab6702ae 100644 --- a/src/libextra/terminfo/parm.rs +++ b/src/libextra/terminfo/parm.rs @@ -545,7 +545,7 @@ priv fn format(val: Param, op: FormatOp, flags: Flags) -> Result<~[u8],~str> { String(s) => { match op { FormatString => { - let mut s = s.as_bytes_with_null_consume(); + let mut s = s.to_bytes_with_null(); s.pop(); // remove the null if flags.precision > 0 && flags.precision < s.len() { s.truncate(flags.precision); diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 125df156ed0..3987f260065 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -2073,8 +2073,7 @@ pub trait OwnedStr { fn reserve(&mut self, n: uint); fn reserve_at_least(&mut self, n: uint); fn capacity(&self) -> uint; - - fn as_bytes_with_null_consume(self) -> ~[u8]; + fn to_bytes_with_null(self) -> ~[u8]; } impl OwnedStr for ~str { @@ -2263,7 +2262,7 @@ impl OwnedStr for ~str { /// Convert to a vector of bytes. This does not allocate a new /// string, and includes the null terminator. #[inline] - fn as_bytes_with_null_consume(self) -> ~[u8] { + fn to_bytes_with_null(self) -> ~[u8] { unsafe { ::cast::transmute(self) } } } @@ -3065,17 +3064,17 @@ mod tests { } #[test] - fn test_as_bytes_with_null_consume() { + fn test_to_bytes_with_null() { let s = ~"ศไทย中华Việt Nam"; let v = ~[ 224, 184, 168, 224, 185, 132, 224, 184, 151, 224, 184, 162, 228, 184, 173, 229, 141, 142, 86, 105, 225, 187, 135, 116, 32, 78, 97, 109, 0 ]; - assert_eq!((~"").as_bytes_with_null_consume(), ~[0]); - assert_eq!((~"abc").as_bytes_with_null_consume(), + assert_eq!((~"").to_bytes_with_null(), ~[0]); + assert_eq!((~"abc").to_bytes_with_null(), ~['a' as u8, 'b' as u8, 'c' as u8, 0]); - assert_eq!(s.as_bytes_with_null_consume(), v); + assert_eq!(s.to_bytes_with_null(), v); } #[test] diff --git a/src/test/run-pass/foreign-fn-linkname.rs b/src/test/run-pass/foreign-fn-linkname.rs index f0cac8f2f3e..38f36dd258b 100644 --- a/src/test/run-pass/foreign-fn-linkname.rs +++ b/src/test/run-pass/foreign-fn-linkname.rs @@ -26,7 +26,7 @@ mod libc { fn strlen(str: ~str) -> uint { unsafe { // C string is terminated with a zero - let bytes = str.as_bytes_with_null_consume(); + let bytes = str.to_bytes_with_null(); return libc::my_strlen(vec::raw::to_ptr(bytes)); } } From cfd89c407598673bf55ea11525b1398c53cd3725 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Sun, 30 Jun 2013 08:25:16 -0700 Subject: [PATCH 03/17] std: remove os::as_c_charp --- src/libstd/io.rs | 27 +++++++++++------------ src/libstd/os.rs | 56 ++++++++++++++++++++++-------------------------- 2 files changed, 39 insertions(+), 44 deletions(-) diff --git a/src/libstd/io.rs b/src/libstd/io.rs index 6ceaf5caea3..6335588db50 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -63,7 +63,7 @@ use iterator::IteratorUtil; use ptr; use result; use str; -use str::StrSlice; +use str::{StrSlice, OwnedStr, StrUtil}; use to_str::ToStr; use uint; use vec; @@ -1031,17 +1031,16 @@ pub fn stdin() -> @Reader { } pub fn file_reader(path: &Path) -> Result<@Reader, ~str> { - unsafe { - let f = os::as_c_charp(path.to_str(), |pathbuf| { - os::as_c_charp("r", |modebuf| - libc::fopen(pathbuf, modebuf) - ) - }); - return if f as uint == 0u { result::Err(~"error opening " - + path.to_str()) } - else { - result::Ok(FILE_reader(f, true)) + let f = do path.to_str().as_c_str |pathbuf| { + do "r".as_c_str |modebuf| { + unsafe { libc::fopen(pathbuf, modebuf as *libc::c_char) } } + }; + + if f as uint == 0u { + result::Err(~"error opening " + path.to_str()) + } else { + result::Ok(FILE_reader(f, true)) } } @@ -1282,7 +1281,7 @@ pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) } } let fd = unsafe { - do os::as_c_charp(path.to_str()) |pathbuf| { + do path.to_str().as_c_str |pathbuf| { libc::open(pathbuf, fflags, (S_IRUSR | S_IWUSR) as c_int) } @@ -1567,8 +1566,8 @@ pub fn file_writer(path: &Path, flags: &[FileFlag]) -> Result<@Writer, ~str> { // FIXME: fileflags // #2004 pub fn buffered_file_writer(path: &Path) -> Result<@Writer, ~str> { unsafe { - let f = do os::as_c_charp(path.to_str()) |pathbuf| { - do os::as_c_charp("w") |modebuf| { + let f = do path.to_str().as_c_str |pathbuf| { + do "w".as_c_str |modebuf| { libc::fopen(pathbuf, modebuf) } }; diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 5981926fce3..2c3ce86ef78 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -87,10 +87,6 @@ pub fn getcwd() -> Path { // FIXME: move these to str perhaps? #2620 -pub fn as_c_charp(s: &str, f: &fn(*c_char) -> T) -> T { - str::as_c_str(s, |b| f(b as *c_char)) -} - pub fn fill_charp_buf(f: &fn(*mut c_char, size_t) -> bool) -> Option<~str> { let mut buf = vec::from_elem(TMPBUF_SZ, 0u8 as c_char); @@ -335,10 +331,10 @@ pub fn unsetenv(n: &str) { } pub fn fdopen(fd: c_int) -> *FILE { - unsafe { - return do as_c_charp("r") |modebuf| { + do "r".as_c_str |modebuf| { + unsafe { libc::fdopen(fd, modebuf) - }; + } } } @@ -471,7 +467,7 @@ pub fn self_exe_path() -> Option { let mut path_str = str::with_capacity(TMPBUF_SZ); let len = do str::as_c_str(path_str) |buf| { let buf = buf as *mut c_char; - do as_c_charp("/proc/self/exe") |proc_self_buf| { + do "/proc/self/exe".as_c_str |proc_self_buf| { readlink(proc_self_buf, buf, TMPBUF_SZ as size_t) } }; @@ -654,9 +650,9 @@ pub fn make_dir(p: &Path, mode: c_int) -> bool { #[cfg(unix)] fn mkdir(p: &Path, mode: c_int) -> bool { - unsafe { - do as_c_charp(p.to_str()) |c| { - libc::mkdir(c, mode as libc::mode_t) == (0 as c_int) + do p.to_str().as_c_str |buf| { + unsafe { + libc::mkdir(buf, mode as libc::mode_t) == (0 as c_int) } } } @@ -830,10 +826,10 @@ pub fn remove_dir(p: &Path) -> bool { #[cfg(unix)] fn rmdir(p: &Path) -> bool { - unsafe { - return do as_c_charp(p.to_str()) |buf| { + do p.to_str().as_c_str |buf| { + unsafe { libc::rmdir(buf) == (0 as c_int) - }; + } } } } @@ -855,10 +851,10 @@ pub fn change_dir(p: &Path) -> bool { #[cfg(unix)] fn chdir(p: &Path) -> bool { - unsafe { - return do as_c_charp(p.to_str()) |buf| { + do p.to_str().as_c_str |buf| { + unsafe { libc::chdir(buf) == (0 as c_int) - }; + } } } } @@ -883,8 +879,8 @@ pub fn copy_file(from: &Path, to: &Path) -> bool { #[cfg(unix)] fn do_copy_file(from: &Path, to: &Path) -> bool { unsafe { - let istream = do as_c_charp(from.to_str()) |fromp| { - do as_c_charp("rb") |modebuf| { + let istream = do from.to_str().as_c_str |fromp| { + do "rb".as_c_str |modebuf| { libc::fopen(fromp, modebuf) } }; @@ -895,8 +891,8 @@ pub fn copy_file(from: &Path, to: &Path) -> bool { let from_mode = from.get_mode().expect("copy_file: couldn't get permissions \ for source file"); - let ostream = do as_c_charp(to.to_str()) |top| { - do as_c_charp("w+b") |modebuf| { + let ostream = do to.to_str().as_c_str |top| { + do "w+b".as_c_str |modebuf| { libc::fopen(top, modebuf) } }; @@ -955,9 +951,9 @@ pub fn remove_file(p: &Path) -> bool { #[cfg(unix)] fn unlink(p: &Path) -> bool { unsafe { - return do as_c_charp(p.to_str()) |buf| { + do p.to_str().as_c_str |buf| { libc::unlink(buf) == (0 as c_int) - }; + } } } } @@ -1703,7 +1699,7 @@ mod tests { use libc; use option::Some; use option; - use os::{as_c_charp, env, getcwd, getenv, make_absolute, real_args}; + use os::{env, getcwd, getenv, make_absolute, real_args}; use os::{remove_file, setenv, unsetenv}; use os; use path::Path; @@ -1941,8 +1937,8 @@ mod tests { let out = tempdir.push("out.txt"); /* Write the temp input file */ - let ostream = do as_c_charp(in.to_str()) |fromp| { - do as_c_charp("w+b") |modebuf| { + let ostream = do in.to_str().as_c_str |fromp| { + do "w+b".as_c_str |modebuf| { libc::fopen(fromp, modebuf) } }; @@ -2020,16 +2016,16 @@ mod tests { } } - let p = tmpdir().push("mmap_file.tmp"); + let path = tmpdir().push("mmap_file.tmp"); let size = page_size() * 2; - remove_file(&p); + remove_file(&path); let fd = unsafe { - let fd = do as_c_charp(p.to_str()) |path| { + let fd = do path.to_str().as_c_str |path| { open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR) }; lseek_(fd, size); - do as_c_charp("x") |x| { + do "x".as_c_str |x| { assert!(write(fd, x as *c_void, 1) == 1); } fd From 9fdec67a6761ae43d8fae80e10b5a7a1e0ca7c0d Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Wed, 10 Jul 2013 17:33:11 -0700 Subject: [PATCH 04/17] std: move str::as_buf into StrSlice --- src/libstd/option.rs | 5 +- src/libstd/rt/borrowck.rs | 8 +- src/libstd/str.rs | 96 ++++++++++---------- src/libstd/sys.rs | 9 +- src/libstd/unstable/lang.rs | 2 +- src/test/run-pass/c-stack-returning-int64.rs | 4 +- 6 files changed, 62 insertions(+), 62 deletions(-) diff --git a/src/libstd/option.rs b/src/libstd/option.rs index f5e5dbb3dbf..9fe590e28ee 100644 --- a/src/libstd/option.rs +++ b/src/libstd/option.rs @@ -50,7 +50,6 @@ use iterator::Iterator; use str::StrSlice; use clone::DeepClone; -#[cfg(test)] use str; #[cfg(test)] use iterator::IteratorUtil; /// The option type @@ -446,10 +445,10 @@ fn test_unwrap_ptr() { #[test] fn test_unwrap_str() { let x = ~"test"; - let addr_x = str::as_buf(x, |buf, _len| buf); + let addr_x = x.as_buf(|buf, _len| buf); let opt = Some(x); let y = opt.unwrap(); - let addr_y = str::as_buf(y, |buf, _len| buf); + let addr_y = y.as_buf(|buf, _len| buf); assert_eq!(addr_x, addr_y); } diff --git a/src/libstd/rt/borrowck.rs b/src/libstd/rt/borrowck.rs index 60df2d5c11b..42e545ce1a9 100644 --- a/src/libstd/rt/borrowck.rs +++ b/src/libstd/rt/borrowck.rs @@ -16,7 +16,7 @@ use managed::raw::BoxRepr; use option::{Option, None, Some}; use uint; use str; -use str::OwnedStr; +use str::{OwnedStr, StrSlice}; use sys; use vec::ImmutableVector; @@ -76,7 +76,7 @@ unsafe fn fail_borrowed(box: *mut BoxRepr, file: *c_char, line: size_t) { match try_take_task_borrow_list() { None => { // not recording borrows let msg = "borrowed"; - do str::as_buf(msg) |msg_p, _| { + do msg.as_buf |msg_p, _| { sys::begin_unwind_(msg_p as *c_char, file, line); } } @@ -92,7 +92,7 @@ unsafe fn fail_borrowed(box: *mut BoxRepr, file: *c_char, line: size_t) { sep = " and at "; } } - do str::as_buf(msg) |msg_p, _| { + do msg.as_buf |msg_p, _| { sys::begin_unwind_(msg_p as *c_char, file, line) } } @@ -231,7 +231,7 @@ pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint, let br = borrow_list.pop(); if br.box != a || br.file != file || br.line != line { let err = fmt!("wrong borrow found, br=%?", br); - do str::as_buf(err) |msg_p, _| { + do err.as_buf |msg_p, _| { sys::begin_unwind_(msg_p as *c_char, file, line) } } diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 3987f260065..c16e87000f5 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -17,7 +17,6 @@ */ use at_vec; -use cast::transmute; use cast; use char; use char::Char; @@ -192,10 +191,10 @@ impl<'self, S: Str> StrVector for &'self [S] { s.reserve(len); unsafe { - do as_buf(s) |buf, _| { + do s.as_buf |buf, _| { let mut buf = ::cast::transmute_mut_unsafe(buf); for self.iter().advance |ss| { - do as_buf(ss.as_slice()) |ssbuf, sslen| { + do ss.as_slice().as_buf |ssbuf, sslen| { let sslen = sslen - 1; ptr::copy_memory(buf, ssbuf, sslen); buf = buf.offset(sslen); @@ -223,12 +222,12 @@ impl<'self, S: Str> StrVector for &'self [S] { s.reserve(len); unsafe { - do as_buf(s) |buf, _| { - do as_buf(sep) |sepbuf, seplen| { + do s.as_buf |buf, _| { + do sep.as_buf |sepbuf, seplen| { let seplen = seplen - 1; let mut buf = ::cast::transmute_mut_unsafe(buf); for self.iter().advance |ss| { - do as_buf(ss.as_slice()) |ssbuf, sslen| { + do ss.as_slice().as_buf |ssbuf, sslen| { let sslen = sslen - 1; if first { first = false; @@ -534,8 +533,8 @@ Section: Comparing strings #[lang="str_eq"] #[inline] pub fn eq_slice(a: &str, b: &str) -> bool { - do as_buf(a) |ap, alen| { - do as_buf(b) |bp, blen| { + do a.as_buf |ap, alen| { + do b.as_buf |bp, blen| { if (alen != blen) { false } else { unsafe { @@ -551,8 +550,8 @@ pub fn eq_slice(a: &str, b: &str) -> bool { #[cfg(test)] #[inline] pub fn eq_slice(a: &str, b: &str) -> bool { - do as_buf(a) |ap, alen| { - do as_buf(b) |bp, blen| { + do a.as_buf |ap, alen| { + do b.as_buf |bp, blen| { if (alen != blen) { false } else { unsafe { @@ -799,7 +798,7 @@ pub trait StrUtil { impl<'self> StrUtil for &'self str { #[inline] fn as_c_str(self, f: &fn(*libc::c_char) -> T) -> T { - do as_buf(self) |buf, len| { + do self.as_buf |buf, len| { // NB: len includes the trailing null. assert!(len > 0); if unsafe { *(ptr::offset(buf,len-1)) != 0 } { @@ -819,30 +818,13 @@ pub fn as_c_str(s: &str, f: &fn(*libc::c_char) -> T) -> T { s.as_c_str(f) } -/** - * Work with the byte buffer and length of a slice. - * - * The given length is one byte longer than the 'official' indexable - * length of the string. This is to permit probing the byte past the - * indexable area for a null byte, as is the case in slices pointing - * to full strings, or suffixes of them. - */ -#[inline] -pub fn as_buf(s: &str, f: &fn(*u8, uint) -> T) -> T { - unsafe { - let v : *(*u8,uint) = transmute(&s); - let (buf,len) = *v; - f(buf, len) - } -} - /// Unsafe operations pub mod raw { use cast; use libc; use ptr; use str::raw; - use str::{as_buf, is_utf8}; + use str::{is_utf8}; use vec; use vec::MutableVector; @@ -931,7 +913,7 @@ pub mod raw { * If end is greater than the length of the string. */ pub unsafe fn slice_bytes_owned(s: &str, begin: uint, end: uint) -> ~str { - do as_buf(s) |sbuf, n| { + do s.as_buf |sbuf, n| { assert!((begin <= end)); assert!((end <= n)); @@ -959,7 +941,7 @@ pub mod raw { */ #[inline] pub unsafe fn slice_bytes(s: &str, begin: uint, end: uint) -> &str { - do as_buf(s) |sbuf, n| { + do s.as_buf |sbuf, n| { assert!((begin <= end)); assert!((end <= n)); @@ -972,7 +954,7 @@ pub mod raw { pub unsafe fn push_byte(s: &mut ~str, b: u8) { let new_len = s.len() + 1; s.reserve_at_least(new_len); - do as_buf(*s) |buf, len| { + do s.as_buf |buf, len| { let buf: *mut u8 = ::cast::transmute(buf); *ptr::mut_offset(buf, len) = b; } @@ -1193,7 +1175,7 @@ impl<'self> Str for @str { impl<'self> Container for &'self str { #[inline] fn len(&self) -> uint { - do as_buf(*self) |_p, n| { n - 1u } + do self.as_buf |_p, n| { n - 1u } } #[inline] fn is_empty(&self) -> bool { @@ -1287,6 +1269,8 @@ pub trait StrSlice<'self> { fn lev_distance(&self, t: &str) -> uint; fn subslice_offset(&self, inner: &str) -> uint; + + fn as_buf(&self, f: &fn(*u8, uint) -> T) -> T; } /// Extension methods for strings @@ -1909,14 +1893,14 @@ impl<'self> StrSlice<'self> for &'self str { /// Given a string, make a new string with repeated copies of it. fn repeat(&self, nn: uint) -> ~str { - do as_buf(*self) |buf, len| { + do self.as_buf |buf, len| { let mut ret = ~""; // ignore the NULL terminator let len = len - 1; ret.reserve(nn * len); unsafe { - do as_buf(ret) |rbuf, _len| { + do ret.as_buf |rbuf, _len| { let mut rbuf = ::cast::transmute_mut_unsafe(rbuf); for nn.times { @@ -2010,8 +1994,8 @@ impl<'self> StrSlice<'self> for &'self str { */ #[inline] fn subslice_offset(&self, inner: &str) -> uint { - do as_buf(*self) |a, a_len| { - do as_buf(inner) |b, b_len| { + do self.as_buf |a, a_len| { + do inner.as_buf |b, b_len| { let a_start: uint; let a_end: uint; let b_start: uint; @@ -2027,6 +2011,22 @@ impl<'self> StrSlice<'self> for &'self str { } } + /** + * Work with the byte buffer and length of a slice. + * + * The given length is one byte longer than the 'official' indexable + * length of the string. This is to permit probing the byte past the + * indexable area for a null byte, as is the case in slices pointing + * to full strings, or suffixes of them. + */ + #[inline] + fn as_buf(&self, f: &fn(*u8, uint) -> T) -> T { + unsafe { + let v: *(*u8, uint) = cast::transmute(self); + let (buf, len) = *v; + f(buf, len) + } + } } #[allow(missing_doc)] @@ -2084,8 +2084,8 @@ impl OwnedStr for ~str { let llen = self.len(); let rlen = rhs.len(); self.reserve(llen + rlen); - do as_buf(*self) |lbuf, _llen| { - do as_buf(rhs) |rbuf, _rlen| { + do self.as_buf |lbuf, _llen| { + do rhs.as_buf |rbuf, _rlen| { let dst = ptr::offset(lbuf, llen); let dst = ::cast::transmute_mut_unsafe(dst); ptr::copy_memory(dst, rbuf, rlen); @@ -2102,8 +2102,8 @@ impl OwnedStr for ~str { let llen = self.len(); let rlen = rhs.len(); self.reserve_at_least(llen + rlen); - do as_buf(*self) |lbuf, _llen| { - do as_buf(rhs) |rbuf, _rlen| { + do self.as_buf |lbuf, _llen| { + do rhs.as_buf |rbuf, _rlen| { let dst = ptr::offset(lbuf, llen); let dst = ::cast::transmute_mut_unsafe(dst); ptr::copy_memory(dst, rbuf, rlen); @@ -2126,7 +2126,7 @@ impl OwnedStr for ~str { let new_len = len + nb; self.reserve_at_least(new_len); let off = len; - do as_buf(*self) |buf, _len| { + do self.as_buf |buf, _len| { let buf: *mut u8 = ::cast::transmute(buf); match nb { 1u => { @@ -3091,20 +3091,20 @@ mod tests { #[test] fn test_as_buf() { let a = "Abcdefg"; - let b = as_buf(a, |buf, _l| { + let b = do a.as_buf |buf, _l| { assert_eq!(unsafe { *buf }, 65u8); 100 - }); + }; assert_eq!(b, 100); } #[test] fn test_as_buf_small() { let a = "A"; - let b = as_buf(a, |buf, _l| { + let b = do a.as_buf |buf, _l| { assert_eq!(unsafe { *buf }, 65u8); 100 - }); + }; assert_eq!(b, 100); } @@ -3112,7 +3112,7 @@ mod tests { fn test_as_buf2() { unsafe { let s = ~"hello"; - let sb = as_buf(s, |b, _l| b); + let sb = s.as_buf(|b, _l| b); let s_cstr = raw::from_buf(sb); assert_eq!(s_cstr, s); } @@ -3121,7 +3121,7 @@ mod tests { #[test] fn test_as_buf_3() { let a = ~"hello"; - do as_buf(a) |buf, len| { + do a.as_buf |buf, len| { unsafe { assert_eq!(a[0], 'h' as u8); assert_eq!(*buf, 'h' as u8); diff --git a/src/libstd/sys.rs b/src/libstd/sys.rs index d50d90376ab..0c497ecef27 100644 --- a/src/libstd/sys.rs +++ b/src/libstd/sys.rs @@ -18,6 +18,7 @@ use io; use libc; use libc::{c_char, size_t}; use repr; +use str::StrSlice; use str; use unstable::intrinsics; @@ -122,8 +123,8 @@ pub trait FailWithCause { impl FailWithCause for ~str { fn fail_with(cause: ~str, file: &'static str, line: uint) -> ! { - do str::as_buf(cause) |msg_buf, _msg_len| { - do str::as_buf(file) |file_buf, _file_len| { + do cause.as_buf |msg_buf, _msg_len| { + do file.as_buf |file_buf, _file_len| { unsafe { let msg_buf = cast::transmute(msg_buf); let file_buf = cast::transmute(file_buf); @@ -136,8 +137,8 @@ impl FailWithCause for ~str { impl FailWithCause for &'static str { fn fail_with(cause: &'static str, file: &'static str, line: uint) -> ! { - do str::as_buf(cause) |msg_buf, _msg_len| { - do str::as_buf(file) |file_buf, _file_len| { + do cause.as_buf |msg_buf, _msg_len| { + do file.as_buf |file_buf, _file_len| { unsafe { let msg_buf = cast::transmute(msg_buf); let file_buf = cast::transmute(file_buf); diff --git a/src/libstd/unstable/lang.rs b/src/libstd/unstable/lang.rs index 92357f210a5..f8cd08b4bf6 100644 --- a/src/libstd/unstable/lang.rs +++ b/src/libstd/unstable/lang.rs @@ -56,7 +56,7 @@ pub fn fail_bounds_check(file: *c_char, line: size_t, index: size_t, len: size_t) { let msg = fmt!("index out of bounds: the len is %d but the index is %d", len as int, index as int); - do str::as_buf(msg) |p, _len| { + do msg.as_buf |p, _len| { fail_(p as *c_char, file, line); } } diff --git a/src/test/run-pass/c-stack-returning-int64.rs b/src/test/run-pass/c-stack-returning-int64.rs index d09f8493d80..12fa8066686 100644 --- a/src/test/run-pass/c-stack-returning-int64.rs +++ b/src/test/run-pass/c-stack-returning-int64.rs @@ -20,11 +20,11 @@ mod libc { } fn atol(s: ~str) -> int { - return str::as_buf(s, { |x, _len| unsafe { libc::atol(x) } }); + s.as_buf(|x, _len| unsafe { libc::atol(x) }) } fn atoll(s: ~str) -> i64 { - return str::as_buf(s, { |x, _len| unsafe { libc::atoll(x) } }); + s.as_buf(|x, _len| unsafe { libc::atoll(x) }) } pub fn main() { From 7af56bb92199eabcfee52c43739761b18872a2c1 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Mon, 22 Jul 2013 21:41:46 -0700 Subject: [PATCH 05/17] std: move StrUtil::as_c_str into StrSlice --- src/libextra/rl.rs | 10 ++-- src/librustc/back/link.rs | 32 +++++----- src/librustc/back/passes.rs | 3 +- src/librustc/lib/llvm.rs | 8 +-- src/librustc/metadata/loader.rs | 4 +- src/librustc/middle/trans/asm.rs | 5 +- src/librustc/middle/trans/base.rs | 49 ++++++++-------- src/librustc/middle/trans/builder.rs | 11 ++-- src/librustc/middle/trans/consts.rs | 3 +- src/librustc/middle/trans/context.rs | 9 +-- src/librustc/middle/trans/controlflow.rs | 5 +- src/librustc/middle/trans/debuginfo.rs | 29 +++++----- src/librustc/middle/trans/glue.rs | 5 +- src/librustpkg/util.rs | 4 +- src/libstd/io.rs | 2 +- src/libstd/os.rs | 23 ++++---- src/libstd/path.rs | 37 +++++------- src/libstd/prelude.rs | 2 +- src/libstd/ptr.rs | 16 ++--- src/libstd/rt/logging.rs | 8 +-- src/libstd/rt/uv/uvll.rs | 4 +- src/libstd/run.rs | 10 ++-- src/libstd/str.rs | 74 ++++++++++-------------- 23 files changed, 157 insertions(+), 196 deletions(-) diff --git a/src/libextra/rl.rs b/src/libextra/rl.rs index 8d291377b1e..08e1c240a4c 100644 --- a/src/libextra/rl.rs +++ b/src/libextra/rl.rs @@ -32,7 +32,7 @@ pub mod rustrt { /// Add a line to history pub unsafe fn add_history(line: &str) -> bool { - do str::as_c_str(line) |buf| { + do line.as_c_str |buf| { rustrt::linenoiseHistoryAdd(buf) == 1 as c_int } } @@ -44,21 +44,21 @@ pub unsafe fn set_history_max_len(len: int) -> bool { /// Save line history to a file pub unsafe fn save_history(file: &str) -> bool { - do str::as_c_str(file) |buf| { + do file.as_c_str |buf| { rustrt::linenoiseHistorySave(buf) == 1 as c_int } } /// Load line history from a file pub unsafe fn load_history(file: &str) -> bool { - do str::as_c_str(file) |buf| { + do file.as_c_str |buf| { rustrt::linenoiseHistoryLoad(buf) == 1 as c_int } } /// Print out a prompt and then wait for input and return it pub unsafe fn read(prompt: &str) -> Option<~str> { - do str::as_c_str(prompt) |buf| { + do prompt.as_c_str |buf| { let line = rustrt::linenoise(buf); if line.is_null() { None } @@ -80,7 +80,7 @@ pub unsafe fn complete(cb: CompletionCb) { unsafe { do cb(str::raw::from_c_str(line)) |suggestion| { - do str::as_c_str(suggestion) |buf| { + do suggestion.as_c_str |buf| { rustrt::linenoiseAddCompletion(completions, buf); } } diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index f9910462db5..d932dc80d51 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -76,9 +76,9 @@ pub fn WriteOutputFile(sess: Session, OptLevel: c_int, EnableSegmentedStacks: bool) { unsafe { - do str::as_c_str(Triple) |Triple| { - do str::as_c_str(Feature) |Feature| { - do str::as_c_str(Output) |Output| { + do Triple.as_c_str |Triple| { + do Feature.as_c_str |Feature| { + do Output.as_c_str |Output| { let result = llvm::LLVMRustWriteOutputFile( PM, M, @@ -263,16 +263,16 @@ pub mod write { output_type_bitcode => { if opts.optimize != session::No { let filename = output.with_filetype("no-opt.bc"); - str::as_c_str(filename.to_str(), |buf| { - llvm::LLVMWriteBitcodeToFile(llmod, buf) - }); + do filename.to_str().as_c_str |buf| { + llvm::LLVMWriteBitcodeToFile(llmod, buf); + } } } _ => { let filename = output.with_filetype("bc"); - str::as_c_str(filename.to_str(), |buf| { - llvm::LLVMWriteBitcodeToFile(llmod, buf) - }); + do filename.to_str().as_c_str |buf| { + llvm::LLVMWriteBitcodeToFile(llmod, buf); + } } } } @@ -333,9 +333,9 @@ pub mod write { // Always output the bitcode file with --save-temps let filename = output.with_filetype("opt.bc"); - str::as_c_str(filename.to_str(), |buf| { + do filename.to_str().as_c_str |buf| { llvm::LLVMWriteBitcodeToFile(llmod, buf) - }); + }; // Save the assembly file if -S is used if output_type == output_type_assembly { WriteOutputFile( @@ -391,13 +391,15 @@ pub mod write { if output_type == output_type_llvm_assembly { // Given options "-S --emit-llvm": output LLVM assembly - str::as_c_str(output.to_str(), |buf_o| { - llvm::LLVMRustAddPrintModulePass(pm.llpm, llmod, buf_o)}); + do output.to_str().as_c_str |buf_o| { + llvm::LLVMRustAddPrintModulePass(pm.llpm, llmod, buf_o); + } } else { // If only a bitcode file is asked for by using the // '--emit-llvm' flag, then output it here - str::as_c_str(output.to_str(), - |buf| llvm::LLVMWriteBitcodeToFile(llmod, buf) ); + do output.to_str().as_c_str |buf| { + llvm::LLVMWriteBitcodeToFile(llmod, buf); + } } llvm::LLVMDisposeModule(llmod); diff --git a/src/librustc/back/passes.rs b/src/librustc/back/passes.rs index f9dc88074d3..4533aeebbcb 100644 --- a/src/librustc/back/passes.rs +++ b/src/librustc/back/passes.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::str; use std::io; use driver::session::{OptLevel, No, Less, Aggressive}; @@ -174,7 +173,7 @@ pub fn populate_pass_manager(sess: Session, pm: &mut PassManager, pass_list:&[~s } pub fn create_pass(name:&str) -> Option { - do str::as_c_str(name) |s| { + do name.as_c_str |s| { unsafe { let p = llvm::LLVMCreatePass(s); if p.is_null() { diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index d1a9e387d00..f3bca7a6ab3 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -12,7 +12,6 @@ use std::hashmap::HashMap; use std::libc::{c_uint, c_ushort}; use std::option; -use std::str; use middle::trans::type_::Type; @@ -2287,10 +2286,9 @@ pub struct TargetData { } pub fn mk_target_data(string_rep: &str) -> TargetData { - let lltd = - str::as_c_str(string_rep, |buf| unsafe { - llvm::LLVMCreateTargetData(buf) - }); + let lltd = do string_rep.as_c_str |buf| { + unsafe { llvm::LLVMCreateTargetData(buf) } + }; TargetData { lltd: lltd, diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index d6687b4313a..a0789b3e323 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -186,9 +186,9 @@ pub fn metadata_matches(extern_metas: &[@ast::MetaItem], fn get_metadata_section(os: os, filename: &Path) -> Option<@~[u8]> { unsafe { - let mb = str::as_c_str(filename.to_str(), |buf| { + let mb = do filename.to_str().as_c_str |buf| { llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf) - }); + }; if mb as int == 0 { return option::None::<@~[u8]>; } let of = match mk_object_file(mb) { option::Some(of) => of, diff --git a/src/librustc/middle/trans/asm.rs b/src/librustc/middle/trans/asm.rs index fadeab0f1f7..903f36c4f8a 100644 --- a/src/librustc/middle/trans/asm.rs +++ b/src/librustc/middle/trans/asm.rs @@ -21,7 +21,6 @@ use middle::ty; use middle::trans::type_::Type; -use std::str; use syntax::ast; // Take an inline assembly expression and splat it out via LLVM @@ -123,8 +122,8 @@ pub fn trans_inline_asm(bcx: block, ia: &ast::inline_asm) -> block { ast::asm_intel => lib::llvm::AD_Intel }; - let r = do str::as_c_str(ia.asm) |a| { - do str::as_c_str(constraints) |c| { + let r = do ia.asm.as_c_str |a| { + do constraints.as_c_str |c| { InlineAsmCall(bcx, a, c, inputs, output, ia.volatile, ia.alignstack, dialect) } }; diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 32a5ebe0c39..9c3eeed5a34 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -70,7 +70,6 @@ use std::hashmap::{HashMap, HashSet}; use std::int; use std::io; use std::libc::c_uint; -use std::str; use std::uint; use std::vec; use std::local_data; @@ -549,11 +548,11 @@ pub fn get_res_dtor(ccx: @mut CrateContext, // Structural comparison: a rather involved form of glue. pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) { if cx.sess.opts.save_temps { - let _: () = str::as_c_str(s, |buf| { + do s.as_c_str |buf| { unsafe { llvm::LLVMSetValueName(v, buf) } - }); + } } } @@ -1577,16 +1576,18 @@ pub struct BasicBlocks { pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef { unsafe { let cx = task_llcx(); - str::as_c_str("static_allocas", - |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)) + do "static_allocas".as_c_str | buf| { + llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf) + } } } pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef { unsafe { let cx = task_llcx(); - str::as_c_str("return", - |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)) + do "return".as_c_str |buf| { + llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf) + } } } @@ -2353,11 +2354,11 @@ pub fn create_entry_wrapper(ccx: @mut CrateContext, }; decl_cdecl_fn(ccx.llmod, main_name, llfty) }; - let llbb = str::as_c_str("top", |buf| { + let llbb = do "top".as_c_str |buf| { unsafe { llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf) } - }); + }; let bld = ccx.builder.B; unsafe { llvm::LLVMPositionBuilderAtEnd(bld, llbb); @@ -2457,9 +2458,9 @@ pub fn get_item_val(ccx: @mut CrateContext, id: ast::node_id) -> ValueRef { exprt = m == ast::m_mutbl; unsafe { let llty = llvm::LLVMTypeOf(v); - let g = str::as_c_str(s, |buf| { + let g = do s.as_c_str |buf| { llvm::LLVMAddGlobal(ccx.llmod, llty, buf) - }); + }; ccx.item_symbols.insert(i.id, s); g } @@ -2509,7 +2510,7 @@ pub fn get_item_val(ccx: @mut CrateContext, id: ast::node_id) -> ValueRef { ast::foreign_item_static(*) => { let typ = ty::node_id_to_type(ccx.tcx, ni.id); let ident = token::ident_to_str(&ni.ident); - let g = do str::as_c_str(ident) |buf| { + let g = do ident.as_c_str |buf| { unsafe { let ty = type_of(ccx, typ); llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf) @@ -2609,11 +2610,11 @@ pub fn trans_constant(ccx: &mut CrateContext, it: @ast::item) { let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed(); let disr_val = vi[i].disr_val; note_unique_llvm_symbol(ccx, s); - let discrim_gvar = str::as_c_str(s, |buf| { + let discrim_gvar = do s.as_c_str |buf| { unsafe { llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf) } - }); + }; unsafe { llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, disr_val)); llvm::LLVMSetGlobalConstant(discrim_gvar, True); @@ -2750,7 +2751,7 @@ pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) { } let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id; - let gc_metadata = do str::as_c_str(gc_metadata_name) |buf| { + let gc_metadata = do gc_metadata_name.as_c_str |buf| { unsafe { llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf) } @@ -2813,11 +2814,11 @@ pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta, let sym_name = ~"_rust_crate_map_" + mapname; let arrtype = Type::array(&int_type, n_subcrates as u64); let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false); - let map = str::as_c_str(sym_name, |buf| { + let map = do sym_name.as_c_str |buf| { unsafe { llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf) } - }); + }; lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage); return map; } @@ -2832,11 +2833,11 @@ pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) { cdata.name, cstore::get_crate_vers(cstore, i), cstore::get_crate_hash(cstore, i)); - let cr = str::as_c_str(nm, |buf| { + let cr = do nm.as_c_str |buf| { unsafe { llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf) } - }); + }; subcrates.push(p2i(ccx, cr)); i += 1; } @@ -2895,16 +2896,16 @@ pub fn write_metadata(cx: &mut CrateContext, crate: &ast::Crate) { let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item); let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate)); let llconst = C_struct([llmeta]); - let mut llglobal = str::as_c_str("rust_metadata", |buf| { + let mut llglobal = do "rust_metadata".as_c_str |buf| { unsafe { llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf) } - }); + }; unsafe { llvm::LLVMSetInitializer(llglobal, llconst); - str::as_c_str(cx.sess.targ_cfg.target_strs.meta_sect_name, |buf| { + do cx.sess.targ_cfg.target_strs.meta_sect_name.as_c_str |buf| { llvm::LLVMSetSection(llglobal, buf) - }); + }; lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage); let t_ptr_i8 = Type::i8p(); @@ -2923,7 +2924,7 @@ fn mk_global(ccx: &CrateContext, internal: bool) -> ValueRef { unsafe { - let llglobal = do str::as_c_str(name) |buf| { + let llglobal = do name.as_c_str |buf| { llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf) }; llvm::LLVMSetInitializer(llglobal, llval); diff --git a/src/librustc/middle/trans/builder.rs b/src/librustc/middle/trans/builder.rs index a4a976145b9..1c9161163cc 100644 --- a/src/librustc/middle/trans/builder.rs +++ b/src/librustc/middle/trans/builder.rs @@ -20,7 +20,6 @@ use middle::trans::type_::Type; use std::cast; use std::hashmap::HashMap; use std::libc::{c_uint, c_ulonglong, c_char}; -use std::str; use std::vec; use syntax::codemap::span; @@ -424,9 +423,9 @@ impl Builder { if name.is_empty() { llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), noname()) } else { - str::as_c_str( - name, - |c| llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), c)) + do name.as_c_str |c| { + llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), c) + } } } } @@ -896,9 +895,9 @@ impl Builder { let BB: BasicBlockRef = llvm::LLVMGetInsertBlock(self.llbuilder); let FN: ValueRef = llvm::LLVMGetBasicBlockParent(BB); let M: ModuleRef = llvm::LLVMGetGlobalParent(FN); - let T: ValueRef = str::as_c_str("llvm.trap", |buf| { + let T: ValueRef = do "llvm.trap".as_c_str |buf| { llvm::LLVMGetNamedFunction(M, buf) - }); + }; assert!((T as int != 0)); let args: &[ValueRef] = []; self.count_insn("trap"); diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index 9246ca1f641..15793ea747f 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -31,7 +31,6 @@ use util::ppaux::{Repr, ty_to_str}; use middle::trans::type_::Type; use std::libc::c_uint; -use std::str; use syntax::{ast, ast_util, ast_map}; pub fn const_lit(cx: &mut CrateContext, e: &ast::expr, lit: ast::lit) @@ -513,7 +512,7 @@ fn const_expr_unadjusted(cx: @mut CrateContext, e: &ast::expr) -> ValueRef { ast::expr_vec(ref es, ast::m_imm) => { let (cv, sz, llunitty) = const_vec(cx, e, *es); let llty = val_ty(cv); - let gv = do str::as_c_str("const") |name| { + let gv = do "const".as_c_str |name| { llvm::LLVMAddGlobal(cx.llmod, llty.to_ref(), name) }; llvm::LLVMSetInitializer(gv, cv); diff --git a/src/librustc/middle/trans/context.rs b/src/librustc/middle/trans/context.rs index 2879e4babbc..78544c1c6c4 100644 --- a/src/librustc/middle/trans/context.rs +++ b/src/librustc/middle/trans/context.rs @@ -28,7 +28,6 @@ use middle::trans::type_::Type; use std::hash; use std::hashmap::{HashMap, HashSet}; -use std::str; use std::local_data; use syntax::ast; @@ -125,13 +124,11 @@ impl CrateContext { unsafe { let llcx = llvm::LLVMContextCreate(); set_task_llcx(llcx); - let llmod = str::as_c_str(name, |buf| { - llvm::LLVMModuleCreateWithNameInContext(buf, llcx) - }); + let llmod = name.as_c_str(|buf| llvm::LLVMModuleCreateWithNameInContext(buf, llcx)); let data_layout: &str = sess.targ_cfg.target_strs.data_layout; let targ_triple: &str = sess.targ_cfg.target_strs.target_triple; - str::as_c_str(data_layout, |buf| llvm::LLVMSetDataLayout(llmod, buf)); - str::as_c_str(targ_triple, |buf| llvm::LLVMSetTarget(llmod, buf)); + data_layout.as_c_str(|buf| llvm::LLVMSetDataLayout(llmod, buf)); + targ_triple.as_c_str(|buf| llvm::LLVMSetTarget(llmod, buf)); let targ_cfg = sess.targ_cfg; let td = mk_target_data(sess.targ_cfg.target_strs.data_layout); diff --git a/src/librustc/middle/trans/controlflow.rs b/src/librustc/middle/trans/controlflow.rs index 9ffe3c9f25c..1c967131b0a 100644 --- a/src/librustc/middle/trans/controlflow.rs +++ b/src/librustc/middle/trans/controlflow.rs @@ -27,7 +27,6 @@ use util::ppaux; use middle::trans::type_::Type; -use std::str; use syntax::ast; use syntax::ast::ident; use syntax::ast_map::path_mod; @@ -251,9 +250,9 @@ pub fn trans_log(log_ex: &ast::expr, ccx, modpath, "loglevel"); let global; unsafe { - global = str::as_c_str(s, |buf| { + global = do s.as_c_str |buf| { llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf) - }); + }; llvm::LLVMSetGlobalConstant(global, False); llvm::LLVMSetInitializer(global, C_null(Type::i32())); lib::llvm::SetLinkage(global, lib::llvm::InternalLinkage); diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 7518d4eb824..4249e47d147 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -65,7 +65,6 @@ use util::ppaux::ty_to_str; use std::hashmap::HashMap; use std::libc::{c_uint, c_ulonglong, c_longlong}; use std::ptr; -use std::str::as_c_str; use std::vec; use syntax::codemap::span; use syntax::{ast, codemap, ast_util, ast_map}; @@ -159,7 +158,7 @@ pub fn create_local_var_metadata(bcx: block, local: @ast::Local) -> DIVariable { Some(_) => lexical_block_metadata(bcx) }; - let var_metadata = do as_c_str(name) |name| { + let var_metadata = do name.as_c_str |name| { unsafe { llvm::LLVMDIBuilderCreateLocalVariable( DIB(cx), @@ -225,7 +224,7 @@ pub fn create_argument_metadata(bcx: block, arg: &ast::arg, span: span) -> Optio // XXX: This is wrong; it should work for multiple bindings. let ident = path.idents.last(); let name: &str = cx.sess.str_of(*ident); - let var_metadata = do as_c_str(name) |name| { + let var_metadata = do name.as_c_str |name| { unsafe { llvm::LLVMDIBuilderCreateLocalVariable( DIB(cx), @@ -354,8 +353,8 @@ pub fn create_function_metadata(fcx: fn_ctxt) -> DISubprogram { }; let fn_metadata = - do as_c_str(cx.sess.str_of(ident)) |name| { - do as_c_str(cx.sess.str_of(ident)) |linkage| { + do cx.sess.str_of(ident).as_c_str |name| { + do cx.sess.str_of(ident).as_c_str |linkage| { unsafe { llvm::LLVMDIBuilderCreateFunction( DIB(cx), @@ -402,11 +401,11 @@ fn compile_unit_metadata(cx: @mut CrateContext) { let work_dir = cx.sess.working_dir.to_str(); let producer = fmt!("rustc version %s", env!("CFG_VERSION")); - do as_c_str(crate_name) |crate_name| { - do as_c_str(work_dir) |work_dir| { - do as_c_str(producer) |producer| { - do as_c_str("") |flags| { - do as_c_str("") |split_name| { + do crate_name.as_c_str |crate_name| { + do work_dir.as_c_str |work_dir| { + do producer.as_c_str |producer| { + do "".as_c_str |flags| { + do "".as_c_str |split_name| { unsafe { llvm::LLVMDIBuilderCreateCompileUnit(dcx.builder, DW_LANG_RUST as c_uint, crate_name, work_dir, producer, @@ -433,8 +432,8 @@ fn file_metadata(cx: &mut CrateContext, full_path: &str) -> DIFile { }; let file_metadata = - do as_c_str(file_name) |file_name| { - do as_c_str(work_dir) |work_dir| { + do file_name.as_c_str |file_name| { + do work_dir.as_c_str |work_dir| { unsafe { llvm::LLVMDIBuilderCreateFile(DIB(cx), file_name, work_dir) } @@ -522,7 +521,7 @@ fn basic_type_metadata(cx: &mut CrateContext, t: ty::t) -> DIType { let llvm_type = type_of::type_of(cx, t); let (size, align) = size_and_align_of(cx, llvm_type); - let ty_metadata = do as_c_str(name) |name| { + let ty_metadata = do name.as_c_str |name| { unsafe { llvm::LLVMDIBuilderCreateBasicType( DIB(cx), @@ -543,7 +542,7 @@ fn pointer_type_metadata(cx: &mut CrateContext, let pointer_llvm_type = type_of::type_of(cx, pointer_type); let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type); let name = ty_to_str(cx.tcx, pointer_type); - let ptr_metadata = do as_c_str(name) |name| { + let ptr_metadata = do name.as_c_str |name| { unsafe { llvm::LLVMDIBuilderCreatePointerType( DIB(cx), @@ -1038,7 +1037,7 @@ fn unimplemented_type_metadata(cx: &mut CrateContext, t: ty::t) -> DIType { debug!("unimplemented_type_metadata: %?", ty::get(t)); let name = ty_to_str(cx.tcx, t); - let metadata = do as_c_str(fmt!("NYI<%s>", name)) |name| { + let metadata = do fmt!("NYI<%s>", name).as_c_str |name| { unsafe { llvm::LLVMDIBuilderCreateBasicType( DIB(cx), diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index d3f5b9844c9..d66b43167ce 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -39,7 +39,6 @@ use middle::trans::type_::Type; use std::io; use std::libc::c_uint; -use std::str; use syntax::ast; pub fn trans_free(cx: block, v: ValueRef) -> block { @@ -658,11 +657,11 @@ pub fn declare_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info { let name = mangle_internal_name_by_type_and_seq(ccx, t, "tydesc").to_managed(); note_unique_llvm_symbol(ccx, name); debug!("+++ declare_tydesc %s %s", ppaux::ty_to_str(ccx.tcx, t), name); - let gvar = str::as_c_str(name, |buf| { + let gvar = do name.as_c_str |buf| { unsafe { llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type.to_ref(), buf) } - }); + }; let inf = @mut tydesc_info { ty: t, tydesc: gvar, diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index 349c41b13a9..dddf494856e 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -382,8 +382,8 @@ pub fn link_exe(_src: &Path, _dest: &Path) -> bool { pub fn link_exe(src: &Path, dest: &Path) -> bool { use std::{libc, str}; unsafe { - do str::as_c_str(src.to_str()) |src_buf| { - do str::as_c_str(dest.to_str()) |dest_buf| { + do src.to_str().as_c_str |src_buf| { + do dest.to_str().as_c_str |dest_buf| { libc::link(src_buf, dest_buf) == 0 as libc::c_int && libc::chmod(dest_buf, 755) == 0 as libc::c_int } diff --git a/src/libstd/io.rs b/src/libstd/io.rs index 6335588db50..fed4eb26dbe 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -63,7 +63,7 @@ use iterator::IteratorUtil; use ptr; use result; use str; -use str::{StrSlice, OwnedStr, StrUtil}; +use str::{StrSlice, OwnedStr}; use to_str::ToStr; use uint; use vec; diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 2c3ce86ef78..8c118d0be76 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -243,12 +243,11 @@ pub fn env() -> ~[(~str,~str)] { pub fn getenv(n: &str) -> Option<~str> { unsafe { do with_env_lock { - let s = str::as_c_str(n, |s| libc::getenv(s)); + let s = n.as_c_str(|s| libc::getenv(s as *libc::c_char)); if ptr::null::() == cast::transmute(s) { - None::<~str> + None } else { - let s = cast::transmute(s); - Some::<~str>(str::raw::from_buf(s)) + Some(str::raw::from_buf(cast::transmute(s))) } } } @@ -277,8 +276,8 @@ pub fn getenv(n: &str) -> Option<~str> { pub fn setenv(n: &str, v: &str) { unsafe { do with_env_lock { - do str::as_c_str(n) |nbuf| { - do str::as_c_str(v) |vbuf| { + do n.to_str().as_c_str |nbuf| { + do v.to_str().as_c_str |vbuf| { libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1); } } @@ -309,7 +308,7 @@ pub fn unsetenv(n: &str) { fn _unsetenv(n: &str) { unsafe { do with_env_lock { - do str::as_c_str(n) |nbuf| { + do n.to_str().as_c_str |nbuf| { libc::funcs::posix01::unistd::unsetenv(nbuf); } } @@ -465,7 +464,7 @@ pub fn self_exe_path() -> Option { use libc::funcs::posix01::unistd::readlink; let mut path_str = str::with_capacity(TMPBUF_SZ); - let len = do str::as_c_str(path_str) |buf| { + let len = do path_str.as_c_str |buf| { let buf = buf as *mut c_char; do "/proc/self/exe".as_c_str |proc_self_buf| { readlink(proc_self_buf, buf, TMPBUF_SZ as size_t) @@ -598,7 +597,7 @@ pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) -> bool { /// Indicates whether a path represents a directory pub fn path_is_dir(p: &Path) -> bool { unsafe { - do str::as_c_str(p.to_str()) |buf| { + do p.to_str().as_c_str |buf| { rustrt::rust_path_is_dir(buf) != 0 as c_int } } @@ -607,7 +606,7 @@ pub fn path_is_dir(p: &Path) -> bool { /// Indicates whether a path exists pub fn path_exists(p: &Path) -> bool { unsafe { - do str::as_c_str(p.to_str()) |buf| { + do p.to_str().as_c_str |buf| { rustrt::rust_path_exists(buf) != 0 as c_int } } @@ -924,7 +923,7 @@ pub fn copy_file(from: &Path, to: &Path) -> bool { fclose(ostream); // Give the new file the old file's permissions - if do str::as_c_str(to.to_str()) |to_buf| { + if do to.to_str().as_c_str |to_buf| { libc::chmod(to_buf, from_mode as libc::mode_t) } != 0 { return false; // should be a condition... @@ -1290,7 +1289,7 @@ pub fn glob(pattern: &str) -> ~[Path] { } let mut g = default_glob_t(); - do str::as_c_str(pattern) |c_pattern| { + do pattern.as_c_str |c_pattern| { unsafe { libc::glob(c_pattern, 0, ptr::null(), &mut g) } }; do(|| { diff --git a/src/libstd/path.rs b/src/libstd/path.rs index 3ec3407b1cc..ef7a055b0e7 100644 --- a/src/libstd/path.rs +++ b/src/libstd/path.rs @@ -23,7 +23,6 @@ use iterator::IteratorUtil; use libc; use option::{None, Option, Some}; use str::{OwnedStr, Str, StrSlice, StrVector}; -use str; use to_str::ToStr; use ascii::{AsciiCast, AsciiStr}; use vec::{OwnedVector, ImmutableVector}; @@ -342,13 +341,11 @@ mod stat { #[cfg(target_os = "win32")] impl WindowsPath { pub fn stat(&self) -> Option { - unsafe { - do str::as_c_str(self.to_str()) |buf| { - let mut st = stat::arch::default_stat(); - match libc::stat(buf, &mut st) { - 0 => Some(st), - _ => None, - } + do self.to_str().as_c_str |buf| { + let mut st = stat::arch::default_stat(); + match unsafe { libc::stat(buf, &mut st) } { + 0 => Some(st), + _ => None, } } } @@ -378,13 +375,11 @@ impl WindowsPath { #[cfg(not(target_os = "win32"))] impl PosixPath { pub fn stat(&self) -> Option { - unsafe { - do str::as_c_str(self.to_str()) |buf| { - let mut st = stat::arch::default_stat(); - match libc::stat(buf, &mut st) { - 0 => Some(st), - _ => None, - } + do self.to_str().as_c_str |buf| { + let mut st = stat::arch::default_stat(); + match unsafe { libc::stat(buf as *libc::c_char, &mut st) } { + 0 => Some(st), + _ => None, } } } @@ -458,13 +453,11 @@ impl PosixPath { #[cfg(unix)] impl PosixPath { pub fn lstat(&self) -> Option { - unsafe { - do str::as_c_str(self.to_str()) |buf| { - let mut st = stat::arch::default_stat(); - match libc::lstat(buf, &mut st) { - 0 => Some(st), - _ => None, - } + do self.to_str().as_c_str |buf| { + let mut st = stat::arch::default_stat(); + match unsafe { libc::lstat(buf, &mut st) } { + 0 => Some(st), + _ => None, } } } diff --git a/src/libstd/prelude.rs b/src/libstd/prelude.rs index e3e042a4947..0d9446bcfca 100644 --- a/src/libstd/prelude.rs +++ b/src/libstd/prelude.rs @@ -62,7 +62,7 @@ pub use path::PosixPath; pub use path::WindowsPath; pub use ptr::RawPtr; pub use ascii::{Ascii, AsciiCast, OwnedAsciiCast, AsciiStr, ToBytesConsume}; -pub use str::{Str, StrVector, StrSlice, OwnedStr, StrUtil, NullTerminatedStr}; +pub use str::{Str, StrVector, StrSlice, OwnedStr, NullTerminatedStr}; pub use from_str::{FromStr}; pub use to_bytes::IterBytes; pub use to_str::{ToStr, ToStrConsume}; diff --git a/src/libstd/ptr.rs b/src/libstd/ptr.rs index c2b59d51347..29564bd9728 100644 --- a/src/libstd/ptr.rs +++ b/src/libstd/ptr.rs @@ -461,17 +461,13 @@ pub mod ptr_tests { #[test] fn test_position() { - use str::as_c_str; use libc::c_char; let s = ~"hello"; unsafe { - assert!(2u == as_c_str(s, |p| position(p, - |c| *c == 'l' as c_char))); - assert!(4u == as_c_str(s, |p| position(p, - |c| *c == 'o' as c_char))); - assert!(5u == as_c_str(s, |p| position(p, - |c| *c == 0 as c_char))); + assert!(2u == s.as_c_str(|p| position(p, |c| *c == 'l' as c_char))); + assert!(4u == s.as_c_str(|p| position(p, |c| *c == 'o' as c_char))); + assert!(5u == s.as_c_str(|p| position(p, |c| *c == 0 as c_char))); } } @@ -480,9 +476,9 @@ pub mod ptr_tests { let s0 = ~"hello"; let s1 = ~"there"; let s2 = ~"thing"; - do str::as_c_str(s0) |p0| { - do str::as_c_str(s1) |p1| { - do str::as_c_str(s2) |p2| { + do s0.as_c_str |p0| { + do s1.as_c_str |p1| { + do s2.as_c_str |p2| { let v = ~[p0, p1, p2, null()]; do v.as_imm_buf |vp, len| { assert_eq!(unsafe { buf_len(vp) }, 3u); diff --git a/src/libstd/rt/logging.rs b/src/libstd/rt/logging.rs index 84186180aa6..11d11daebc2 100644 --- a/src/libstd/rt/logging.rs +++ b/src/libstd/rt/logging.rs @@ -46,17 +46,15 @@ impl Logger for StdErrLogger { /// per-module global logging flags based on the logging spec pub fn init(crate_map: *u8) { use os; - use str; + use str::StrSlice; use ptr; use option::{Some, None}; let log_spec = os::getenv("RUST_LOG"); match log_spec { Some(spec) => { - do str::as_c_str(spec) |s| { - unsafe { - rust_update_log_settings(crate_map, s); - } + do spec.as_c_str |buf| { + unsafe { rust_update_log_settings(crate_map, buf) } } } None => { diff --git a/src/libstd/rt/uv/uvll.rs b/src/libstd/rt/uv/uvll.rs index 62bf8f27af9..1f27a577684 100644 --- a/src/libstd/rt/uv/uvll.rs +++ b/src/libstd/rt/uv/uvll.rs @@ -382,12 +382,12 @@ pub unsafe fn as_sockaddr_in6(addr: *sockaddr) -> *sockaddr_in6 { } pub unsafe fn malloc_ip4_addr(ip: &str, port: int) -> *sockaddr_in { - do str::as_c_str(ip) |ip_buf| { + do ip.as_c_str |ip_buf| { rust_uv_ip4_addrp(ip_buf as *u8, port as libc::c_int) } } pub unsafe fn malloc_ip6_addr(ip: &str, port: int) -> *sockaddr_in6 { - do str::as_c_str(ip) |ip_buf| { + do ip.as_c_str |ip_buf| { rust_uv_ip6_addrp(ip_buf as *u8, port as libc::c_int) } } diff --git a/src/libstd/run.rs b/src/libstd/run.rs index c0b46ba273d..d8fc68d6422 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -507,7 +507,7 @@ fn spawn_process_os(prog: &str, args: &[~str], do with_envp(env) |envp| { do with_dirp(dir) |dirp| { - do str::as_c_str(cmd) |cmdp| { + do cmd.as_c_str |cmdp| { let created = CreateProcessA(ptr::null(), cast::transmute(cmdp), ptr::mut_null(), ptr::mut_null(), TRUE, 0, envp, dirp, &mut si, &mut pi); @@ -696,12 +696,12 @@ fn spawn_process_os(prog: &str, args: &[~str], #[cfg(unix)] fn with_argv(prog: &str, args: &[~str], cb: &fn(**libc::c_char) -> T) -> T { - let mut argptrs = ~[str::as_c_str(prog, |b| b)]; + let mut argptrs = ~[prog.as_c_str(|b| b)]; let mut tmps = ~[]; for args.iter().advance |arg| { let t = @(*arg).clone(); tmps.push(t); - argptrs.push(str::as_c_str(*t, |b| b)); + argptrs.push(t.as_c_str(|b| b)); } argptrs.push(ptr::null()); argptrs.as_imm_buf(|buf, _len| cb(buf)) @@ -723,7 +723,7 @@ fn with_envp(env: Option<&[(~str, ~str)]>, cb: &fn(*c_void) -> T) -> T { &(ref k, ref v) => { let kv = @fmt!("%s=%s", *k, *v); tmps.push(kv); - ptrs.push(str::as_c_str(*kv, |b| b)); + ptrs.push(kv.as_c_str(|b| b)); } } } @@ -761,7 +761,7 @@ fn with_envp(env: Option<&[(~str, ~str)]>, cb: &fn(*mut c_void) -> T) -> T { fn with_dirp(d: Option<&Path>, cb: &fn(*libc::c_char) -> T) -> T { match d { - Some(dir) => str::as_c_str(dir.to_str(), cb), + Some(dir) => dir.to_str().as_c_str(cb), None => cb(ptr::null()) } } diff --git a/src/libstd/str.rs b/src/libstd/str.rs index c16e87000f5..ab3d362ba79 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -773,51 +773,6 @@ static TAG_THREE_B: uint = 224u; static MAX_THREE_B: uint = 65536u; static TAG_FOUR_B: uint = 240u; -/** - * A dummy trait to hold all the utility methods that we implement on strings. - */ -pub trait StrUtil { - /** - * Work with the byte buffer of a string as a null-terminated C string. - * - * Allows for unsafe manipulation of strings, which is useful for foreign - * interop. This is similar to `str::as_buf`, but guarantees null-termination. - * If the given slice is not already null-terminated, this function will - * allocate a temporary, copy the slice, null terminate it, and pass - * that instead. - * - * # Example - * - * ~~~ {.rust} - * let s = "PATH".as_c_str(|path| libc::getenv(path)); - * ~~~ - */ - fn as_c_str(self, f: &fn(*libc::c_char) -> T) -> T; -} - -impl<'self> StrUtil for &'self str { - #[inline] - fn as_c_str(self, f: &fn(*libc::c_char) -> T) -> T { - do self.as_buf |buf, len| { - // NB: len includes the trailing null. - assert!(len > 0); - if unsafe { *(ptr::offset(buf,len-1)) != 0 } { - to_owned(self).as_c_str(|s| f(s)) - } else { - f(buf as *libc::c_char) - } - } - } -} - -/** - * Deprecated. Use the `as_c_str` method on strings instead. - */ -#[inline] -pub fn as_c_str(s: &str, f: &fn(*libc::c_char) -> T) -> T { - s.as_c_str(f) -} - /// Unsafe operations pub mod raw { use cast; @@ -1271,6 +1226,7 @@ pub trait StrSlice<'self> { fn subslice_offset(&self, inner: &str) -> uint; fn as_buf(&self, f: &fn(*u8, uint) -> T) -> T; + fn as_c_str(&self, f: &fn(*libc::c_char) -> T) -> T; } /// Extension methods for strings @@ -2027,6 +1983,34 @@ impl<'self> StrSlice<'self> for &'self str { f(buf, len) } } + + /** + * Work with the byte buffer of a string as a null-terminated C string. + * + * Allows for unsafe manipulation of strings, which is useful for foreign + * interop. This is similar to `str::as_buf`, but guarantees null-termination. + * If the given slice is not already null-terminated, this function will + * allocate a temporary, copy the slice, null terminate it, and pass + * that instead. + * + * # Example + * + * ~~~ {.rust} + * let s = "PATH".as_c_str(|path| libc::getenv(path)); + * ~~~ + */ + #[inline] + fn as_c_str(&self, f: &fn(*libc::c_char) -> T) -> T { + do self.as_buf |buf, len| { + // NB: len includes the trailing null. + assert!(len > 0); + if unsafe { *(ptr::offset(buf, len - 1)) != 0 } { + self.to_owned().as_c_str(|s| f(s)) + } else { + f(buf as *libc::c_char) + } + } + } } #[allow(missing_doc)] From cf75330807ad908a428e9c162a388e367fb07781 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Mon, 22 Jul 2013 21:42:51 -0700 Subject: [PATCH 06/17] std: add test for str::as_c_str --- src/librustpkg/util.rs | 2 +- src/libstd/run.rs | 1 - src/libstd/str.rs | 22 ++++++++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index dddf494856e..60367fd9aa6 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -380,7 +380,7 @@ pub fn link_exe(_src: &Path, _dest: &Path) -> bool { #[cfg(target_os = "freebsd")] #[cfg(target_os = "macos")] pub fn link_exe(src: &Path, dest: &Path) -> bool { - use std::{libc, str}; + use std::libc; unsafe { do src.to_str().as_c_str |src_buf| { do dest.to_str().as_c_str |dest_buf| { diff --git a/src/libstd/run.rs b/src/libstd/run.rs index d8fc68d6422..b6cc556af10 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -23,7 +23,6 @@ use option::{Some, None}; use os; use prelude::*; use ptr; -use str; use task; use vec::ImmutableVector; diff --git a/src/libstd/str.rs b/src/libstd/str.rs index ab3d362ba79..5bd084b8796 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -3116,6 +3116,28 @@ mod tests { } } + #[test] + fn test_as_c_str() { + let a = ~""; + do a.as_c_str |buf| { + unsafe { + assert_eq!(*ptr::offset(buf, 0), 0); + } + } + + let a = ~"hello"; + do a.as_c_str |buf| { + unsafe { + assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char); + assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char); + assert_eq!(*ptr::offset(buf, 2), 'l' as libc::c_char); + assert_eq!(*ptr::offset(buf, 3), 'l' as libc::c_char); + assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char); + assert_eq!(*ptr::offset(buf, 5), 0); + } + } + } + #[test] fn test_subslice_offset() { let a = "kernelsprite"; From 3b818edeba4dbca7c605ca5600f2d1b4b000120b Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Mon, 22 Jul 2013 21:45:33 -0700 Subject: [PATCH 07/17] std and extra: use as_c_str instead of as_buf in a couple places These uses are assuming the strings are null terminated, so it should be using `as_c_str` instead of `as_buf` --- src/libstd/rt/borrowck.rs | 6 +++--- src/libstd/sys.rs | 20 ++++++-------------- src/libstd/unstable/lang.rs | 4 ++-- 3 files changed, 11 insertions(+), 19 deletions(-) diff --git a/src/libstd/rt/borrowck.rs b/src/libstd/rt/borrowck.rs index 42e545ce1a9..1a468fcf215 100644 --- a/src/libstd/rt/borrowck.rs +++ b/src/libstd/rt/borrowck.rs @@ -76,7 +76,7 @@ unsafe fn fail_borrowed(box: *mut BoxRepr, file: *c_char, line: size_t) { match try_take_task_borrow_list() { None => { // not recording borrows let msg = "borrowed"; - do msg.as_buf |msg_p, _| { + do msg.as_c_str |msg_p| { sys::begin_unwind_(msg_p as *c_char, file, line); } } @@ -92,7 +92,7 @@ unsafe fn fail_borrowed(box: *mut BoxRepr, file: *c_char, line: size_t) { sep = " and at "; } } - do msg.as_buf |msg_p, _| { + do msg.as_c_str |msg_p| { sys::begin_unwind_(msg_p as *c_char, file, line) } } @@ -231,7 +231,7 @@ pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint, let br = borrow_list.pop(); if br.box != a || br.file != file || br.line != line { let err = fmt!("wrong borrow found, br=%?", br); - do err.as_buf |msg_p, _| { + do err.as_c_str |msg_p| { sys::begin_unwind_(msg_p as *c_char, file, line) } } diff --git a/src/libstd/sys.rs b/src/libstd/sys.rs index 0c497ecef27..28cd2345aab 100644 --- a/src/libstd/sys.rs +++ b/src/libstd/sys.rs @@ -123,13 +123,9 @@ pub trait FailWithCause { impl FailWithCause for ~str { fn fail_with(cause: ~str, file: &'static str, line: uint) -> ! { - do cause.as_buf |msg_buf, _msg_len| { - do file.as_buf |file_buf, _file_len| { - unsafe { - let msg_buf = cast::transmute(msg_buf); - let file_buf = cast::transmute(file_buf); - begin_unwind_(msg_buf, file_buf, line as libc::size_t) - } + do cause.as_c_str |msg_buf| { + do file.as_c_str |file_buf| { + begin_unwind_(msg_buf, file_buf, line as libc::size_t) } } } @@ -137,13 +133,9 @@ impl FailWithCause for ~str { impl FailWithCause for &'static str { fn fail_with(cause: &'static str, file: &'static str, line: uint) -> ! { - do cause.as_buf |msg_buf, _msg_len| { - do file.as_buf |file_buf, _file_len| { - unsafe { - let msg_buf = cast::transmute(msg_buf); - let file_buf = cast::transmute(file_buf); - begin_unwind_(msg_buf, file_buf, line as libc::size_t) - } + do cause.as_c_str |msg_buf| { + do file.as_c_str |file_buf| { + begin_unwind_(msg_buf, file_buf, line as libc::size_t) } } } diff --git a/src/libstd/unstable/lang.rs b/src/libstd/unstable/lang.rs index f8cd08b4bf6..d96681ae803 100644 --- a/src/libstd/unstable/lang.rs +++ b/src/libstd/unstable/lang.rs @@ -56,8 +56,8 @@ pub fn fail_bounds_check(file: *c_char, line: size_t, index: size_t, len: size_t) { let msg = fmt!("index out of bounds: the len is %d but the index is %d", len as int, index as int); - do msg.as_buf |p, _len| { - fail_(p as *c_char, file, line); + do msg.as_c_str |buf| { + fail_(buf, file, line); } } From cc9666f68f829c17ff3a535f714fe5dbb3f72755 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Mon, 22 Jul 2013 21:48:22 -0700 Subject: [PATCH 08/17] std: rename str.as_buf to as_imm_buf, add str.as_mut_buf --- src/libstd/option.rs | 4 +- src/libstd/str.rs | 128 +++++++++---------- src/test/run-pass/c-stack-returning-int64.rs | 4 +- 3 files changed, 65 insertions(+), 71 deletions(-) diff --git a/src/libstd/option.rs b/src/libstd/option.rs index 9fe590e28ee..c4fee908266 100644 --- a/src/libstd/option.rs +++ b/src/libstd/option.rs @@ -445,10 +445,10 @@ fn test_unwrap_ptr() { #[test] fn test_unwrap_str() { let x = ~"test"; - let addr_x = x.as_buf(|buf, _len| buf); + let addr_x = x.as_imm_buf(|buf, _len| buf); let opt = Some(x); let y = opt.unwrap(); - let addr_y = y.as_buf(|buf, _len| buf); + let addr_y = y.as_imm_buf(|buf, _len| buf); assert_eq!(addr_x, addr_y); } diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 5bd084b8796..59121d6f135 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -191,10 +191,10 @@ impl<'self, S: Str> StrVector for &'self [S] { s.reserve(len); unsafe { - do s.as_buf |buf, _| { - let mut buf = ::cast::transmute_mut_unsafe(buf); + do s.as_mut_buf |buf, _| { + let mut buf = buf; for self.iter().advance |ss| { - do ss.as_slice().as_buf |ssbuf, sslen| { + do ss.as_slice().as_imm_buf |ssbuf, sslen| { let sslen = sslen - 1; ptr::copy_memory(buf, ssbuf, sslen); buf = buf.offset(sslen); @@ -222,12 +222,12 @@ impl<'self, S: Str> StrVector for &'self [S] { s.reserve(len); unsafe { - do s.as_buf |buf, _| { - do sep.as_buf |sepbuf, seplen| { + do s.as_mut_buf |buf, _| { + do sep.as_imm_buf |sepbuf, seplen| { let seplen = seplen - 1; let mut buf = ::cast::transmute_mut_unsafe(buf); for self.iter().advance |ss| { - do ss.as_slice().as_buf |ssbuf, sslen| { + do ss.as_slice().as_imm_buf |ssbuf, sslen| { let sslen = sslen - 1; if first { first = false; @@ -533,8 +533,8 @@ Section: Comparing strings #[lang="str_eq"] #[inline] pub fn eq_slice(a: &str, b: &str) -> bool { - do a.as_buf |ap, alen| { - do b.as_buf |bp, blen| { + do a.as_imm_buf |ap, alen| { + do b.as_imm_buf |bp, blen| { if (alen != blen) { false } else { unsafe { @@ -550,8 +550,8 @@ pub fn eq_slice(a: &str, b: &str) -> bool { #[cfg(test)] #[inline] pub fn eq_slice(a: &str, b: &str) -> bool { - do a.as_buf |ap, alen| { - do b.as_buf |bp, blen| { + do a.as_imm_buf |ap, alen| { + do b.as_imm_buf |bp, blen| { if (alen != blen) { false } else { unsafe { @@ -868,7 +868,7 @@ pub mod raw { * If end is greater than the length of the string. */ pub unsafe fn slice_bytes_owned(s: &str, begin: uint, end: uint) -> ~str { - do s.as_buf |sbuf, n| { + do s.as_imm_buf |sbuf, n| { assert!((begin <= end)); assert!((end <= n)); @@ -896,7 +896,7 @@ pub mod raw { */ #[inline] pub unsafe fn slice_bytes(s: &str, begin: uint, end: uint) -> &str { - do s.as_buf |sbuf, n| { + do s.as_imm_buf |sbuf, n| { assert!((begin <= end)); assert!((end <= n)); @@ -909,8 +909,7 @@ pub mod raw { pub unsafe fn push_byte(s: &mut ~str, b: u8) { let new_len = s.len() + 1; s.reserve_at_least(new_len); - do s.as_buf |buf, len| { - let buf: *mut u8 = ::cast::transmute(buf); + do s.as_mut_buf |buf, len| { *ptr::mut_offset(buf, len) = b; } set_len(&mut *s, new_len); @@ -1130,7 +1129,7 @@ impl<'self> Str for @str { impl<'self> Container for &'self str { #[inline] fn len(&self) -> uint { - do self.as_buf |_p, n| { n - 1u } + do self.as_imm_buf |_p, n| { n - 1u } } #[inline] fn is_empty(&self) -> bool { @@ -1225,7 +1224,8 @@ pub trait StrSlice<'self> { fn subslice_offset(&self, inner: &str) -> uint; - fn as_buf(&self, f: &fn(*u8, uint) -> T) -> T; + fn as_imm_buf(&self, f: &fn(*u8, uint) -> T) -> T; + fn as_mut_buf(&self, f: &fn(*mut u8, uint) -> T) -> T; fn as_c_str(&self, f: &fn(*libc::c_char) -> T) -> T; } @@ -1849,15 +1849,15 @@ impl<'self> StrSlice<'self> for &'self str { /// Given a string, make a new string with repeated copies of it. fn repeat(&self, nn: uint) -> ~str { - do self.as_buf |buf, len| { + do self.as_imm_buf |buf, len| { let mut ret = ~""; // ignore the NULL terminator let len = len - 1; ret.reserve(nn * len); unsafe { - do ret.as_buf |rbuf, _len| { - let mut rbuf = ::cast::transmute_mut_unsafe(rbuf); + do ret.as_mut_buf |rbuf, _len| { + let mut rbuf = rbuf; for nn.times { ptr::copy_memory(rbuf, buf, len); @@ -1950,8 +1950,8 @@ impl<'self> StrSlice<'self> for &'self str { */ #[inline] fn subslice_offset(&self, inner: &str) -> uint { - do self.as_buf |a, a_len| { - do inner.as_buf |b, b_len| { + do self.as_imm_buf |a, a_len| { + do inner.as_imm_buf |b, b_len| { let a_start: uint; let a_end: uint; let b_start: uint; @@ -1976,7 +1976,7 @@ impl<'self> StrSlice<'self> for &'self str { * to full strings, or suffixes of them. */ #[inline] - fn as_buf(&self, f: &fn(*u8, uint) -> T) -> T { + fn as_imm_buf(&self, f: &fn(*u8, uint) -> T) -> T { unsafe { let v: *(*u8, uint) = cast::transmute(self); let (buf, len) = *v; @@ -1984,6 +1984,23 @@ impl<'self> StrSlice<'self> for &'self str { } } + /** + * Work with the byte buffer and length of a slice. + * + * The given length is one byte longer than the 'official' indexable + * length of the string. This is to permit probing the byte past the + * indexable area for a null byte, as is the case in slices pointing + * to full strings, or suffixes of them. + */ + #[inline] + fn as_mut_buf(&self, f: &fn(*mut u8, uint) -> T) -> T { + unsafe { + let v: *(*mut u8, uint) = cast::transmute(self); + let (buf, len) = *v; + f(buf, len) + } + } + /** * Work with the byte buffer of a string as a null-terminated C string. * @@ -2001,7 +2018,7 @@ impl<'self> StrSlice<'self> for &'self str { */ #[inline] fn as_c_str(&self, f: &fn(*libc::c_char) -> T) -> T { - do self.as_buf |buf, len| { + do self.as_imm_buf |buf, len| { // NB: len includes the trailing null. assert!(len > 0); if unsafe { *(ptr::offset(buf, len - 1)) != 0 } { @@ -2068,8 +2085,8 @@ impl OwnedStr for ~str { let llen = self.len(); let rlen = rhs.len(); self.reserve(llen + rlen); - do self.as_buf |lbuf, _llen| { - do rhs.as_buf |rbuf, _rlen| { + do self.as_imm_buf |lbuf, _llen| { + do rhs.as_imm_buf |rbuf, _rlen| { let dst = ptr::offset(lbuf, llen); let dst = ::cast::transmute_mut_unsafe(dst); ptr::copy_memory(dst, rbuf, rlen); @@ -2086,8 +2103,8 @@ impl OwnedStr for ~str { let llen = self.len(); let rlen = rhs.len(); self.reserve_at_least(llen + rlen); - do self.as_buf |lbuf, _llen| { - do rhs.as_buf |rbuf, _rlen| { + do self.as_imm_buf |lbuf, _llen| { + do rhs.as_imm_buf |rbuf, _rlen| { let dst = ptr::offset(lbuf, llen); let dst = ::cast::transmute_mut_unsafe(dst); ptr::copy_memory(dst, rbuf, rlen); @@ -2110,8 +2127,7 @@ impl OwnedStr for ~str { let new_len = len + nb; self.reserve_at_least(new_len); let off = len; - do self.as_buf |buf, _len| { - let buf: *mut u8 = ::cast::transmute(buf); + do self.as_mut_buf |buf, _len| { match nb { 1u => { *ptr::mut_offset(buf, off) = code as u8; @@ -3073,45 +3089,23 @@ mod tests { } #[test] - fn test_as_buf() { - let a = "Abcdefg"; - let b = do a.as_buf |buf, _l| { - assert_eq!(unsafe { *buf }, 65u8); - 100 - }; - assert_eq!(b, 100); - } - - #[test] - fn test_as_buf_small() { - let a = "A"; - let b = do a.as_buf |buf, _l| { - assert_eq!(unsafe { *buf }, 65u8); - 100 - }; - assert_eq!(b, 100); - } - - #[test] - fn test_as_buf2() { - unsafe { - let s = ~"hello"; - let sb = s.as_buf(|b, _l| b); - let s_cstr = raw::from_buf(sb); - assert_eq!(s_cstr, s); - } - } - - #[test] - fn test_as_buf_3() { - let a = ~"hello"; - do a.as_buf |buf, len| { + fn test_as_imm_buf() { + do "".as_imm_buf |buf, len| { + assert_eq!(len, 1); unsafe { - assert_eq!(a[0], 'h' as u8); - assert_eq!(*buf, 'h' as u8); - assert_eq!(len, 6u); - assert_eq!(*ptr::offset(buf,4u), 'o' as u8); - assert_eq!(*ptr::offset(buf,5u), 0u8); + assert_eq!(*ptr::offset(buf, 0), 0); + } + } + + do "hello".as_imm_buf |buf, len| { + assert_eq!(len, 6); + unsafe { + assert_eq!(*ptr::offset(buf, 0), 'h' as u8); + assert_eq!(*ptr::offset(buf, 1), 'e' as u8); + assert_eq!(*ptr::offset(buf, 2), 'l' as u8); + assert_eq!(*ptr::offset(buf, 3), 'l' as u8); + assert_eq!(*ptr::offset(buf, 4), 'o' as u8); + assert_eq!(*ptr::offset(buf, 5), 0); } } } diff --git a/src/test/run-pass/c-stack-returning-int64.rs b/src/test/run-pass/c-stack-returning-int64.rs index 12fa8066686..9775f1ef45a 100644 --- a/src/test/run-pass/c-stack-returning-int64.rs +++ b/src/test/run-pass/c-stack-returning-int64.rs @@ -20,11 +20,11 @@ mod libc { } fn atol(s: ~str) -> int { - s.as_buf(|x, _len| unsafe { libc::atol(x) }) + s.as_imm_buf(|x, _len| unsafe { libc::atol(x) }) } fn atoll(s: ~str) -> i64 { - s.as_buf(|x, _len| unsafe { libc::atoll(x) }) + s.as_imm_buf(|x, _len| unsafe { libc::atoll(x) }) } pub fn main() { From 31b77aecfc195c774852965329b5e75453eee0b2 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Tue, 23 Jul 2013 06:49:17 -0700 Subject: [PATCH 09/17] std: remove str::to_owned and str::raw::slice_bytes_owned --- src/libextra/getopts.rs | 42 +++++++------- src/libextra/time.rs | 2 +- src/librustc/metadata/filesearch.rs | 5 +- src/librustc/metadata/loader.rs | 2 +- src/libstd/io.rs | 2 +- src/libstd/str.rs | 63 +++++++-------------- src/test/run-pass/struct-order-of-eval-1.rs | 2 +- src/test/run-pass/struct-order-of-eval-2.rs | 2 +- 8 files changed, 50 insertions(+), 70 deletions(-) diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index 07a1c674404..c6db3637eed 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -457,7 +457,7 @@ pub fn opt_default(mm: &Matches, nm: &str, def: &str) -> Option<~str> { let vals = opt_vals(mm, nm); if vals.is_empty() { return None::<~str>; } return match vals[0] { Val(ref s) => Some::<~str>((*s).clone()), - _ => Some::<~str>(str::to_owned(def)) } + _ => Some::<~str>(def.to_owned()) } } #[deriving(Eq)] @@ -497,10 +497,10 @@ pub mod groups { desc: &str, hint: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); - return OptGroup { short_name: str::to_owned(short_name), - long_name: str::to_owned(long_name), - hint: str::to_owned(hint), - desc: str::to_owned(desc), + return OptGroup { short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: hint.to_owned(), + desc: desc.to_owned(), hasarg: Yes, occur: Req}; } @@ -510,10 +510,10 @@ pub mod groups { desc: &str, hint: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); - return OptGroup {short_name: str::to_owned(short_name), - long_name: str::to_owned(long_name), - hint: str::to_owned(hint), - desc: str::to_owned(desc), + return OptGroup {short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: hint.to_owned(), + desc: desc.to_owned(), hasarg: Yes, occur: Optional}; } @@ -523,10 +523,10 @@ pub mod groups { desc: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); - return OptGroup {short_name: str::to_owned(short_name), - long_name: str::to_owned(long_name), + return OptGroup {short_name: short_name.to_owned(), + long_name: long_name.to_owned(), hint: ~"", - desc: str::to_owned(desc), + desc: desc.to_owned(), hasarg: No, occur: Optional}; } @@ -536,10 +536,10 @@ pub mod groups { desc: &str, hint: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); - return OptGroup {short_name: str::to_owned(short_name), - long_name: str::to_owned(long_name), - hint: str::to_owned(hint), - desc: str::to_owned(desc), + return OptGroup {short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: hint.to_owned(), + desc: desc.to_owned(), hasarg: Maybe, occur: Optional}; } @@ -552,10 +552,10 @@ pub mod groups { desc: &str, hint: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); - return OptGroup {short_name: str::to_owned(short_name), - long_name: str::to_owned(long_name), - hint: str::to_owned(hint), - desc: str::to_owned(desc), + return OptGroup {short_name: short_name.to_owned(), + long_name: long_name.to_owned(), + hint: hint.to_owned(), + desc: desc.to_owned(), hasarg: Yes, occur: Multi}; } @@ -678,7 +678,7 @@ pub mod groups { row }); - return str::to_owned(brief) + + return brief.to_owned() + "\n\nOptions:\n" + rows.collect::<~[~str]>().connect("\n") + "\n\n"; diff --git a/src/libextra/time.rs b/src/libextra/time.rs index e08327f82c7..b1c07e83f52 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -1027,7 +1027,7 @@ mod tests { fn test(s: &str, format: &str) -> bool { match strptime(s, format) { - Ok(ref tm) => tm.strftime(format) == str::to_owned(s), + Ok(ref tm) => tm.strftime(format) == s.to_owned(), Err(e) => fail!(e) } } diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index de4eb5c3953..6017b804b57 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -12,7 +12,6 @@ use std::option; use std::os; use std::result; -use std::str; // A module for searching for libraries // FIXME (#2658): I'm not happy how this module turned out. Should @@ -83,7 +82,7 @@ pub fn mk_filesearch(maybe_sysroot: &Option<@Path>, @FileSearchImpl { sysroot: sysroot, addl_lib_search_paths: addl_lib_search_paths, - target_triple: str::to_owned(target_triple) + target_triple: target_triple.to_owned() } as @FileSearch } @@ -110,7 +109,7 @@ pub fn search(filesearch: @FileSearch, pick: pick) -> Option { pub fn relative_target_lib_path(target_triple: &str) -> Path { Path(libdir()).push_many([~"rustc", - str::to_owned(target_triple), + target_triple.to_owned(), libdir()]) } diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index a0789b3e323..481d27f6944 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -80,7 +80,7 @@ fn libname(cx: &Context) -> (~str, ~str) { os_freebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX), }; - (str::to_owned(dll_prefix), str::to_owned(dll_suffix)) + (dll_prefix.to_owned(), dll_suffix.to_owned()) } fn find_library_crate_aux( diff --git a/src/libstd/io.rs b/src/libstd/io.rs index fed4eb26dbe..05a5184ccba 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -763,7 +763,7 @@ impl ReaderUtil for T { fn read_lines(&self) -> ~[~str] { do vec::build |push| { for self.each_line |line| { - push(str::to_owned(line)); + push(line.to_owned()); } } } diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 59121d6f135..42b651a8e38 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -32,7 +32,7 @@ use ptr::RawPtr; use to_str::ToStr; use uint; use vec; -use vec::{OwnedVector, OwnedCopyableVector, ImmutableVector}; +use vec::{OwnedVector, OwnedCopyableVector, ImmutableVector, MutableVector}; /* Section: Conditions @@ -120,23 +120,17 @@ pub fn from_bytes_slice<'a>(vector: &'a [u8]) -> &'a str { } } -/// Copy a slice into a new unique str -#[inline] -pub fn to_owned(s: &str) -> ~str { - unsafe { raw::slice_bytes_owned(s, 0, s.len()) } -} - impl ToStr for ~str { #[inline] - fn to_str(&self) -> ~str { to_owned(*self) } + fn to_str(&self) -> ~str { self.to_owned() } } impl<'self> ToStr for &'self str { #[inline] - fn to_str(&self) -> ~str { to_owned(*self) } + fn to_str(&self) -> ~str { self.to_owned() } } impl ToStr for @str { #[inline] - fn to_str(&self) -> ~str { to_owned(*self) } + fn to_str(&self) -> ~str { self.to_owned() } } /** @@ -857,33 +851,6 @@ pub mod raw { ::cast::transmute(v) } - /** - * Takes a bytewise (not UTF-8) slice from a string. - * - * Returns the substring from [`begin`..`end`). - * - * # Failure - * - * If begin is greater than end. - * If end is greater than the length of the string. - */ - pub unsafe fn slice_bytes_owned(s: &str, begin: uint, end: uint) -> ~str { - do s.as_imm_buf |sbuf, n| { - assert!((begin <= end)); - assert!((end <= n)); - - let mut v = vec::with_capacity(end - begin + 1u); - do v.as_imm_buf |vbuf, _vlen| { - let vbuf = ::cast::transmute_mut_unsafe(vbuf); - let src = ptr::offset(sbuf, begin); - ptr::copy_memory(vbuf, src, end - begin); - } - vec::raw::set_len(&mut v, end - begin); - v.push(0u8); - ::cast::transmute(v) - } - } - /** * Takes a bytewise (not UTF-8) slice from a string. * @@ -936,7 +903,7 @@ pub mod raw { let len = s.len(); assert!((len > 0u)); let b = s[0]; - *s = raw::slice_bytes_owned(*s, 1u, len); + *s = s.slice(1, len).to_owned(); return b; } @@ -1609,7 +1576,21 @@ impl<'self> StrSlice<'self> for &'self str { /// Copy a slice into a new unique str #[inline] - fn to_owned(&self) -> ~str { to_owned(*self) } + fn to_owned(&self) -> ~str { + do self.as_imm_buf |src, len| { + assert!(len > 0); + unsafe { + let mut v = vec::with_capacity(len); + + do v.as_mut_buf |dst, _| { + ptr::copy_memory(dst, src, len - 1); + } + vec::raw::set_len(&mut v, len - 1); + v.push(0u8); + ::cast::transmute(v) + } + } + } #[inline] fn to_managed(&self) -> @str { @@ -2177,7 +2158,7 @@ impl OwnedStr for ~str { */ fn shift_char(&mut self) -> char { let CharRange {ch, next} = self.char_range_at(0u); - *self = unsafe { raw::slice_bytes_owned(*self, next, self.len()) }; + *self = self.slice(next, self.len()).to_owned(); return ch; } @@ -2270,7 +2251,7 @@ impl OwnedStr for ~str { impl Clone for ~str { #[inline] fn clone(&self) -> ~str { - to_owned(*self) + self.to_owned() } } diff --git a/src/test/run-pass/struct-order-of-eval-1.rs b/src/test/run-pass/struct-order-of-eval-1.rs index cfa0401e5b9..42908a339d2 100644 --- a/src/test/run-pass/struct-order-of-eval-1.rs +++ b/src/test/run-pass/struct-order-of-eval-1.rs @@ -14,5 +14,5 @@ struct S { f0: ~str, f1: int } pub fn main() { let s = ~"Hello, world!"; - let _s = S { f0: str::to_owned(s), ..S { f0: s, f1: 23 } }; + let _s = S { f0: s.to_owned(), ..S { f0: s, f1: 23 } }; } diff --git a/src/test/run-pass/struct-order-of-eval-2.rs b/src/test/run-pass/struct-order-of-eval-2.rs index f58e5bab3fe..b6851a72888 100644 --- a/src/test/run-pass/struct-order-of-eval-2.rs +++ b/src/test/run-pass/struct-order-of-eval-2.rs @@ -14,5 +14,5 @@ struct S { f0: ~str, f1: ~str } pub fn main() { let s = ~"Hello, world!"; - let _s = S { f1: str::to_owned(s), f0: s }; + let _s = S { f1: s.to_owned(), f0: s }; } From 2dd3c44a566537ef3f45e62e04148d61ab3cfd85 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Tue, 23 Jul 2013 06:51:27 -0700 Subject: [PATCH 10/17] std: remove a malloc from os::fill_charp_buf --- src/libstd/os.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 8c118d0be76..142021be471 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -87,9 +87,8 @@ pub fn getcwd() -> Path { // FIXME: move these to str perhaps? #2620 -pub fn fill_charp_buf(f: &fn(*mut c_char, size_t) -> bool) - -> Option<~str> { - let mut buf = vec::from_elem(TMPBUF_SZ, 0u8 as c_char); +pub fn fill_charp_buf(f: &fn(*mut c_char, size_t) -> bool) -> Option<~str> { + let mut buf = [0 as c_char, .. TMPBUF_SZ]; do buf.as_mut_buf |b, sz| { if f(b, sz as size_t) { unsafe { From 037a5b1af4b66e44d6d2130cedb576c5659bac8c Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Tue, 23 Jul 2013 12:30:34 -0700 Subject: [PATCH 11/17] str: move as_mut_buf into OwnedStr, and make it `self` --- src/libstd/str.rs | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 42b651a8e38..95cbc5aa409 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -1192,7 +1192,6 @@ pub trait StrSlice<'self> { fn subslice_offset(&self, inner: &str) -> uint; fn as_imm_buf(&self, f: &fn(*u8, uint) -> T) -> T; - fn as_mut_buf(&self, f: &fn(*mut u8, uint) -> T) -> T; fn as_c_str(&self, f: &fn(*libc::c_char) -> T) -> T; } @@ -1965,23 +1964,6 @@ impl<'self> StrSlice<'self> for &'self str { } } - /** - * Work with the byte buffer and length of a slice. - * - * The given length is one byte longer than the 'official' indexable - * length of the string. This is to permit probing the byte past the - * indexable area for a null byte, as is the case in slices pointing - * to full strings, or suffixes of them. - */ - #[inline] - fn as_mut_buf(&self, f: &fn(*mut u8, uint) -> T) -> T { - unsafe { - let v: *(*mut u8, uint) = cast::transmute(self); - let (buf, len) = *v; - f(buf, len) - } - } - /** * Work with the byte buffer of a string as a null-terminated C string. * @@ -2056,6 +2038,18 @@ pub trait OwnedStr { fn reserve_at_least(&mut self, n: uint); fn capacity(&self) -> uint; fn to_bytes_with_null(self) -> ~[u8]; + + /** + * Work with the mutable byte buffer and length of a slice. + * + * The given length is one byte longer than the 'official' indexable + * length of the string. This is to permit probing the byte past the + * indexable area for a null byte, as is the case in slices pointing + * to full strings, or suffixes of them. + * + * Make sure any mutations to this buffer keep this string valid UTF8. + */ + fn as_mut_buf(&mut self, f: &fn(*mut u8, uint) -> T) -> T; } impl OwnedStr for ~str { @@ -2246,6 +2240,12 @@ impl OwnedStr for ~str { fn to_bytes_with_null(self) -> ~[u8] { unsafe { ::cast::transmute(self) } } + + #[inline] + fn as_mut_buf(&mut self, f: &fn(*mut u8, uint) -> T) -> T { + let v: &mut ~[u8] = unsafe { cast::transmute(self) }; + v.as_mut_buf(f) + } } impl Clone for ~str { From cced3c9013e4f8e1202b6088f9d3b564e40cac40 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Tue, 23 Jul 2013 12:31:00 -0700 Subject: [PATCH 12/17] std: simplify str::as_imm_buf and vec::as_{imm,mut}_buf --- src/libstd/str.rs | 7 ++----- src/libstd/vec.rs | 11 ++++------- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 95cbc5aa409..b869f574beb 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -1957,11 +1957,8 @@ impl<'self> StrSlice<'self> for &'self str { */ #[inline] fn as_imm_buf(&self, f: &fn(*u8, uint) -> T) -> T { - unsafe { - let v: *(*u8, uint) = cast::transmute(self); - let (buf, len) = *v; - f(buf, len) - } + let v: &[u8] = unsafe { cast::transmute(*self) }; + v.as_imm_buf(f) } /** diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index baeb87e51b9..6bbf1210a31 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -1691,7 +1691,7 @@ pub trait MutableVector<'self, T> { unsafe fn unsafe_mut_ref(&self, index: uint) -> *mut T; unsafe fn unsafe_set(&self, index: uint, val: T); - fn as_mut_buf(&self, f: &fn(*mut T, uint) -> U) -> U; + fn as_mut_buf(self, f: &fn(*mut T, uint) -> U) -> U; } impl<'self,T> MutableVector<'self, T> for &'self mut [T] { @@ -1783,12 +1783,9 @@ impl<'self,T> MutableVector<'self, T> for &'self mut [T] { /// Similar to `as_imm_buf` but passing a `*mut T` #[inline] - fn as_mut_buf(&self, f: &fn(*mut T, uint) -> U) -> U { - unsafe { - let v : *(*mut T,uint) = transmute(self); - let (buf,len) = *v; - f(buf, len / sys::nonzero_size_of::()) - } + fn as_mut_buf(self, f: &fn(*mut T, uint) -> U) -> U { + let (buf, len): (*mut T, uint) = unsafe { transmute(self) }; + f(buf, len / sys::nonzero_size_of::()) } } From bbedbc04507ea3a1e87905c4b37c3460b5de1746 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Tue, 23 Jul 2013 09:54:28 -0700 Subject: [PATCH 13/17] std: inline str::with_capacity and vec::with_capacity --- src/libstd/str.rs | 8 +++----- src/libstd/vec.rs | 1 + 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/libstd/str.rs b/src/libstd/str.rs index b869f574beb..0d2cfa2e1e8 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -180,9 +180,7 @@ impl<'self, S: Str> StrVector for &'self [S] { let len = self.iter().transform(|s| s.as_slice().len()).sum(); - let mut s = ~""; - - s.reserve(len); + let mut s = with_capacity(len); unsafe { do s.as_mut_buf |buf, _| { @@ -678,6 +676,7 @@ pub fn from_utf16(v: &[u16]) -> ~str { * Allocates a new string with the specified capacity. The string returned is * the empty string, but has capacity for much more. */ +#[inline] pub fn with_capacity(capacity: uint) -> ~str { let mut buf = ~""; buf.reserve(capacity); @@ -1830,10 +1829,9 @@ impl<'self> StrSlice<'self> for &'self str { /// Given a string, make a new string with repeated copies of it. fn repeat(&self, nn: uint) -> ~str { do self.as_imm_buf |buf, len| { - let mut ret = ~""; // ignore the NULL terminator let len = len - 1; - ret.reserve(nn * len); + let mut ret = with_capacity(nn * len); unsafe { do ret.as_mut_buf |rbuf, _len| { diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 6bbf1210a31..cc41f0dbb94 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -87,6 +87,7 @@ pub fn from_elem(n_elts: uint, t: T) -> ~[T] { } /// Creates a new vector with a capacity of `capacity` +#[inline] pub fn with_capacity(capacity: uint) -> ~[T] { unsafe { if contains_managed::() { From 1354cfa07f0f236708d31a743e9f5bbb3ab6872f Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Sun, 21 Jul 2013 08:57:16 -0700 Subject: [PATCH 14/17] clean up warnings --- src/libextra/future.rs | 2 +- src/test/run-pass/resource-cycle.rs | 12 +++++------- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/libextra/future.rs b/src/libextra/future.rs index d8f21b46013..3e5bca60a95 100644 --- a/src/libextra/future.rs +++ b/src/libextra/future.rs @@ -194,7 +194,7 @@ mod test { #[test] fn test_interface_unwrap() { - let mut f = from_value(~"fail"); + let f = from_value(~"fail"); assert_eq!(f.unwrap(), ~"fail"); } diff --git a/src/test/run-pass/resource-cycle.rs b/src/test/run-pass/resource-cycle.rs index 7858417a3ca..db73aac2eae 100644 --- a/src/test/run-pass/resource-cycle.rs +++ b/src/test/run-pass/resource-cycle.rs @@ -23,16 +23,14 @@ impl Drop for r { cast::transmute::<*r, uint>(self), cast::transmute::<**int, uint>(&(self.v)), cast::transmute::<*int, uint>(self.v)); - let v2: ~int = cast::transmute(self.v); + let _v2: ~int = cast::transmute(self.v); } } } fn r(v: *int) -> r { - unsafe { - r { - v: v - } + r { + v: v } } @@ -52,7 +50,7 @@ pub fn main() { let i2p = cast::transmute_copy(&i2); cast::forget(i2); - let mut x1 = @mut t(Node{ + let x1 = @mut t(Node{ next: None, r: { let rs = r(i1p); @@ -64,7 +62,7 @@ pub fn main() { cast::transmute::<@mut t, uint>(x1), cast::transmute::<*r, uint>(&x1.r)); - let mut x2 = @mut t(Node{ + let x2 = @mut t(Node{ next: None, r: { let rs = r(i2p); From d573ecd1f99944ca45837cbfc2efddcbddae8761 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Fri, 19 Jul 2013 19:50:10 -0700 Subject: [PATCH 15/17] rustc: remove unused variables --- src/librustc/middle/trans/_match.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index b125232a7aa..bffc8532af5 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -1279,8 +1279,6 @@ pub fn compile_submatch(bcx: block, assert!((m.len() > 0u || chk.is_some())); let _icx = push_ctxt("match::compile_submatch"); let mut bcx = bcx; - let tcx = bcx.tcx(); - let dm = tcx.def_map; if m.len() == 0u { Br(bcx, chk.get()()); return; From 9c3679a9a2caeacdd16735c64ab4837721287e64 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Tue, 23 Jul 2013 09:55:09 -0700 Subject: [PATCH 16/17] std: make str::append move self This eliminates a copy and fixes a FIXME. --- src/libstd/str.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 0d2cfa2e1e8..49a7eccaca8 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -2028,7 +2028,7 @@ pub trait OwnedStr { fn pop_char(&mut self) -> char; fn shift_char(&mut self) -> char; fn unshift_char(&mut self, ch: char); - fn append(&self, rhs: &str) -> ~str; // FIXME #4850: this should consume self. + fn append(self, rhs: &str) -> ~str; fn reserve(&mut self, n: uint); fn reserve_at_least(&mut self, n: uint); fn capacity(&self) -> uint; @@ -2162,11 +2162,10 @@ impl OwnedStr for ~str { /// Concatenate two strings together. #[inline] - fn append(&self, rhs: &str) -> ~str { - // FIXME #4850: this should consume self, but that causes segfaults - let mut v = self.clone(); - v.push_str_no_overallocate(rhs); - v + fn append(self, rhs: &str) -> ~str { + let mut new_str = self; + new_str.push_str_no_overallocate(rhs); + new_str } /** From 9a950802ed01ac2e7d7e04cb9df0519245551393 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Wed, 24 Jul 2013 12:33:49 -0700 Subject: [PATCH 17/17] std: str.as_bytes_with_null_consume() => str.to_bytes_with_null() --- src/libstd/run.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/run.rs b/src/libstd/run.rs index b6cc556af10..2a8d29214fa 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -746,7 +746,7 @@ fn with_envp(env: Option<&[(~str, ~str)]>, cb: &fn(*mut c_void) -> T) -> T { let mut blk = ~[]; for es.iter().advance |pair| { let kv = fmt!("%s=%s", pair.first(), pair.second()); - blk.push_all(kv.as_bytes_with_null_consume()); + blk.push_all(kv.to_bytes_with_null()); } blk.push(0); blk.as_imm_buf(|p, _len|