Skip to content

Commit af7eede

Browse files
committed
Remove an allocation from rt::init
Previously the thread name would first be heap allocated and then re-allocated to add a nul terminator. Now it will be heap allocated only once with nul terminator added form the start.
1 parent 6f6bb16 commit af7eede

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

library/std/src/rt.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
#![deny(unsafe_op_in_unsafe_fn)]
1717
#![allow(unused_macros)]
1818

19+
use crate::ffi::CString;
20+
1921
// Re-export some of our utilities which are expected by other crates.
2022
pub use crate::panicking::{begin_panic, begin_panic_fmt, panic_count};
2123

@@ -38,7 +40,7 @@ unsafe fn init(argc: isize, argv: *const *const u8) {
3840
// created. Note that this isn't necessary in general for new threads,
3941
// but we just do this to name the main thread and to give it correct
4042
// info about the stack bounds.
41-
let thread = Thread::new(Some("main".to_owned()));
43+
let thread = Thread::new(Some(CString::new("main").unwrap()));
4244
thread_info::set(main_guard, thread);
4345
}
4446
}

library/std/src/thread/mod.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,9 @@ impl Builder {
457457

458458
let stack_size = stack_size.unwrap_or_else(thread::min_stack);
459459

460-
let my_thread = Thread::new(name);
460+
let my_thread = Thread::new(name.map(|name| {
461+
CString::new(name).expect("thread name may not contain interior null bytes")
462+
}));
461463
let their_thread = my_thread.clone();
462464

463465
let my_packet: Arc<UnsafeCell<Option<Result<T>>>> = Arc::new(UnsafeCell::new(None));
@@ -1073,12 +1075,8 @@ pub struct Thread {
10731075
impl Thread {
10741076
// Used only internally to construct a thread object without spawning
10751077
// Panics if the name contains nuls.
1076-
pub(crate) fn new(name: Option<String>) -> Thread {
1077-
let cname =
1078-
name.map(|n| CString::new(n).expect("thread name may not contain interior null bytes"));
1079-
Thread {
1080-
inner: Arc::new(Inner { name: cname, id: ThreadId::new(), parker: Parker::new() }),
1081-
}
1078+
pub(crate) fn new(name: Option<CString>) -> Thread {
1079+
Thread { inner: Arc::new(Inner { name, id: ThreadId::new(), parker: Parker::new() }) }
10821080
}
10831081

10841082
/// Atomically makes the handle's token available if it is not already.

0 commit comments

Comments
 (0)