Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Use c"lit" for CStrings without unwrap #133701

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/back/lto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ fn prepare_lto(
// __llvm_profile_counter_bias is pulled in at link time by an undefined reference to
// __llvm_profile_runtime, therefore we won't know until link time if this symbol
// should have default visibility.
symbols_below_threshold.push(CString::new("__llvm_profile_counter_bias").unwrap());
symbols_below_threshold.push(c"__llvm_profile_counter_bias".to_owned());
Ok((symbols_below_threshold, upstream_modules))
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
}

fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
config.instrument_coverage.then(|| CString::new("default_%m_%p.profraw").unwrap())
config.instrument_coverage.then(|| c"default_%m_%p.profraw".to_owned())
}

pub(crate) unsafe fn llvm_optimize(
Expand Down
13 changes: 4 additions & 9 deletions compiler/rustc_error_codes/src/error_codes/E0060.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,19 @@ unsafe { printf(); } // error!
Using this declaration, it must be called with at least one argument, so
simply calling `printf()` is invalid. But the following uses are allowed:

```
```rust,edition2021
# use std::os::raw::{c_char, c_int};
# #[cfg_attr(all(windows, target_env = "msvc"),
# link(name = "legacy_stdio_definitions",
# kind = "static", modifiers = "-bundle"))]
# extern "C" { fn printf(_: *const c_char, ...) -> c_int; }
# fn main() {
unsafe {
use std::ffi::CString;

let fmt = CString::new("test\n").unwrap();
printf(fmt.as_ptr());
printf(c"test\n".as_ptr());

let fmt = CString::new("number = %d\n").unwrap();
printf(fmt.as_ptr(), 3);
printf(c"number = %d\n".as_ptr(), 3);

let fmt = CString::new("%d, %d\n").unwrap();
printf(fmt.as_ptr(), 10, 5);
printf(c"%d, %d\n".as_ptr(), 10, 5);
}
# }
```
32 changes: 15 additions & 17 deletions library/alloc/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ impl CString {
/// fn some_extern_function(s: *mut c_char);
/// }
///
/// let c_string = CString::new("Hello!").expect("CString::new failed");
/// let c_string = CString::from(c"Hello!");
/// let raw = c_string.into_raw();
/// unsafe {
/// some_extern_function(raw);
Expand Down Expand Up @@ -429,7 +429,7 @@ impl CString {
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
/// let c_string = CString::from(c"foo");
///
/// let ptr = c_string.into_raw();
///
Expand Down Expand Up @@ -487,7 +487,7 @@ impl CString {
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
/// let c_string = CString::from(c"foo");
/// let bytes = c_string.into_bytes();
/// assert_eq!(bytes, vec![b'f', b'o', b'o']);
/// ```
Expand All @@ -508,7 +508,7 @@ impl CString {
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
/// let c_string = CString::from(c"foo");
/// let bytes = c_string.into_bytes_with_nul();
/// assert_eq!(bytes, vec![b'f', b'o', b'o', b'\0']);
/// ```
Expand All @@ -530,7 +530,7 @@ impl CString {
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
/// let c_string = CString::from(c"foo");
/// let bytes = c_string.as_bytes();
/// assert_eq!(bytes, &[b'f', b'o', b'o']);
/// ```
Expand All @@ -550,7 +550,7 @@ impl CString {
/// ```
/// use std::ffi::CString;
///
/// let c_string = CString::new("foo").expect("CString::new failed");
/// let c_string = CString::from(c"foo");
/// let bytes = c_string.as_bytes_with_nul();
/// assert_eq!(bytes, &[b'f', b'o', b'o', b'\0']);
/// ```
Expand All @@ -568,7 +568,7 @@ impl CString {
/// ```
/// use std::ffi::{CString, CStr};
///
/// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
/// let c_string = CString::from(c"foo");
/// let cstr = c_string.as_c_str();
/// assert_eq!(cstr,
/// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
Expand All @@ -586,12 +586,9 @@ impl CString {
/// # Examples
///
/// ```
/// use std::ffi::{CString, CStr};
///
/// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
/// let c_string = c"foo".to_owned();
/// let boxed = c_string.into_boxed_c_str();
/// assert_eq!(&*boxed,
/// CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed"));
/// assert_eq!(boxed.to_bytes_with_nul(), b"foo\0");
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "into_boxed_c_str", since = "1.20.0")]
Expand Down Expand Up @@ -658,7 +655,7 @@ impl CString {
/// assert_eq!(
/// CString::from_vec_with_nul(b"abc\0".to_vec())
/// .expect("CString::from_vec_with_nul failed"),
/// CString::new(b"abc".to_vec()).expect("CString::new failed")
/// c"abc".to_owned()
/// );
/// ```
///
Expand Down Expand Up @@ -1168,11 +1165,12 @@ impl CStr {
/// # Examples
///
/// ```
/// use std::ffi::CString;
/// use std::ffi::{CStr, CString};
///
/// let c_string = CString::new(b"foo".to_vec()).expect("CString::new failed");
/// let boxed = c_string.into_boxed_c_str();
/// assert_eq!(boxed.into_c_string(), CString::new("foo").expect("CString::new failed"));
/// let boxed: Box<CStr> = Box::from(c"foo");
/// let c_string: CString = c"foo".to_owned();
///
/// assert_eq!(boxed.into_c_string(), c_string);
/// ```
#[rustc_allow_incoherent_impl]
#[must_use = "`self` will be dropped if the result is not used"]
Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/ffi/c_str/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ fn boxed_default() {

#[test]
fn test_c_str_clone_into() {
let mut c_string = CString::new("lorem").unwrap();
let mut c_string = c"lorem".to_owned();
let c_ptr = c_string.as_ptr();
let c_str = CStr::from_bytes_with_nul(b"ipsum\0").unwrap();
c_str.clone_into(&mut c_string);
Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/rc/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,9 @@ fn test_unsized() {
#[test]
fn test_maybe_thin_unsized() {
// If/when custom thin DSTs exist, this test should be updated to use one
use std::ffi::{CStr, CString};
use std::ffi::CStr;

let x: Rc<CStr> = Rc::from(CString::new("swordfish").unwrap().into_boxed_c_str());
let x: Rc<CStr> = Rc::from(c"swordfish");
assert_eq!(format!("{x:?}"), "\"swordfish\"");
let y: Weak<CStr> = Rc::downgrade(&x);
drop(x);
Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/sync/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,9 +412,9 @@ fn test_unsized() {
#[test]
fn test_maybe_thin_unsized() {
// If/when custom thin DSTs exist, this test should be updated to use one
use std::ffi::{CStr, CString};
use std::ffi::CStr;

let x: Arc<CStr> = Arc::from(CString::new("swordfish").unwrap().into_boxed_c_str());
let x: Arc<CStr> = Arc::from(c"swordfish");
assert_eq!(format!("{x:?}"), "\"swordfish\"");
let y: Weak<CStr> = Arc::downgrade(&x);
drop(x);
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/sys/pal/unix/process/process_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ impl Command {
fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| {
*saw_nul = true;
CString::new("<string-with-nul>").unwrap()
c"<string-with-nul>".to_owned()
})
}

Expand Down
3 changes: 1 addition & 2 deletions src/tools/miri/tests/pass-dep/libc/libc-fs-symlink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,8 @@ fn test_readlink() {
assert_eq!(res, small_buf.len() as isize);

// Test that we report a proper error for a missing path.
let bad_path = CString::new("MIRI_MISSING_FILE_NAME").unwrap();
let res = unsafe {
libc::readlink(bad_path.as_ptr(), small_buf.as_mut_ptr().cast(), small_buf.len())
libc::readlink(c"MIRI_MISSING_FILE_NAME".as_ptr(), small_buf.as_mut_ptr().cast(), small_buf.len())
};
assert_eq!(res, -1);
assert_eq!(Error::last_os_error().kind(), ErrorKind::NotFound);
Expand Down
4 changes: 1 addition & 3 deletions src/tools/miri/tests/pass-dep/libc/libc-fs-with-isolation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
//@compile-flags: -Zmiri-isolation-error=warn-nobacktrace
//@normalize-stderr-test: "(stat(x)?)" -> "$$STAT"

use std::ffi::CString;
use std::fs;
use std::io::{Error, ErrorKind};

Expand All @@ -13,10 +12,9 @@ fn main() {
}

// test `readlink`
let symlink_c_str = CString::new("foo.txt").unwrap();
let mut buf = vec![0; "foo_link.txt".len() + 1];
unsafe {
assert_eq!(libc::readlink(symlink_c_str.as_ptr(), buf.as_mut_ptr(), buf.len()), -1);
assert_eq!(libc::readlink(c"foo.txt".as_ptr(), buf.as_mut_ptr(), buf.len()), -1);
assert_eq!(Error::last_os_error().raw_os_error(), Some(libc::EACCES));
}

Expand Down
10 changes: 5 additions & 5 deletions src/tools/miri/tests/pass-dep/libc/libc-mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@ fn test_memcpy() {
}

fn test_strcpy() {
use std::ffi::{CStr, CString};
use std::ffi::CStr;

// case: src_size equals dest_size
unsafe {
let src = CString::new("rust").unwrap();
let size = src.as_bytes_with_nul().len();
let src = c"rust";
let size = src.to_bytes_with_nul().len();
let dest = libc::malloc(size);
libc::strcpy(dest as *mut libc::c_char, src.as_ptr());
assert_eq!(CStr::from_ptr(dest as *const libc::c_char), src.as_ref());
Expand All @@ -69,8 +69,8 @@ fn test_strcpy() {

// case: src_size is less than dest_size
unsafe {
let src = CString::new("rust").unwrap();
let size = src.as_bytes_with_nul().len();
let src = c"rust";
let size = src.to_bytes_with_nul().len();
let dest = libc::malloc(size + 1);
libc::strcpy(dest as *mut libc::c_char, src.as_ptr());
assert_eq!(CStr::from_ptr(dest as *const libc::c_char), src.as_ref());
Expand Down
4 changes: 1 addition & 3 deletions src/tools/rust-analyzer/crates/profile/src/memory_usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,13 @@ fn memusage_linux() -> MemoryUsage {
// mallinfo2 is very recent, so its presence needs to be detected at runtime.
// Both are abysmally slow.

use std::ffi::CStr;
use std::sync::atomic::{AtomicUsize, Ordering};

static MALLINFO2: AtomicUsize = AtomicUsize::new(1);

let mut mallinfo2 = MALLINFO2.load(Ordering::Relaxed);
if mallinfo2 == 1 {
let cstr = CStr::from_bytes_with_nul(b"mallinfo2\0").unwrap();
mallinfo2 = unsafe { libc::dlsym(libc::RTLD_DEFAULT, cstr.as_ptr()) } as usize;
mallinfo2 = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"mallinfo2".as_ptr()) } as usize;
// NB: races don't matter here, since they'll always store the same value
MALLINFO2.store(mallinfo2, Ordering::Relaxed);
}
Expand Down
2 changes: 1 addition & 1 deletion tests/run-make/libtest-thread-limit/rmake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn main() {
// If the process ID is 0, this is the child process responsible for running the test
// program.
if pid == 0 {
let test = CString::new("test").unwrap();
let test = c"test";
// The argv array should be terminated with a NULL pointer.
let argv = [test.as_ptr(), std::ptr::null()];
// rlim_cur is soft limit, rlim_max is hard limit.
Expand Down
4 changes: 2 additions & 2 deletions tests/ui/process/env-funky-keys.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//@ run-pass
//@ edition: 2021
// Ignore this test on Android, because it segfaults there.

//@ ignore-android
Expand Down Expand Up @@ -32,10 +33,9 @@ fn main() {
.unwrap()
.as_os_str()
.as_bytes()).unwrap();
let new_env_var = CString::new("FOOBAR").unwrap();
let filename: *const c_char = current_exe.as_ptr();
let argv: &[*const c_char] = &[filename, filename, ptr::null()];
let envp: &[*const c_char] = &[new_env_var.as_ptr(), ptr::null()];
let envp: &[*const c_char] = &[c"FOOBAR".as_ptr(), ptr::null()];
unsafe {
execve(filename, &argv[0], &envp[0]);
}
Expand Down
Loading