Skip to content

Commit b7dbeda

Browse files
committed
Change std::ffi::c_str_to_bytes to get the pointer as is
The lifetime of the resulting reference is freely inferred as per RFC PR rust-lang#556. [breaking-change]
1 parent 1bf653b commit b7dbeda

File tree

14 files changed

+41
-40
lines changed

14 files changed

+41
-40
lines changed

src/librustc_trans/back/write.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ pub fn llvm_err(handler: &diagnostic::Handler, msg: String) -> ! {
4949
if cstr == ptr::null() {
5050
handler.fatal(&msg[]);
5151
} else {
52-
let err = ffi::c_str_to_bytes(&cstr);
52+
let err = ffi::c_str_to_bytes(cstr);
5353
let err = String::from_utf8_lossy(err.as_slice()).to_string();
5454
libc::free(cstr as *mut _);
5555
handler.fatal(&format!("{}: {}",
@@ -380,7 +380,7 @@ unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_vo
380380
}
381381

382382
llvm::diagnostic::Optimization(opt) => {
383-
let pass_name = str::from_utf8(ffi::c_str_to_bytes(&opt.pass_name))
383+
let pass_name = str::from_utf8(ffi::c_str_to_bytes(opt.pass_name))
384384
.ok()
385385
.expect("got a non-UTF8 pass name from LLVM");
386386
let enabled = match cgcx.remark {

src/librustc_trans/trans/base.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3040,7 +3040,7 @@ fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
30403040
continue
30413041
}
30423042

3043-
let name = ffi::c_str_to_bytes(&llvm::LLVMGetValueName(val))
3043+
let name = ffi::c_str_to_bytes(llvm::LLVMGetValueName(val))
30443044
.to_vec();
30453045
declared.insert(name);
30463046
}
@@ -3057,7 +3057,7 @@ fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
30573057
continue
30583058
}
30593059

3060-
let name = ffi::c_str_to_bytes(&llvm::LLVMGetValueName(val))
3060+
let name = ffi::c_str_to_bytes(llvm::LLVMGetValueName(val))
30613061
.to_vec();
30623062
if !declared.contains(&name) &&
30633063
!reachable.contains(str::from_utf8(name.as_slice()).unwrap()) {

src/libstd/dynamic_lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ mod dl {
232232
let ret = if ptr::null() == last_error {
233233
Ok(result)
234234
} else {
235-
let s = ffi::c_str_to_bytes(&last_error);
235+
let s = ffi::c_str_to_bytes(last_error);
236236
Err(str::from_utf8(s).unwrap().to_string())
237237
};
238238

src/libstd/ffi/c_str.rs

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -132,13 +132,14 @@ impl fmt::Debug for CString {
132132
/// will then return a corresponding slice for the contents of the C string not
133133
/// including the nul terminator.
134134
///
135-
/// This function will tie the lifetime of the returned slice to the lifetime of
136-
/// the pointer provided. This is done to help prevent the slice from escaping
137-
/// the lifetime of the pointer itself. If a longer lifetime is needed, then
138-
/// `mem::copy_lifetime` should be used.
135+
/// The lifetime of the returned slice is inferred from its usage in the
136+
/// call context. See the documentation on `std::slice::from_raw_parts`
137+
/// for possible pitfalls and suggested ways to mitigate them.
139138
///
140-
/// This function is unsafe because there is no guarantee of the validity of the
141-
/// pointer `raw` or a guarantee that a nul terminator will be found.
139+
/// This function is unsafe because there is no guarantee of the validity of
140+
/// the pointer `raw` or a guarantee that a nul terminator will be found.
141+
/// There is also no guarantee whether the lifetime inferred is a suitable
142+
/// lifetime for the returned slice.
142143
///
143144
/// # Example
144145
///
@@ -155,23 +156,23 @@ impl fmt::Debug for CString {
155156
///
156157
/// unsafe {
157158
/// let to_print = my_string();
158-
/// let slice = ffi::c_str_to_bytes(&to_print);
159+
/// let slice = ffi::c_str_to_bytes(to_print);
159160
/// println!("string returned: {}", str::from_utf8(slice).unwrap());
160161
/// }
161162
/// # }
162163
/// ```
163-
pub unsafe fn c_str_to_bytes<'a>(raw: &'a *const libc::c_char) -> &'a [u8] {
164-
let len = libc::strlen(*raw);
165-
slice::from_raw_parts(*(raw as *const _ as *const *const u8), len as usize)
164+
pub unsafe fn c_str_to_bytes<'a>(raw: *const libc::c_char) -> &'a [u8] {
165+
let len = libc::strlen(raw);
166+
slice::from_raw_parts(raw as *const u8, len as usize)
166167
}
167168

168169
/// Interpret a C string as a byte slice with the nul terminator.
169170
///
170-
/// This function is identical to `from_raw_buf` except that the returned slice
171+
/// This function is identical to `c_str_to_bytes` except that the returned slice
171172
/// will include the nul terminator of the string.
172-
pub unsafe fn c_str_to_bytes_with_nul<'a>(raw: &'a *const libc::c_char) -> &'a [u8] {
173-
let len = libc::strlen(*raw) + 1;
174-
slice::from_raw_parts(*(raw as *const _ as *const *const u8), len as usize)
173+
pub unsafe fn c_str_to_bytes_with_nul<'a>(raw: *const libc::c_char) -> &'a [u8] {
174+
let len = libc::strlen(raw) + 1;
175+
slice::from_raw_parts(raw as *const u8, len as usize)
175176
}
176177

177178
#[cfg(test)]
@@ -186,8 +187,8 @@ mod tests {
186187
let data = b"123\0";
187188
let ptr = data.as_ptr() as *const libc::c_char;
188189
unsafe {
189-
assert_eq!(c_str_to_bytes(&ptr), b"123");
190-
assert_eq!(c_str_to_bytes_with_nul(&ptr), b"123\0");
190+
assert_eq!(c_str_to_bytes(ptr), b"123");
191+
assert_eq!(c_str_to_bytes_with_nul(ptr), b"123\0");
191192
}
192193
}
193194

src/libstd/os.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -563,7 +563,7 @@ unsafe fn load_argc_and_argv(argc: int,
563563
use iter::range;
564564

565565
(0..argc as uint).map(|i| {
566-
ffi::c_str_to_bytes(&*argv.offset(i as int)).to_vec()
566+
ffi::c_str_to_bytes(*argv.offset(i as int)).to_vec()
567567
}).collect()
568568
}
569569

@@ -628,7 +628,7 @@ fn real_args_as_bytes() -> Vec<Vec<u8>> {
628628
let tmp = objc_msgSend(args, objectAtSel, i);
629629
let utf_c_str: *const libc::c_char =
630630
mem::transmute(objc_msgSend(tmp, utf8Sel));
631-
res.push(c_str_to_bytes(&utf_c_str).to_vec());
631+
res.push(c_str_to_bytes(utf_c_str).to_vec());
632632
}
633633
}
634634

src/libstd/rt/args.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ mod imp {
9999
unsafe fn load_argc_and_argv(argc: int, argv: *const *const u8) -> Vec<Vec<u8>> {
100100
let argv = argv as *const *const libc::c_char;
101101
(0..argc as uint).map(|i| {
102-
ffi::c_str_to_bytes(&*argv.offset(i as int)).to_vec()
102+
ffi::c_str_to_bytes(*argv.offset(i as int)).to_vec()
103103
}).collect()
104104
}
105105

src/libstd/sys/common/net.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ pub fn get_address_name(addr: IpAddr) -> Result<String, IoError> {
325325
}
326326

327327
unsafe {
328-
Ok(str::from_utf8(ffi::c_str_to_bytes(&hostbuf.as_ptr()))
328+
Ok(str::from_utf8(ffi::c_str_to_bytes(hostbuf.as_ptr()))
329329
.unwrap().to_string())
330330
}
331331
}

src/libstd/sys/unix/backtrace.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> {
233233
output(w, idx,addr, None)
234234
} else {
235235
output(w, idx, addr, Some(unsafe {
236-
ffi::c_str_to_bytes(&info.dli_sname)
236+
ffi::c_str_to_bytes(info.dli_sname)
237237
}))
238238
}
239239
}
@@ -364,7 +364,7 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> {
364364
if ret == 0 || data.is_null() {
365365
output(w, idx, addr, None)
366366
} else {
367-
output(w, idx, addr, Some(unsafe { ffi::c_str_to_bytes(&data) }))
367+
output(w, idx, addr, Some(unsafe { ffi::c_str_to_bytes(data) }))
368368
}
369369
}
370370

src/libstd/sys/unix/fs.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ pub fn readdir(p: &Path) -> IoResult<Vec<Path>> {
212212
while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
213213
if entry_ptr.is_null() { break }
214214
paths.push(unsafe {
215-
Path::new(ffi::c_str_to_bytes(&rust_list_dir_val(entry_ptr)))
215+
Path::new(ffi::c_str_to_bytes(rust_list_dir_val(entry_ptr)))
216216
});
217217
}
218218
assert_eq!(unsafe { closedir(dir_ptr) }, 0);

src/libstd/sys/unix/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ pub fn last_gai_error(s: libc::c_int) -> IoError {
8585

8686
let mut err = decode_error(s);
8787
err.detail = Some(unsafe {
88-
str::from_utf8(ffi::c_str_to_bytes(&gai_strerror(s))).unwrap().to_string()
88+
str::from_utf8(ffi::c_str_to_bytes(gai_strerror(s))).unwrap().to_string()
8989
});
9090
err
9191
}

src/libstd/sys/unix/os.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ pub fn error_string(errno: i32) -> String {
9090
}
9191

9292
let p = p as *const _;
93-
str::from_utf8(ffi::c_str_to_bytes(&p)).unwrap().to_string()
93+
str::from_utf8(ffi::c_str_to_bytes(p)).unwrap().to_string()
9494
}
9595
}
9696

@@ -100,7 +100,7 @@ pub fn getcwd() -> IoResult<Path> {
100100
if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
101101
Err(IoError::last_error())
102102
} else {
103-
Ok(Path::new(ffi::c_str_to_bytes(&buf.as_ptr())))
103+
Ok(Path::new(ffi::c_str_to_bytes(buf.as_ptr())))
104104
}
105105
}
106106
}
@@ -213,7 +213,7 @@ pub fn load_self() -> Option<Vec<u8>> {
213213
if v.is_null() {
214214
None
215215
} else {
216-
Some(ffi::c_str_to_bytes(&v).to_vec())
216+
Some(ffi::c_str_to_bytes(v).to_vec())
217217
}
218218
}
219219
}
@@ -264,7 +264,7 @@ pub fn args() -> Args {
264264
let (argc, argv) = (*_NSGetArgc() as isize,
265265
*_NSGetArgv() as *const *const c_char);
266266
range(0, argc as isize).map(|i| {
267-
let bytes = ffi::c_str_to_bytes(&*argv.offset(i)).to_vec();
267+
let bytes = ffi::c_str_to_bytes(*argv.offset(i)).to_vec();
268268
OsStringExt::from_vec(bytes)
269269
}).collect::<Vec<_>>()
270270
};
@@ -322,7 +322,7 @@ pub fn args() -> Args {
322322
let tmp = objc_msgSend(args, objectAtSel, i);
323323
let utf_c_str: *const libc::c_char =
324324
mem::transmute(objc_msgSend(tmp, utf8Sel));
325-
let bytes = ffi::c_str_to_bytes(&utf_c_str).to_vec();
325+
let bytes = ffi::c_str_to_bytes(utf_c_str).to_vec();
326326
res.push(OsString::from_vec(bytes))
327327
}
328328
}
@@ -377,7 +377,7 @@ pub fn env() -> Env {
377377
}
378378
let mut result = Vec::new();
379379
while *environ != ptr::null() {
380-
result.push(parse(ffi::c_str_to_bytes(&*environ)));
380+
result.push(parse(ffi::c_str_to_bytes(*environ)));
381381
environ = environ.offset(1);
382382
}
383383
Env { iter: result.into_iter(), _dont_send_or_sync_me: 0 as *mut _ }
@@ -399,7 +399,7 @@ pub fn getenv(k: &OsStr) -> Option<OsString> {
399399
if s.is_null() {
400400
None
401401
} else {
402-
Some(OsStringExt::from_vec(ffi::c_str_to_bytes(&s).to_vec()))
402+
Some(OsStringExt::from_vec(ffi::c_str_to_bytes(s).to_vec()))
403403
}
404404
}
405405
}
@@ -475,7 +475,7 @@ pub fn home_dir() -> Option<Path> {
475475
_ => return None
476476
}
477477
let ptr = passwd.pw_dir as *const _;
478-
let bytes = ffi::c_str_to_bytes(&ptr).to_vec();
478+
let bytes = ffi::c_str_to_bytes(ptr).to_vec();
479479
return Some(OsStringExt::from_vec(bytes))
480480
}
481481
}

src/libstd/sys/windows/backtrace.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> {
362362
if ret == libc::TRUE {
363363
try!(write!(w, " - "));
364364
let ptr = info.Name.as_ptr() as *const libc::c_char;
365-
let bytes = unsafe { ffi::c_str_to_bytes(&ptr) };
365+
let bytes = unsafe { ffi::c_str_to_bytes(ptr) };
366366
match str::from_utf8(bytes) {
367367
Ok(s) => try!(demangle(w, s)),
368368
Err(..) => try!(w.write_all(&bytes[..bytes.len()-1])),

src/test/run-pass/running-with-no-runtime.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ fn start(argc: int, argv: *const *const u8) -> int {
3838
let args = unsafe {
3939
(0..argc as uint).map(|i| {
4040
let ptr = *argv.offset(i as int) as *const _;
41-
ffi::c_str_to_bytes(&ptr).to_vec()
41+
ffi::c_str_to_bytes(ptr).to_vec()
4242
}).collect::<Vec<_>>()
4343
};
4444
let me = args[0].as_slice();

src/test/run-pass/variadic-ffi.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ extern {
2222
unsafe fn check<T, F>(expected: &str, f: F) where F: FnOnce(*mut c_char) -> T {
2323
let mut x = [0 as c_char; 50];
2424
f(&mut x[0] as *mut c_char);
25-
assert_eq!(expected.as_bytes(), ffi::c_str_to_bytes(&x.as_ptr()));
25+
assert_eq!(expected.as_bytes(), ffi::c_str_to_bytes(x.as_ptr()));
2626
}
2727

2828
pub fn main() {

0 commit comments

Comments
 (0)