diff --git a/library/std/src/collections/hash/mod.rs b/library/std/src/collections/hash/mod.rs index 348820af54bff..0476b0206f3d7 100644 --- a/library/std/src/collections/hash/mod.rs +++ b/library/std/src/collections/hash/mod.rs @@ -1,4 +1,4 @@ //! Unordered containers, implemented as hash-tables -pub mod map; -pub mod set; +pub(crate) mod map; +pub(crate) mod set; diff --git a/library/std/src/error.rs b/library/std/src/error.rs index 05f8fd8de327f..23f8de5c39e06 100644 --- a/library/std/src/error.rs +++ b/library/std/src/error.rs @@ -15,7 +15,7 @@ mod private { // implementations, since that can enable unsound downcasting. #[unstable(feature = "error_type_id", issue = "60784")] #[derive(Debug)] - pub struct Internal; + pub(crate) struct Internal; } /// An error reporter that prints an error and its sources. diff --git a/library/std/src/fs/tests.rs b/library/std/src/fs/tests.rs index 839fdc96632d1..6a7cffadb06db 100644 --- a/library/std/src/fs/tests.rs +++ b/library/std/src/fs/tests.rs @@ -72,7 +72,7 @@ macro_rules! error_contains { // have permission, and return otherwise. This way, we still don't run these // tests most of the time, but at least we do if the user has the right // permissions. -pub fn got_symlink_permission(tmpdir: &TempDir) -> bool { +pub(crate) fn got_symlink_permission(tmpdir: &TempDir) -> bool { if cfg!(unix) { return true; } diff --git a/library/std/src/io/buffered/bufreader/buffer.rs b/library/std/src/io/buffered/bufreader/buffer.rs index e9e29d60ca282..f7cddee8375df 100644 --- a/library/std/src/io/buffered/bufreader/buffer.rs +++ b/library/std/src/io/buffered/bufreader/buffer.rs @@ -12,7 +12,7 @@ use crate::cmp; use crate::io::{self, BorrowedBuf, Read}; use crate::mem::MaybeUninit; -pub struct Buffer { +pub(crate) struct Buffer { // The buffer. buf: Box<[MaybeUninit]>, // The current seek offset into `buf`, must always be <= `filled`. @@ -30,54 +30,54 @@ pub struct Buffer { impl Buffer { #[inline] - pub fn with_capacity(capacity: usize) -> Self { + pub(crate) fn with_capacity(capacity: usize) -> Self { let buf = Box::new_uninit_slice(capacity); Self { buf, pos: 0, filled: 0, initialized: 0 } } #[inline] - pub fn buffer(&self) -> &[u8] { + pub(crate) fn buffer(&self) -> &[u8] { // SAFETY: self.pos and self.cap are valid, and self.cap => self.pos, and // that region is initialized because those are all invariants of this type. unsafe { MaybeUninit::slice_assume_init_ref(self.buf.get_unchecked(self.pos..self.filled)) } } #[inline] - pub fn capacity(&self) -> usize { + pub(crate) fn capacity(&self) -> usize { self.buf.len() } #[inline] - pub fn filled(&self) -> usize { + pub(crate) fn filled(&self) -> usize { self.filled } #[inline] - pub fn pos(&self) -> usize { + pub(crate) fn pos(&self) -> usize { self.pos } // This is only used by a test which asserts that the initialization-tracking is correct. #[cfg(test)] - pub fn initialized(&self) -> usize { + pub(crate) fn initialized(&self) -> usize { self.initialized } #[inline] - pub fn discard_buffer(&mut self) { + pub(crate) fn discard_buffer(&mut self) { self.pos = 0; self.filled = 0; } #[inline] - pub fn consume(&mut self, amt: usize) { + pub(crate) fn consume(&mut self, amt: usize) { self.pos = cmp::min(self.pos + amt, self.filled); } /// If there are `amt` bytes available in the buffer, pass a slice containing those bytes to /// `visitor` and return true. If there are not enough bytes available, return false. #[inline] - pub fn consume_with(&mut self, amt: usize, mut visitor: V) -> bool + pub(crate) fn consume_with(&mut self, amt: usize, mut visitor: V) -> bool where V: FnMut(&[u8]), { @@ -92,12 +92,12 @@ impl Buffer { } #[inline] - pub fn unconsume(&mut self, amt: usize) { + pub(crate) fn unconsume(&mut self, amt: usize) { self.pos = self.pos.saturating_sub(amt); } #[inline] - pub fn fill_buf(&mut self, mut reader: impl Read) -> io::Result<&[u8]> { + pub(crate) fn fill_buf(&mut self, mut reader: impl Read) -> io::Result<&[u8]> { // If we've reached the end of our internal buffer then we need to fetch // some more data from the reader. // Branch using `>=` instead of the more correct `==` diff --git a/library/std/src/io/buffered/linewritershim.rs b/library/std/src/io/buffered/linewritershim.rs index 0175d2693e894..b0fefb7d5d29a 100644 --- a/library/std/src/io/buffered/linewritershim.rs +++ b/library/std/src/io/buffered/linewritershim.rs @@ -11,12 +11,12 @@ use crate::sys_common::memchr; /// `BufWriters` to be temporarily given line-buffering logic; this is what /// enables Stdout to be alternately in line-buffered or block-buffered mode. #[derive(Debug)] -pub struct LineWriterShim<'a, W: Write> { +pub(crate) struct LineWriterShim<'a, W: Write> { buffer: &'a mut BufWriter, } impl<'a, W: Write> LineWriterShim<'a, W> { - pub fn new(buffer: &'a mut BufWriter) -> Self { + pub(crate) fn new(buffer: &'a mut BufWriter) -> Self { Self { buffer } } diff --git a/library/std/src/io/buffered/tests.rs b/library/std/src/io/buffered/tests.rs index 4c1b7d57684dd..c1882d3c3fe1e 100644 --- a/library/std/src/io/buffered/tests.rs +++ b/library/std/src/io/buffered/tests.rs @@ -8,7 +8,7 @@ use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::thread; /// A dummy reader intended at testing short-reads propagation. -pub struct ShortReader { +pub(crate) struct ShortReader { lengths: Vec, } @@ -541,25 +541,25 @@ fn bench_buffered_writer(b: &mut test::Bencher) { #[derive(Default, Clone)] struct ProgrammableSink { // Writes append to this slice - pub buffer: Vec, + pub(crate) buffer: Vec, // If true, writes will always be an error - pub always_write_error: bool, + pub(crate) always_write_error: bool, // If true, flushes will always be an error - pub always_flush_error: bool, + pub(crate) always_flush_error: bool, // If set, only up to this number of bytes will be written in a single // call to `write` - pub accept_prefix: Option, + pub(crate) accept_prefix: Option, // If set, counts down with each write, and writes return an error // when it hits 0 - pub max_writes: Option, + pub(crate) max_writes: Option, // If set, attempting to write when max_writes == Some(0) will be an // error; otherwise, it will return Ok(0). - pub error_after_max_writes: bool, + pub(crate) error_after_max_writes: bool, } impl Write for ProgrammableSink { @@ -1006,7 +1006,7 @@ enum RecordedEvent { #[derive(Debug, Clone, Default)] struct WriteRecorder { - pub events: Vec, + pub(crate) events: Vec, } impl Write for WriteRecorder { diff --git a/library/std/src/io/cursor/tests.rs b/library/std/src/io/cursor/tests.rs index d7c203c297fe6..f90fc9715f09f 100644 --- a/library/std/src/io/cursor/tests.rs +++ b/library/std/src/io/cursor/tests.rs @@ -518,7 +518,7 @@ fn test_partial_eq() { #[test] fn test_eq() { - struct AssertEq(pub T); + struct AssertEq(pub(crate) T); let _: AssertEq>> = AssertEq(Cursor::new(Vec::new())); } diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index 14bfef4c7aad9..d3803b8def241 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -610,7 +610,7 @@ pub fn stdout() -> Stdout { // Flush the data and disable buffering during shutdown // by replacing the line writer by one with zero // buffering capacity. -pub fn cleanup() { +pub(crate) fn cleanup() { let mut initialized = false; let stdout = STDOUT.get_or_init(|| { initialized = true; diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 363a266717467..2af6c97d15ba6 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -221,6 +221,7 @@ #![allow(unused_lifetimes)] #![deny(rustc::existing_doc_keyword)] #![deny(fuzzy_provenance_casts)] +#![cfg_attr(not(test), warn(unreachable_pub))] // Ensure that std can be linked against panic_abort despite compiled with `-C panic=unwind` #![deny(ffi_unwind_calls)] // std may use features in a platform-specific way @@ -518,6 +519,8 @@ pub mod fs; pub mod io; pub mod net; pub mod num; +// os-specific code may be incorrectly detected as unreachable +#[allow(unreachable_pub)] pub mod os; pub mod panic; pub mod path; @@ -582,7 +585,10 @@ pub mod arch { pub use std_detect::is_x86_feature_detected; // Platform-abstraction modules +// platform-specific code may be incorrectly detected as unreachable +#[allow(unreachable_pub)] mod sys; +#[allow(unreachable_pub)] mod sys_common; pub mod alloc; @@ -592,7 +598,7 @@ mod panicking; mod personality; #[path = "../../backtrace/src/lib.rs"] -#[allow(dead_code, unused_attributes, fuzzy_provenance_casts)] +#[allow(dead_code, unused_attributes, fuzzy_provenance_casts, unreachable_pub)] mod backtrace_rs; // Re-export macros defined in core. diff --git a/library/std/src/net/display_buffer.rs b/library/std/src/net/display_buffer.rs index 7aadf06e92fc6..ae59a40e245ac 100644 --- a/library/std/src/net/display_buffer.rs +++ b/library/std/src/net/display_buffer.rs @@ -3,19 +3,19 @@ use crate::mem::MaybeUninit; use crate::str; /// Used for slow path in `Display` implementations when alignment is required. -pub struct DisplayBuffer { +pub(crate) struct DisplayBuffer { buf: [MaybeUninit; SIZE], len: usize, } impl DisplayBuffer { #[inline] - pub const fn new() -> Self { + pub(crate) const fn new() -> Self { Self { buf: MaybeUninit::uninit_array(), len: 0 } } #[inline] - pub fn as_str(&self) -> &str { + pub(crate) fn as_str(&self) -> &str { // SAFETY: `buf` is only written to by the `fmt::Write::write_str` implementation // which writes a valid UTF-8 string to `buf` and correctly sets `len`. unsafe { diff --git a/library/std/src/net/test.rs b/library/std/src/net/test.rs index 37937b5ea9541..10ea6380eeb83 100644 --- a/library/std/src/net/test.rs +++ b/library/std/src/net/test.rs @@ -6,25 +6,25 @@ use crate::sync::atomic::{AtomicUsize, Ordering}; static PORT: AtomicUsize = AtomicUsize::new(0); -pub fn next_test_ip4() -> SocketAddr { +pub(crate) fn next_test_ip4() -> SocketAddr { let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port(); SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port)) } -pub fn next_test_ip6() -> SocketAddr { +pub(crate) fn next_test_ip6() -> SocketAddr { let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port(); SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), port, 0, 0)) } -pub fn sa4(a: Ipv4Addr, p: u16) -> SocketAddr { +pub(crate) fn sa4(a: Ipv4Addr, p: u16) -> SocketAddr { SocketAddr::V4(SocketAddrV4::new(a, p)) } -pub fn sa6(a: Ipv6Addr, p: u16) -> SocketAddr { +pub(crate) fn sa6(a: Ipv6Addr, p: u16) -> SocketAddr { SocketAddr::V6(SocketAddrV6::new(a, p, 0, 0)) } -pub fn tsa(a: A) -> Result, String> { +pub(crate) fn tsa(a: A) -> Result, String> { match a.to_socket_addrs() { Ok(a) => Ok(a.collect()), Err(e) => Err(e.to_string()), diff --git a/library/std/src/os/unix/mod.rs b/library/std/src/os/unix/mod.rs index f97fa0fb06f78..030639bd477e7 100644 --- a/library/std/src/os/unix/mod.rs +++ b/library/std/src/os/unix/mod.rs @@ -60,7 +60,7 @@ mod platform { #[cfg(target_os = "l4re")] pub use crate::os::l4re::*; #[cfg(target_os = "linux")] - pub use crate::os::linux::*; + pub(crate) use crate::os::linux::*; #[cfg(target_os = "macos")] pub use crate::os::macos::*; #[cfg(target_os = "netbsd")] diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index e59f32af77df8..76abb99d55797 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -404,7 +404,7 @@ pub mod panic_count { pub use realstd::rt::panic_count; /// Invoke a closure, capturing the cause of an unwinding panic if one occurs. -pub unsafe fn r#try R>(f: F) -> Result> { +pub(crate) unsafe fn r#try R>(f: F) -> Result> { union Data { f: ManuallyDrop, r: ManuallyDrop, @@ -517,14 +517,14 @@ pub unsafe fn r#try R>(f: F) -> Result> /// Determines whether the current thread is unwinding because of panic. #[inline] -pub fn panicking() -> bool { +pub(crate) fn panicking() -> bool { !panic_count::count_is_zero() } /// Entry point of panics from the core crate (`panic_impl` lang item). #[cfg(not(test))] #[panic_handler] -pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! { +pub(crate) fn begin_panic_handler(info: &PanicInfo<'_>) -> ! { struct PanicPayload<'a> { inner: &'a fmt::Arguments<'a>, string: Option, @@ -716,7 +716,7 @@ fn rust_panic_with_hook( /// This is the entry point for `resume_unwind`. /// It just forwards the payload to the panic runtime. -pub fn rust_panic_without_hook(payload: Box) -> ! { +pub(crate) fn rust_panic_without_hook(payload: Box) -> ! { panic_count::increase(); struct RewrapBox(Box); diff --git a/library/std/src/path/tests.rs b/library/std/src/path/tests.rs index dd307022c6d05..87d9dad9c2ae1 100644 --- a/library/std/src/path/tests.rs +++ b/library/std/src/path/tests.rs @@ -131,7 +131,7 @@ fn into() { #[test] #[cfg(unix)] -pub fn test_decompositions_unix() { +pub(crate) fn test_decompositions_unix() { t!("", iter: [], has_root: false, @@ -465,7 +465,7 @@ pub fn test_decompositions_unix() { #[test] #[cfg(windows)] -pub fn test_decompositions_windows() { +pub(crate) fn test_decompositions_windows() { t!("", iter: [], has_root: false, @@ -1095,7 +1095,7 @@ pub fn test_decompositions_windows() { } #[test] -pub fn test_stem_ext() { +pub(crate) fn test_stem_ext() { t!("foo", file_stem: Some("foo"), extension: None @@ -1138,7 +1138,7 @@ pub fn test_stem_ext() { } #[test] -pub fn test_prefix_ext() { +pub(crate) fn test_prefix_ext() { t!("foo", file_prefix: Some("foo"), extension: None @@ -1181,7 +1181,7 @@ pub fn test_prefix_ext() { } #[test] -pub fn test_push() { +pub(crate) fn test_push() { macro_rules! tp ( ($path:expr, $push:expr, $expected:expr) => ( { let mut actual = PathBuf::from($path); @@ -1279,7 +1279,7 @@ pub fn test_push() { } #[test] -pub fn test_pop() { +pub(crate) fn test_pop() { macro_rules! tp ( ($path:expr, $expected:expr, $output:expr) => ( { let mut actual = PathBuf::from($path); @@ -1333,7 +1333,7 @@ pub fn test_pop() { } #[test] -pub fn test_set_file_name() { +pub(crate) fn test_set_file_name() { macro_rules! tfn ( ($path:expr, $file:expr, $expected:expr) => ( { let mut p = PathBuf::from($path); @@ -1367,7 +1367,7 @@ pub fn test_set_file_name() { } #[test] -pub fn test_set_extension() { +pub(crate) fn test_set_extension() { macro_rules! tfe ( ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( { let mut p = PathBuf::from($path); @@ -1420,7 +1420,7 @@ fn test_eq_receivers() { } #[test] -pub fn test_compare() { +pub(crate) fn test_compare() { use crate::collections::hash_map::DefaultHasher; use crate::hash::{Hash, Hasher}; diff --git a/library/std/src/personality/dwarf/eh.rs b/library/std/src/personality/dwarf/eh.rs index 87585a8fcd0d7..413fe2aecdd39 100644 --- a/library/std/src/personality/dwarf/eh.rs +++ b/library/std/src/personality/dwarf/eh.rs @@ -15,44 +15,47 @@ use super::DwarfReader; use core::mem; use core::ptr; -pub const DW_EH_PE_omit: u8 = 0xFF; -pub const DW_EH_PE_absptr: u8 = 0x00; - -pub const DW_EH_PE_uleb128: u8 = 0x01; -pub const DW_EH_PE_udata2: u8 = 0x02; -pub const DW_EH_PE_udata4: u8 = 0x03; -pub const DW_EH_PE_udata8: u8 = 0x04; -pub const DW_EH_PE_sleb128: u8 = 0x09; -pub const DW_EH_PE_sdata2: u8 = 0x0A; -pub const DW_EH_PE_sdata4: u8 = 0x0B; -pub const DW_EH_PE_sdata8: u8 = 0x0C; - -pub const DW_EH_PE_pcrel: u8 = 0x10; -pub const DW_EH_PE_textrel: u8 = 0x20; -pub const DW_EH_PE_datarel: u8 = 0x30; -pub const DW_EH_PE_funcrel: u8 = 0x40; -pub const DW_EH_PE_aligned: u8 = 0x50; - -pub const DW_EH_PE_indirect: u8 = 0x80; +pub(crate) const DW_EH_PE_omit: u8 = 0xFF; +pub(crate) const DW_EH_PE_absptr: u8 = 0x00; + +pub(crate) const DW_EH_PE_uleb128: u8 = 0x01; +pub(crate) const DW_EH_PE_udata2: u8 = 0x02; +pub(crate) const DW_EH_PE_udata4: u8 = 0x03; +pub(crate) const DW_EH_PE_udata8: u8 = 0x04; +pub(crate) const DW_EH_PE_sleb128: u8 = 0x09; +pub(crate) const DW_EH_PE_sdata2: u8 = 0x0A; +pub(crate) const DW_EH_PE_sdata4: u8 = 0x0B; +pub(crate) const DW_EH_PE_sdata8: u8 = 0x0C; + +pub(crate) const DW_EH_PE_pcrel: u8 = 0x10; +pub(crate) const DW_EH_PE_textrel: u8 = 0x20; +pub(crate) const DW_EH_PE_datarel: u8 = 0x30; +pub(crate) const DW_EH_PE_funcrel: u8 = 0x40; +pub(crate) const DW_EH_PE_aligned: u8 = 0x50; + +pub(crate) const DW_EH_PE_indirect: u8 = 0x80; #[derive(Copy, Clone)] -pub struct EHContext<'a> { - pub ip: usize, // Current instruction pointer - pub func_start: usize, // Address of the current function - pub get_text_start: &'a dyn Fn() -> usize, // Get address of the code section - pub get_data_start: &'a dyn Fn() -> usize, // Get address of the data section +pub(crate) struct EHContext<'a> { + pub(crate) ip: usize, // Current instruction pointer + pub(crate) func_start: usize, // Address of the current function + pub(crate) get_text_start: &'a dyn Fn() -> usize, // Get address of the code section + pub(crate) get_data_start: &'a dyn Fn() -> usize, // Get address of the data section } -pub enum EHAction { +pub(crate) enum EHAction { None, Cleanup(usize), Catch(usize), Terminate, } -pub const USING_SJLJ_EXCEPTIONS: bool = cfg!(all(target_os = "ios", target_arch = "arm")); +pub(crate) const USING_SJLJ_EXCEPTIONS: bool = cfg!(all(target_os = "ios", target_arch = "arm")); -pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result { +pub(crate) unsafe fn find_eh_action( + lsda: *const u8, + context: &EHContext<'_>, +) -> Result { if lsda.is_null() { return Ok(EHAction::None); } diff --git a/library/std/src/personality/dwarf/mod.rs b/library/std/src/personality/dwarf/mod.rs index 652fbe95a14d1..fb6845c0b9649 100644 --- a/library/std/src/personality/dwarf/mod.rs +++ b/library/std/src/personality/dwarf/mod.rs @@ -9,19 +9,19 @@ #[cfg(test)] mod tests; -pub mod eh; +pub(crate) mod eh; use core::mem; -pub struct DwarfReader { - pub ptr: *const u8, +pub(crate) struct DwarfReader { + pub(crate) ptr: *const u8, } #[repr(C, packed)] struct Unaligned(T); impl DwarfReader { - pub fn new(ptr: *const u8) -> DwarfReader { + pub(crate) fn new(ptr: *const u8) -> DwarfReader { DwarfReader { ptr } } @@ -29,7 +29,7 @@ impl DwarfReader { // on a 4-byte boundary. This may cause problems on platforms with strict // alignment requirements. By wrapping data in a "packed" struct, we are // telling the backend to generate "misalignment-safe" code. - pub unsafe fn read(&mut self) -> T { + pub(crate) unsafe fn read(&mut self) -> T { let Unaligned(result) = *(self.ptr as *const Unaligned); self.ptr = self.ptr.add(mem::size_of::()); result @@ -37,7 +37,7 @@ impl DwarfReader { // ULEB128 and SLEB128 encodings are defined in Section 7.6 - "Variable // Length Data". - pub unsafe fn read_uleb128(&mut self) -> u64 { + pub(crate) unsafe fn read_uleb128(&mut self) -> u64 { let mut shift: usize = 0; let mut result: u64 = 0; let mut byte: u8; @@ -52,7 +52,7 @@ impl DwarfReader { result } - pub unsafe fn read_sleb128(&mut self) -> i64 { + pub(crate) unsafe fn read_sleb128(&mut self) -> i64 { let mut shift: u32 = 0; let mut result: u64 = 0; let mut byte: u8; diff --git a/library/std/src/process/tests.rs b/library/std/src/process/tests.rs index b4f6cc2dabae3..d8354d2763e8b 100644 --- a/library/std/src/process/tests.rs +++ b/library/std/src/process/tests.rs @@ -68,7 +68,7 @@ fn signal_reported_right() { } } -pub fn run_output(mut cmd: Command) -> String { +pub(crate) fn run_output(mut cmd: Command) -> String { let p = cmd.spawn(); assert!(p.is_ok()); let mut p = p.unwrap(); @@ -216,18 +216,18 @@ fn test_wait_with_output_once() { } #[cfg(all(unix, not(target_os = "android")))] -pub fn env_cmd() -> Command { +pub(crate) fn env_cmd() -> Command { Command::new("env") } #[cfg(target_os = "android")] -pub fn env_cmd() -> Command { +pub(crate) fn env_cmd() -> Command { let mut cmd = Command::new("/system/bin/sh"); cmd.arg("-c").arg("set"); cmd } #[cfg(windows)] -pub fn env_cmd() -> Command { +pub(crate) fn env_cmd() -> Command { let mut cmd = Command::new("cmd"); cmd.arg("/c").arg("set"); cmd diff --git a/library/std/src/sync/mpmc/context.rs b/library/std/src/sync/mpmc/context.rs index bbfc6ce00ffc2..a146e5f899536 100644 --- a/library/std/src/sync/mpmc/context.rs +++ b/library/std/src/sync/mpmc/context.rs @@ -12,7 +12,7 @@ use crate::time::Instant; /// Thread-local context. #[derive(Debug, Clone)] -pub struct Context { +pub(crate) struct Context { inner: Arc, } @@ -35,7 +35,7 @@ struct Inner { impl Context { /// Creates a new context for the duration of the closure. #[inline] - pub fn with(f: F) -> R + pub(crate) fn with(f: F) -> R where F: FnOnce(&Context) -> R, { @@ -87,7 +87,7 @@ impl Context { /// /// On failure, the previously selected operation is returned. #[inline] - pub fn try_select(&self, select: Selected) -> Result<(), Selected> { + pub(crate) fn try_select(&self, select: Selected) -> Result<(), Selected> { self.inner .select .compare_exchange( @@ -104,7 +104,7 @@ impl Context { /// /// This method must be called after `try_select` succeeds and there is a packet to provide. #[inline] - pub fn store_packet(&self, packet: *mut ()) { + pub(crate) fn store_packet(&self, packet: *mut ()) { if !packet.is_null() { self.inner.packet.store(packet, Ordering::Release); } @@ -114,7 +114,7 @@ impl Context { /// /// If the deadline is reached, `Selected::Aborted` will be selected. #[inline] - pub fn wait_until(&self, deadline: Option) -> Selected { + pub(crate) fn wait_until(&self, deadline: Option) -> Selected { loop { // Check whether an operation has been selected. let sel = Selected::from(self.inner.select.load(Ordering::Acquire)); @@ -143,13 +143,13 @@ impl Context { /// Unparks the thread this context belongs to. #[inline] - pub fn unpark(&self) { + pub(crate) fn unpark(&self) { self.inner.thread.unpark(); } /// Returns the id of the thread this context belongs to. #[inline] - pub fn thread_id(&self) -> usize { + pub(crate) fn thread_id(&self) -> usize { self.inner.thread_id } } diff --git a/library/std/src/sync/mpmc/error.rs b/library/std/src/sync/mpmc/error.rs index 1b8a1f387974d..a9d5e8abb9f30 100644 --- a/library/std/src/sync/mpmc/error.rs +++ b/library/std/src/sync/mpmc/error.rs @@ -1,7 +1,9 @@ use crate::error; use crate::fmt; -pub use crate::sync::mpsc::{RecvError, RecvTimeoutError, SendError, TryRecvError, TrySendError}; +pub(crate) use crate::sync::mpsc::{ + RecvError, RecvTimeoutError, SendError, TryRecvError, TrySendError, +}; /// An error returned from the [`send_timeout`] method. /// @@ -9,7 +11,7 @@ pub use crate::sync::mpsc::{RecvError, RecvTimeoutError, SendError, TryRecvError /// /// [`send_timeout`]: super::Sender::send_timeout #[derive(PartialEq, Eq, Clone, Copy)] -pub enum SendTimeoutError { +pub(crate) enum SendTimeoutError { /// The message could not be sent because the channel is full and the operation timed out. /// /// If this is a zero-capacity channel, then the error indicates that there was no receiver diff --git a/library/std/src/sync/mpmc/mod.rs b/library/std/src/sync/mpmc/mod.rs index 7a602cecd3b89..9ebda086adfca 100644 --- a/library/std/src/sync/mpmc/mod.rs +++ b/library/std/src/sync/mpmc/mod.rs @@ -43,12 +43,12 @@ mod zero; use crate::fmt; use crate::panic::{RefUnwindSafe, UnwindSafe}; use crate::time::{Duration, Instant}; -pub use error::*; +pub(crate) use error::*; /// Creates a channel of unbounded capacity. /// /// This channel has a growable buffer that can hold any number of messages at a time. -pub fn channel() -> (Sender, Receiver) { +pub(crate) fn channel() -> (Sender, Receiver) { let (s, r) = counter::new(list::Channel::new()); let s = Sender { flavor: SenderFlavor::List(s) }; let r = Receiver { flavor: ReceiverFlavor::List(r) }; @@ -61,7 +61,7 @@ pub fn channel() -> (Sender, Receiver) { /// /// A special case is zero-capacity channel, which cannot hold any messages. Instead, send and /// receive operations must appear at the same time in order to pair up and pass the message over. -pub fn sync_channel(cap: usize) -> (Sender, Receiver) { +pub(crate) fn sync_channel(cap: usize) -> (Sender, Receiver) { if cap == 0 { let (s, r) = counter::new(zero::Channel::new()); let s = Sender { flavor: SenderFlavor::Zero(s) }; @@ -76,7 +76,7 @@ pub fn sync_channel(cap: usize) -> (Sender, Receiver) { } /// The sending side of a channel. -pub struct Sender { +pub(crate) struct Sender { flavor: SenderFlavor, } @@ -106,7 +106,7 @@ impl Sender { /// /// If called on a zero-capacity channel, this method will send the message only if there /// happens to be a receive operation on the other side of the channel at the same time. - pub fn try_send(&self, msg: T) -> Result<(), TrySendError> { + pub(crate) fn try_send(&self, msg: T) -> Result<(), TrySendError> { match &self.flavor { SenderFlavor::Array(chan) => chan.try_send(msg), SenderFlavor::List(chan) => chan.try_send(msg), @@ -122,7 +122,7 @@ impl Sender { /// /// If called on a zero-capacity channel, this method will wait for a receive operation to /// appear on the other side of the channel. - pub fn send(&self, msg: T) -> Result<(), SendError> { + pub(crate) fn send(&self, msg: T) -> Result<(), SendError> { match &self.flavor { SenderFlavor::Array(chan) => chan.send(msg, None), SenderFlavor::List(chan) => chan.send(msg, None), @@ -148,7 +148,11 @@ impl Sender { /// /// If called on a zero-capacity channel, this method will wait for a receive operation to /// appear on the other side of the channel. - pub fn send_timeout(&self, msg: T, timeout: Duration) -> Result<(), SendTimeoutError> { + pub(crate) fn send_timeout( + &self, + msg: T, + timeout: Duration, + ) -> Result<(), SendTimeoutError> { match Instant::now().checked_add(timeout) { Some(deadline) => self.send_deadline(msg, deadline), // So far in the future that it's practically the same as waiting indefinitely. @@ -164,7 +168,11 @@ impl Sender { /// /// If called on a zero-capacity channel, this method will wait for a receive operation to /// appear on the other side of the channel. - pub fn send_deadline(&self, msg: T, deadline: Instant) -> Result<(), SendTimeoutError> { + pub(crate) fn send_deadline( + &self, + msg: T, + deadline: Instant, + ) -> Result<(), SendTimeoutError> { match &self.flavor { SenderFlavor::Array(chan) => chan.send(msg, Some(deadline)), SenderFlavor::List(chan) => chan.send(msg, Some(deadline)), @@ -175,7 +183,7 @@ impl Sender { /// Returns `true` if the channel is empty. /// /// Note: Zero-capacity channels are always empty. - pub fn is_empty(&self) -> bool { + pub(crate) fn is_empty(&self) -> bool { match &self.flavor { SenderFlavor::Array(chan) => chan.is_empty(), SenderFlavor::List(chan) => chan.is_empty(), @@ -186,7 +194,7 @@ impl Sender { /// Returns `true` if the channel is full. /// /// Note: Zero-capacity channels are always full. - pub fn is_full(&self) -> bool { + pub(crate) fn is_full(&self) -> bool { match &self.flavor { SenderFlavor::Array(chan) => chan.is_full(), SenderFlavor::List(chan) => chan.is_full(), @@ -195,7 +203,7 @@ impl Sender { } /// Returns the number of messages in the channel. - pub fn len(&self) -> usize { + pub(crate) fn len(&self) -> usize { match &self.flavor { SenderFlavor::Array(chan) => chan.len(), SenderFlavor::List(chan) => chan.len(), @@ -204,7 +212,7 @@ impl Sender { } /// If the channel is bounded, returns its capacity. - pub fn capacity(&self) -> Option { + pub(crate) fn capacity(&self) -> Option { match &self.flavor { SenderFlavor::Array(chan) => chan.capacity(), SenderFlavor::List(chan) => chan.capacity(), @@ -213,7 +221,7 @@ impl Sender { } /// Returns `true` if senders belong to the same channel. - pub fn same_channel(&self, other: &Sender) -> bool { + pub(crate) fn same_channel(&self, other: &Sender) -> bool { match (&self.flavor, &other.flavor) { (SenderFlavor::Array(ref a), SenderFlavor::Array(ref b)) => a == b, (SenderFlavor::List(ref a), SenderFlavor::List(ref b)) => a == b, @@ -254,7 +262,7 @@ impl fmt::Debug for Sender { } /// The receiving side of a channel. -pub struct Receiver { +pub(crate) struct Receiver { flavor: ReceiverFlavor, } @@ -284,7 +292,7 @@ impl Receiver { /// /// If called on a zero-capacity channel, this method will receive a message only if there /// happens to be a send operation on the other side of the channel at the same time. - pub fn try_recv(&self) -> Result { + pub(crate) fn try_recv(&self) -> Result { match &self.flavor { ReceiverFlavor::Array(chan) => chan.try_recv(), ReceiverFlavor::List(chan) => chan.try_recv(), @@ -301,7 +309,7 @@ impl Receiver { /// /// If called on a zero-capacity channel, this method will wait for a send operation to appear /// on the other side of the channel. - pub fn recv(&self) -> Result { + pub(crate) fn recv(&self) -> Result { match &self.flavor { ReceiverFlavor::Array(chan) => chan.recv(None), ReceiverFlavor::List(chan) => chan.recv(None), @@ -318,7 +326,7 @@ impl Receiver { /// /// If called on a zero-capacity channel, this method will wait for a send operation to appear /// on the other side of the channel. - pub fn recv_timeout(&self, timeout: Duration) -> Result { + pub(crate) fn recv_timeout(&self, timeout: Duration) -> Result { match Instant::now().checked_add(timeout) { Some(deadline) => self.recv_deadline(deadline), // So far in the future that it's practically the same as waiting indefinitely. @@ -334,7 +342,7 @@ impl Receiver { /// /// If called on a zero-capacity channel, this method will wait for a send operation to appear /// on the other side of the channel. - pub fn recv_deadline(&self, deadline: Instant) -> Result { + pub(crate) fn recv_deadline(&self, deadline: Instant) -> Result { match &self.flavor { ReceiverFlavor::Array(chan) => chan.recv(Some(deadline)), ReceiverFlavor::List(chan) => chan.recv(Some(deadline)), @@ -351,7 +359,7 @@ impl Receiver { /// Returns `true` if the channel is empty. /// /// Note: Zero-capacity channels are always empty. - pub fn is_empty(&self) -> bool { + pub(crate) fn is_empty(&self) -> bool { match &self.flavor { ReceiverFlavor::Array(chan) => chan.is_empty(), ReceiverFlavor::List(chan) => chan.is_empty(), @@ -362,7 +370,7 @@ impl Receiver { /// Returns `true` if the channel is full. /// /// Note: Zero-capacity channels are always full. - pub fn is_full(&self) -> bool { + pub(crate) fn is_full(&self) -> bool { match &self.flavor { ReceiverFlavor::Array(chan) => chan.is_full(), ReceiverFlavor::List(chan) => chan.is_full(), @@ -371,7 +379,7 @@ impl Receiver { } /// Returns the number of messages in the channel. - pub fn len(&self) -> usize { + pub(crate) fn len(&self) -> usize { match &self.flavor { ReceiverFlavor::Array(chan) => chan.len(), ReceiverFlavor::List(chan) => chan.len(), @@ -380,7 +388,7 @@ impl Receiver { } /// If the channel is bounded, returns its capacity. - pub fn capacity(&self) -> Option { + pub(crate) fn capacity(&self) -> Option { match &self.flavor { ReceiverFlavor::Array(chan) => chan.capacity(), ReceiverFlavor::List(chan) => chan.capacity(), @@ -389,7 +397,7 @@ impl Receiver { } /// Returns `true` if receivers belong to the same channel. - pub fn same_channel(&self, other: &Receiver) -> bool { + pub(crate) fn same_channel(&self, other: &Receiver) -> bool { match (&self.flavor, &other.flavor) { (ReceiverFlavor::Array(a), ReceiverFlavor::Array(b)) => a == b, (ReceiverFlavor::List(a), ReceiverFlavor::List(b)) => a == b, diff --git a/library/std/src/sync/mpmc/select.rs b/library/std/src/sync/mpmc/select.rs index 56a83fee2e119..ef6d1b4803ff7 100644 --- a/library/std/src/sync/mpmc/select.rs +++ b/library/std/src/sync/mpmc/select.rs @@ -3,7 +3,7 @@ /// /// Each field contains data associated with a specific channel flavor. #[derive(Debug, Default)] -pub struct Token { +pub(crate) struct Token { pub(crate) array: super::array::ArrayToken, pub(crate) list: super::list::ListToken, #[allow(dead_code)] @@ -12,7 +12,7 @@ pub struct Token { /// Identifier associated with an operation by a specific thread on a specific channel. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Operation(usize); +pub(crate) struct Operation(usize); impl Operation { /// Creates an operation identifier from a mutable reference. @@ -21,7 +21,7 @@ impl Operation { /// reference should point to a variable that is specific to the thread and the operation, /// and is alive for the entire duration of a blocking operation. #[inline] - pub fn hook(r: &mut T) -> Operation { + pub(crate) fn hook(r: &mut T) -> Operation { let val = r as *mut T as usize; // Make sure that the pointer address doesn't equal the numerical representation of // `Selected::{Waiting, Aborted, Disconnected}`. @@ -32,7 +32,7 @@ impl Operation { /// Current state of a blocking operation. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Selected { +pub(crate) enum Selected { /// Still waiting for an operation. Waiting, diff --git a/library/std/src/sync/mpmc/utils.rs b/library/std/src/sync/mpmc/utils.rs index d053d69e26eee..00cc3dc9873a4 100644 --- a/library/std/src/sync/mpmc/utils.rs +++ b/library/std/src/sync/mpmc/utils.rs @@ -65,13 +65,13 @@ use crate::ops::{Deref, DerefMut}; )), repr(align(64)) )] -pub struct CachePadded { +pub(crate) struct CachePadded { value: T, } impl CachePadded { /// Pads and aligns a value to the length of a cache line. - pub fn new(value: T) -> CachePadded { + pub(crate) fn new(value: T) -> CachePadded { CachePadded:: { value } } } @@ -93,13 +93,13 @@ impl DerefMut for CachePadded { const SPIN_LIMIT: u32 = 6; /// Performs quadratic backoff in spin loops. -pub struct Backoff { +pub(crate) struct Backoff { step: Cell, } impl Backoff { /// Creates a new `Backoff`. - pub fn new() -> Self { + pub(crate) fn new() -> Self { Backoff { step: Cell::new(0) } } @@ -108,7 +108,7 @@ impl Backoff { /// This method should be used for retrying an operation because another thread made /// progress. i.e. on CAS failure. #[inline] - pub fn spin_light(&self) { + pub(crate) fn spin_light(&self) { let step = self.step.get().min(SPIN_LIMIT); for _ in 0..step.pow(2) { crate::hint::spin_loop(); @@ -121,7 +121,7 @@ impl Backoff { /// /// This method should be used in blocking loops where parking the thread is not an option. #[inline] - pub fn spin_heavy(&self) { + pub(crate) fn spin_heavy(&self) { if self.step.get() <= SPIN_LIMIT { for _ in 0..self.step.get().pow(2) { crate::hint::spin_loop() diff --git a/library/std/src/sync/mpmc/waker.rs b/library/std/src/sync/mpmc/waker.rs index 4912ca4f8150b..c57ae0c2f55ce 100644 --- a/library/std/src/sync/mpmc/waker.rs +++ b/library/std/src/sync/mpmc/waker.rs @@ -196,7 +196,7 @@ impl Drop for SyncWaker { /// Returns a unique id for the current thread. #[inline] -pub fn current_thread_id() -> usize { +pub(crate) fn current_thread_id() -> usize { // `u8` is not drop so this variable will be available during thread destruction, // whereas `thread::current()` would not be thread_local! { static DUMMY: u8 = 0 } diff --git a/library/std/src/sync/mpsc/sync_tests.rs b/library/std/src/sync/mpsc/sync_tests.rs index 9d2f92ffc9b14..171584982b909 100644 --- a/library/std/src/sync/mpsc/sync_tests.rs +++ b/library/std/src/sync/mpsc/sync_tests.rs @@ -4,7 +4,7 @@ use crate::sync::mpmc::SendTimeoutError; use crate::thread; use crate::time::Duration; -pub fn stress_factor() -> usize { +pub(crate) fn stress_factor() -> usize { match env::var("RUST_TEST_STRESS") { Ok(val) => val.parse().unwrap(), Err(..) => 1, diff --git a/library/std/src/sync/mpsc/tests.rs b/library/std/src/sync/mpsc/tests.rs index 1e52a4a705c98..7c3414928d7ed 100644 --- a/library/std/src/sync/mpsc/tests.rs +++ b/library/std/src/sync/mpsc/tests.rs @@ -3,7 +3,7 @@ use crate::env; use crate::thread; use crate::time::{Duration, Instant}; -pub fn stress_factor() -> usize { +pub(crate) fn stress_factor() -> usize { match env::var("RUST_TEST_STRESS") { Ok(val) => val.parse().unwrap(), Err(..) => 1, diff --git a/library/std/src/sync/mutex.rs b/library/std/src/sync/mutex.rs index 065045f442069..df7a7913b7790 100644 --- a/library/std/src/sync/mutex.rs +++ b/library/std/src/sync/mutex.rs @@ -541,10 +541,10 @@ impl fmt::Display for MutexGuard<'_, T> { } } -pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex { +pub(crate) fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex { &guard.lock.inner } -pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag { +pub(crate) fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag { &guard.lock.poison } diff --git a/library/std/src/sync/poison.rs b/library/std/src/sync/poison.rs index 741312d5537e9..af4deb782240e 100644 --- a/library/std/src/sync/poison.rs +++ b/library/std/src/sync/poison.rs @@ -3,7 +3,7 @@ use crate::fmt; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::thread; -pub struct Flag { +pub(crate) struct Flag { failed: AtomicBool, } @@ -20,42 +20,42 @@ pub struct Flag { impl Flag { #[inline] - pub const fn new() -> Flag { + pub(crate) const fn new() -> Flag { Flag { failed: AtomicBool::new(false) } } /// Check the flag for an unguarded borrow, where we only care about existing poison. #[inline] - pub fn borrow(&self) -> LockResult<()> { + pub(crate) fn borrow(&self) -> LockResult<()> { if self.get() { Err(PoisonError::new(())) } else { Ok(()) } } /// Check the flag for a guarded borrow, where we may also set poison when `done`. #[inline] - pub fn guard(&self) -> LockResult { + pub(crate) fn guard(&self) -> LockResult { let ret = Guard { panicking: thread::panicking() }; if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) } } #[inline] - pub fn done(&self, guard: &Guard) { + pub(crate) fn done(&self, guard: &Guard) { if !guard.panicking && thread::panicking() { self.failed.store(true, Ordering::Relaxed); } } #[inline] - pub fn get(&self) -> bool { + pub(crate) fn get(&self) -> bool { self.failed.load(Ordering::Relaxed) } #[inline] - pub fn clear(&self) { + pub(crate) fn clear(&self) { self.failed.store(false, Ordering::Relaxed) } } -pub struct Guard { +pub(crate) struct Guard { panicking: bool, } @@ -261,7 +261,7 @@ impl Error for TryLockError { } } -pub fn map_result(result: LockResult, f: F) -> LockResult +pub(crate) fn map_result(result: LockResult, f: F) -> LockResult where F: FnOnce(T) -> U, { diff --git a/library/std/src/sync/remutex.rs b/library/std/src/sync/remutex.rs index 4c054da64714c..32c69593b25e8 100644 --- a/library/std/src/sync/remutex.rs +++ b/library/std/src/sync/remutex.rs @@ -38,7 +38,7 @@ use crate::sys::locks as sys; /// since we're not dealing with multiple threads. If it compares unequal, /// synchronization is left to the mutex, making relaxed memory ordering for /// the `owner` field fine in all cases. -pub struct ReentrantMutex { +pub(crate) struct ReentrantMutex { mutex: sys::Mutex, owner: AtomicUsize, lock_count: UnsafeCell, @@ -64,7 +64,7 @@ impl RefUnwindSafe for ReentrantMutex {} /// rules. Use interior mutability (usually `RefCell`) in order to mutate the /// guarded data. #[must_use = "if unused the ReentrantMutex will immediately unlock"] -pub struct ReentrantMutexGuard<'a, T: 'a> { +pub(crate) struct ReentrantMutexGuard<'a, T: 'a> { lock: &'a ReentrantMutex, } @@ -72,7 +72,7 @@ impl !Send for ReentrantMutexGuard<'_, T> {} impl ReentrantMutex { /// Creates a new reentrant mutex in an unlocked state. - pub const fn new(t: T) -> ReentrantMutex { + pub(crate) const fn new(t: T) -> ReentrantMutex { ReentrantMutex { mutex: sys::Mutex::new(), owner: AtomicUsize::new(0), @@ -93,7 +93,7 @@ impl ReentrantMutex { /// If another user of this mutex panicked while holding the mutex, then /// this call will return failure if the mutex would otherwise be /// acquired. - pub fn lock(&self) -> ReentrantMutexGuard<'_, T> { + pub(crate) fn lock(&self) -> ReentrantMutexGuard<'_, T> { let this_thread = current_thread_unique_ptr(); // Safety: We only touch lock_count when we own the lock. unsafe { @@ -121,7 +121,7 @@ impl ReentrantMutex { /// If another user of this mutex panicked while holding the mutex, then /// this call will return failure if the mutex would otherwise be /// acquired. - pub fn try_lock(&self) -> Option> { + pub(crate) fn try_lock(&self) -> Option> { let this_thread = current_thread_unique_ptr(); // Safety: We only touch lock_count when we own the lock. unsafe { @@ -171,7 +171,7 @@ impl Drop for ReentrantMutexGuard<'_, T> { /// Get an address that is unique per running thread. /// /// This can be used as a non-null usize-sized ID. -pub fn current_thread_unique_ptr() -> usize { +pub(crate) fn current_thread_unique_ptr() -> usize { // Use a non-drop type to make sure it's still available during thread destruction. thread_local! { static X: u8 = const { 0 } } X.with(|x| <*const _>::addr(x)) diff --git a/library/std/src/sync/remutex/tests.rs b/library/std/src/sync/remutex/tests.rs index fc553081d4227..2f97f6172f077 100644 --- a/library/std/src/sync/remutex/tests.rs +++ b/library/std/src/sync/remutex/tests.rs @@ -52,7 +52,7 @@ fn trylock_works() { let _lock3 = m.try_lock(); } -pub struct Answer<'a>(pub ReentrantMutexGuard<'a, RefCell>); +pub(crate) struct Answer<'a>(pub(crate) ReentrantMutexGuard<'a, RefCell>); impl Drop for Answer<'_> { fn drop(&mut self) { *self.0.borrow_mut() = 42; diff --git a/library/std/src/sys_common/backtrace.rs b/library/std/src/sys_common/backtrace.rs index f1d804ef40c0e..2f8cfeda2bd68 100644 --- a/library/std/src/sys_common/backtrace.rs +++ b/library/std/src/sys_common/backtrace.rs @@ -12,13 +12,13 @@ use crate::sync::{Mutex, PoisonError}; /// Max number of frames to print. const MAX_NB_FRAMES: usize = 100; -pub fn lock() -> impl Drop { +pub(crate) fn lock() -> impl Drop { static LOCK: Mutex<()> = Mutex::new(()); LOCK.lock().unwrap_or_else(PoisonError::into_inner) } /// Prints the current backtrace. -pub fn print(w: &mut dyn Write, format: PrintFmt) -> io::Result<()> { +pub(crate) fn print(w: &mut dyn Write, format: PrintFmt) -> io::Result<()> { // There are issues currently linking libbacktrace into tests, and in // general during std's own unit tests we're not testing this path. In // test mode immediately return here to optimize away any references to the @@ -114,7 +114,7 @@ unsafe fn _print_fmt(fmt: &mut fmt::Formatter<'_>, print_fmt: PrintFmt) -> fmt:: /// this is only inline(never) when backtraces in std are enabled, otherwise /// it's fine to optimize away. #[cfg_attr(feature = "backtrace", inline(never))] -pub fn __rust_begin_short_backtrace(f: F) -> T +pub(crate) fn __rust_begin_short_backtrace(f: F) -> T where F: FnOnce() -> T, { @@ -130,7 +130,7 @@ where /// this is only inline(never) when backtraces in std are enabled, otherwise /// it's fine to optimize away. #[cfg_attr(feature = "backtrace", inline(never))] -pub fn __rust_end_short_backtrace(f: F) -> T +pub(crate) fn __rust_end_short_backtrace(f: F) -> T where F: FnOnce() -> T, { @@ -145,7 +145,7 @@ where /// Prints the filename of the backtrace frame. /// /// See also `output`. -pub fn output_filename( +pub(crate) fn output_filename( fmt: &mut fmt::Formatter<'_>, bows: BytesOrWideString<'_>, print_fmt: PrintFmt, diff --git a/library/std/src/sys_common/io.rs b/library/std/src/sys_common/io.rs index 4a42ff3c618ce..e08e18d32611a 100644 --- a/library/std/src/sys_common/io.rs +++ b/library/std/src/sys_common/io.rs @@ -1,6 +1,6 @@ // Bare metal platforms usually have very small amounts of RAM // (in the order of hundreds of KB) -pub const DEFAULT_BUF_SIZE: usize = if cfg!(target_os = "espidf") { 512 } else { 8 * 1024 }; +pub(crate) const DEFAULT_BUF_SIZE: usize = if cfg!(target_os = "espidf") { 512 } else { 8 * 1024 }; #[cfg(test)] #[allow(dead_code)] // not used on emscripten diff --git a/library/std/src/sys_common/lazy_box.rs b/library/std/src/sys_common/lazy_box.rs index 63c3316bdeb28..d280a64c0797d 100644 --- a/library/std/src/sys_common/lazy_box.rs +++ b/library/std/src/sys_common/lazy_box.rs @@ -40,7 +40,7 @@ pub(crate) trait LazyInit { impl LazyBox { #[inline] - pub const fn new() -> Self { + pub(crate) const fn new() -> Self { Self { ptr: AtomicPtr::new(null_mut()), _phantom: PhantomData } } diff --git a/library/std/src/sys_common/memchr.rs b/library/std/src/sys_common/memchr.rs index b219e87891264..807a35b5e88d2 100644 --- a/library/std/src/sys_common/memchr.rs +++ b/library/std/src/sys_common/memchr.rs @@ -26,7 +26,7 @@ mod tests; /// assert_eq!(memchr(b'k', haystack), Some(8)); /// ``` #[inline] -pub fn memchr(needle: u8, haystack: &[u8]) -> Option { +pub(crate) fn memchr(needle: u8, haystack: &[u8]) -> Option { sys::memchr(needle, haystack) } @@ -46,6 +46,6 @@ pub fn memchr(needle: u8, haystack: &[u8]) -> Option { /// assert_eq!(memrchr(b'o', haystack), Some(17)); /// ``` #[inline] -pub fn memrchr(needle: u8, haystack: &[u8]) -> Option { +pub(crate) fn memrchr(needle: u8, haystack: &[u8]) -> Option { sys::memrchr(needle, haystack) } diff --git a/library/std/src/sys_common/mod.rs b/library/std/src/sys_common/mod.rs index 6b24b0e9aa8be..3ff91c6aeade0 100644 --- a/library/std/src/sys_common/mod.rs +++ b/library/std/src/sys_common/mod.rs @@ -20,25 +20,25 @@ #[cfg(test)] mod tests; -pub mod backtrace; -pub mod fs; -pub mod io; -pub mod lazy_box; -pub mod memchr; -pub mod once; -pub mod process; -pub mod thread; -pub mod thread_info; -pub mod thread_local_dtor; -pub mod thread_parking; -pub mod wstr; -pub mod wtf8; +pub(crate) mod backtrace; +pub(crate) mod fs; +pub(crate) mod io; +pub(crate) mod lazy_box; +pub(crate) mod memchr; +pub(crate) mod once; +pub(crate) mod process; +pub(crate) mod thread; +pub(crate) mod thread_info; +pub(crate) mod thread_local_dtor; +pub(crate) mod thread_parking; +pub(crate) mod wstr; +pub(crate) mod wtf8; cfg_if::cfg_if! { if #[cfg(target_os = "windows")] { pub use crate::sys::thread_local_key; } else { - pub mod thread_local_key; + pub(crate) mod thread_local_key; } } @@ -50,7 +50,7 @@ cfg_if::cfg_if! { all(target_vendor = "fortanix", target_env = "sgx")))] { pub use crate::sys::net; } else { - pub mod net; + pub(crate) mod net; } } @@ -58,25 +58,25 @@ cfg_if::cfg_if! { /// A trait for viewing representations from std types #[doc(hidden)] -pub trait AsInner { +pub(crate) trait AsInner { fn as_inner(&self) -> &Inner; } /// A trait for viewing representations from std types #[doc(hidden)] -pub trait AsInnerMut { +pub(crate) trait AsInnerMut { fn as_inner_mut(&mut self) -> &mut Inner; } /// A trait for extracting representations from std types #[doc(hidden)] -pub trait IntoInner { +pub(crate) trait IntoInner { fn into_inner(self) -> Inner; } /// A trait for creating std types from internal representations #[doc(hidden)] -pub trait FromInner { +pub(crate) trait FromInner { fn from_inner(inner: Inner) -> Self; } @@ -84,7 +84,7 @@ pub trait FromInner { // (numer*denom) and the overall result fit into i64 (which is the case // for our time conversions). #[allow(dead_code)] // not used on all platforms -pub fn mul_div_u64(value: u64, numer: u64, denom: u64) -> u64 { +pub(crate) fn mul_div_u64(value: u64, numer: u64, denom: u64) -> u64 { let q = value / denom; let r = value % denom; // Decompose value as (value/denom*denom + value%denom), diff --git a/library/std/src/sys_common/net.rs b/library/std/src/sys_common/net.rs index 2c38dfecf9734..bc989fa6b2627 100644 --- a/library/std/src/sys_common/net.rs +++ b/library/std/src/sys_common/net.rs @@ -58,7 +58,7 @@ cfg_if::cfg_if! { // sockaddr and misc bindings //////////////////////////////////////////////////////////////////////////////// -pub fn setsockopt( +pub(crate) fn setsockopt( sock: &Socket, level: c_int, option_name: c_int, @@ -76,7 +76,11 @@ pub fn setsockopt( } } -pub fn getsockopt(sock: &Socket, level: c_int, option_name: c_int) -> io::Result { +pub(crate) fn getsockopt( + sock: &Socket, + level: c_int, + option_name: c_int, +) -> io::Result { unsafe { let mut option_value: T = mem::zeroed(); let mut option_len = mem::size_of::() as c::socklen_t; @@ -103,7 +107,10 @@ where } } -pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, len: usize) -> io::Result { +pub(crate) fn sockaddr_to_addr( + storage: &c::sockaddr_storage, + len: usize, +) -> io::Result { match storage.ss_family as c_int { c::AF_INET => { assert!(len as usize >= mem::size_of::()); @@ -135,14 +142,14 @@ fn to_ipv6mr_interface(value: u32) -> crate::ffi::c_uint { // get_host_addresses //////////////////////////////////////////////////////////////////////////////// -pub struct LookupHost { +pub(crate) struct LookupHost { original: *mut c::addrinfo, cur: *mut c::addrinfo, port: u16, } impl LookupHost { - pub fn port(&self) -> u16 { + pub(crate) fn port(&self) -> u16 { self.port } } @@ -214,12 +221,12 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost { // TCP streams //////////////////////////////////////////////////////////////////////////////// -pub struct TcpStream { +pub(crate) struct TcpStream { inner: Socket, } impl TcpStream { - pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result { + pub(crate) fn connect(addr: io::Result<&SocketAddr>) -> io::Result { let addr = addr?; init(); @@ -231,7 +238,7 @@ impl TcpStream { Ok(TcpStream { inner: sock }) } - pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result { + pub(crate) fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result { init(); let sock = Socket::new(addr, c::SOCK_STREAM)?; @@ -239,48 +246,48 @@ impl TcpStream { Ok(TcpStream { inner: sock }) } - pub fn socket(&self) -> &Socket { + pub(crate) fn socket(&self) -> &Socket { &self.inner } - pub fn into_socket(self) -> Socket { + pub(crate) fn into_socket(self) -> Socket { self.inner } - pub fn set_read_timeout(&self, dur: Option) -> io::Result<()> { + pub(crate) fn set_read_timeout(&self, dur: Option) -> io::Result<()> { self.inner.set_timeout(dur, c::SO_RCVTIMEO) } - pub fn set_write_timeout(&self, dur: Option) -> io::Result<()> { + pub(crate) fn set_write_timeout(&self, dur: Option) -> io::Result<()> { self.inner.set_timeout(dur, c::SO_SNDTIMEO) } - pub fn read_timeout(&self) -> io::Result> { + pub(crate) fn read_timeout(&self) -> io::Result> { self.inner.timeout(c::SO_RCVTIMEO) } - pub fn write_timeout(&self) -> io::Result> { + pub(crate) fn write_timeout(&self) -> io::Result> { self.inner.timeout(c::SO_SNDTIMEO) } - pub fn peek(&self, buf: &mut [u8]) -> io::Result { + pub(crate) fn peek(&self, buf: &mut [u8]) -> io::Result { self.inner.peek(buf) } - pub fn read(&self, buf: &mut [u8]) -> io::Result { + pub(crate) fn read(&self, buf: &mut [u8]) -> io::Result { self.inner.read(buf) } - pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { + pub(crate) fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { self.inner.read_vectored(bufs) } #[inline] - pub fn is_read_vectored(&self) -> bool { + pub(crate) fn is_read_vectored(&self) -> bool { self.inner.is_read_vectored() } - pub fn write(&self, buf: &[u8]) -> io::Result { + pub(crate) fn write(&self, buf: &[u8]) -> io::Result { let len = cmp::min(buf.len(), ::MAX as usize) as wrlen_t; let ret = cvt(unsafe { c::send(self.inner.as_raw(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL) @@ -288,61 +295,61 @@ impl TcpStream { Ok(ret as usize) } - pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { + pub(crate) fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result { self.inner.write_vectored(bufs) } #[inline] - pub fn is_write_vectored(&self) -> bool { + pub(crate) fn is_write_vectored(&self) -> bool { self.inner.is_write_vectored() } - pub fn peer_addr(&self) -> io::Result { + pub(crate) fn peer_addr(&self) -> io::Result { sockname(|buf, len| unsafe { c::getpeername(self.inner.as_raw(), buf, len) }) } - pub fn socket_addr(&self) -> io::Result { + pub(crate) fn socket_addr(&self) -> io::Result { sockname(|buf, len| unsafe { c::getsockname(self.inner.as_raw(), buf, len) }) } - pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + pub(crate) fn shutdown(&self, how: Shutdown) -> io::Result<()> { self.inner.shutdown(how) } - pub fn duplicate(&self) -> io::Result { + pub(crate) fn duplicate(&self) -> io::Result { self.inner.duplicate().map(|s| TcpStream { inner: s }) } - pub fn set_linger(&self, linger: Option) -> io::Result<()> { + pub(crate) fn set_linger(&self, linger: Option) -> io::Result<()> { self.inner.set_linger(linger) } - pub fn linger(&self) -> io::Result> { + pub(crate) fn linger(&self) -> io::Result> { self.inner.linger() } - pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + pub(crate) fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { self.inner.set_nodelay(nodelay) } - pub fn nodelay(&self) -> io::Result { + pub(crate) fn nodelay(&self) -> io::Result { self.inner.nodelay() } - pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + pub(crate) fn set_ttl(&self, ttl: u32) -> io::Result<()> { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int) } - pub fn ttl(&self) -> io::Result { + pub(crate) fn ttl(&self) -> io::Result { let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?; Ok(raw as u32) } - pub fn take_error(&self) -> io::Result> { + pub(crate) fn take_error(&self) -> io::Result> { self.inner.take_error() } - pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + pub(crate) fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { self.inner.set_nonblocking(nonblocking) } } @@ -380,12 +387,12 @@ impl fmt::Debug for TcpStream { // TCP listeners //////////////////////////////////////////////////////////////////////////////// -pub struct TcpListener { +pub(crate) struct TcpListener { inner: Socket, } impl TcpListener { - pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result { + pub(crate) fn bind(addr: io::Result<&SocketAddr>) -> io::Result { let addr = addr?; init(); @@ -423,19 +430,19 @@ impl TcpListener { Ok(TcpListener { inner: sock }) } - pub fn socket(&self) -> &Socket { + pub(crate) fn socket(&self) -> &Socket { &self.inner } - pub fn into_socket(self) -> Socket { + pub(crate) fn into_socket(self) -> Socket { self.inner } - pub fn socket_addr(&self) -> io::Result { + pub(crate) fn socket_addr(&self) -> io::Result { sockname(|buf, len| unsafe { c::getsockname(self.inner.as_raw(), buf, len) }) } - pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { + pub(crate) fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() }; let mut len = mem::size_of_val(&storage) as c::socklen_t; let sock = self.inner.accept(&mut storage as *mut _ as *mut _, &mut len)?; @@ -443,33 +450,33 @@ impl TcpListener { Ok((TcpStream { inner: sock }, addr)) } - pub fn duplicate(&self) -> io::Result { + pub(crate) fn duplicate(&self) -> io::Result { self.inner.duplicate().map(|s| TcpListener { inner: s }) } - pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + pub(crate) fn set_ttl(&self, ttl: u32) -> io::Result<()> { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int) } - pub fn ttl(&self) -> io::Result { + pub(crate) fn ttl(&self) -> io::Result { let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?; Ok(raw as u32) } - pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + pub(crate) fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int) } - pub fn only_v6(&self) -> io::Result { + pub(crate) fn only_v6(&self) -> io::Result { let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY)?; Ok(raw != 0) } - pub fn take_error(&self) -> io::Result> { + pub(crate) fn take_error(&self) -> io::Result> { self.inner.take_error() } - pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + pub(crate) fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { self.inner.set_nonblocking(nonblocking) } } @@ -497,12 +504,12 @@ impl fmt::Debug for TcpListener { // UDP //////////////////////////////////////////////////////////////////////////////// -pub struct UdpSocket { +pub(crate) struct UdpSocket { inner: Socket, } impl UdpSocket { - pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result { + pub(crate) fn bind(addr: io::Result<&SocketAddr>) -> io::Result { let addr = addr?; init(); @@ -513,31 +520,31 @@ impl UdpSocket { Ok(UdpSocket { inner: sock }) } - pub fn socket(&self) -> &Socket { + pub(crate) fn socket(&self) -> &Socket { &self.inner } - pub fn into_socket(self) -> Socket { + pub(crate) fn into_socket(self) -> Socket { self.inner } - pub fn peer_addr(&self) -> io::Result { + pub(crate) fn peer_addr(&self) -> io::Result { sockname(|buf, len| unsafe { c::getpeername(self.inner.as_raw(), buf, len) }) } - pub fn socket_addr(&self) -> io::Result { + pub(crate) fn socket_addr(&self) -> io::Result { sockname(|buf, len| unsafe { c::getsockname(self.inner.as_raw(), buf, len) }) } - pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + pub(crate) fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { self.inner.recv_from(buf) } - pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + pub(crate) fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { self.inner.peek_from(buf) } - pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result { + pub(crate) fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result { let len = cmp::min(buf.len(), ::MAX as usize) as wrlen_t; let (dst, dstlen) = dst.into_inner(); let ret = cvt(unsafe { @@ -553,36 +560,36 @@ impl UdpSocket { Ok(ret as usize) } - pub fn duplicate(&self) -> io::Result { + pub(crate) fn duplicate(&self) -> io::Result { self.inner.duplicate().map(|s| UdpSocket { inner: s }) } - pub fn set_read_timeout(&self, dur: Option) -> io::Result<()> { + pub(crate) fn set_read_timeout(&self, dur: Option) -> io::Result<()> { self.inner.set_timeout(dur, c::SO_RCVTIMEO) } - pub fn set_write_timeout(&self, dur: Option) -> io::Result<()> { + pub(crate) fn set_write_timeout(&self, dur: Option) -> io::Result<()> { self.inner.set_timeout(dur, c::SO_SNDTIMEO) } - pub fn read_timeout(&self) -> io::Result> { + pub(crate) fn read_timeout(&self) -> io::Result> { self.inner.timeout(c::SO_RCVTIMEO) } - pub fn write_timeout(&self) -> io::Result> { + pub(crate) fn write_timeout(&self) -> io::Result> { self.inner.timeout(c::SO_SNDTIMEO) } - pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { + pub(crate) fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { setsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST, broadcast as c_int) } - pub fn broadcast(&self) -> io::Result { + pub(crate) fn broadcast(&self) -> io::Result { let raw: c_int = getsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST)?; Ok(raw != 0) } - pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { + pub(crate) fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { setsockopt( &self.inner, c::IPPROTO_IP, @@ -591,12 +598,12 @@ impl UdpSocket { ) } - pub fn multicast_loop_v4(&self) -> io::Result { + pub(crate) fn multicast_loop_v4(&self) -> io::Result { let raw: IpV4MultiCastType = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP)?; Ok(raw != 0) } - pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { + pub(crate) fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { setsockopt( &self.inner, c::IPPROTO_IP, @@ -605,21 +612,25 @@ impl UdpSocket { ) } - pub fn multicast_ttl_v4(&self) -> io::Result { + pub(crate) fn multicast_ttl_v4(&self) -> io::Result { let raw: IpV4MultiCastType = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL)?; Ok(raw as u32) } - pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { + pub(crate) fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP, multicast_loop_v6 as c_int) } - pub fn multicast_loop_v6(&self) -> io::Result { + pub(crate) fn multicast_loop_v6(&self) -> io::Result { let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP)?; Ok(raw != 0) } - pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + pub(crate) fn join_multicast_v4( + &self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr, + ) -> io::Result<()> { let mreq = c::ip_mreq { imr_multiaddr: multiaddr.into_inner(), imr_interface: interface.into_inner(), @@ -627,7 +638,7 @@ impl UdpSocket { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq) } - pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + pub(crate) fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { let mreq = c::ipv6_mreq { ipv6mr_multiaddr: multiaddr.into_inner(), ipv6mr_interface: to_ipv6mr_interface(interface), @@ -635,7 +646,11 @@ impl UdpSocket { setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq) } - pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + pub(crate) fn leave_multicast_v4( + &self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr, + ) -> io::Result<()> { let mreq = c::ip_mreq { imr_multiaddr: multiaddr.into_inner(), imr_interface: interface.into_inner(), @@ -643,7 +658,11 @@ impl UdpSocket { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq) } - pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + pub(crate) fn leave_multicast_v6( + &self, + multiaddr: &Ipv6Addr, + interface: u32, + ) -> io::Result<()> { let mreq = c::ipv6_mreq { ipv6mr_multiaddr: multiaddr.into_inner(), ipv6mr_interface: to_ipv6mr_interface(interface), @@ -651,32 +670,32 @@ impl UdpSocket { setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq) } - pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + pub(crate) fn set_ttl(&self, ttl: u32) -> io::Result<()> { setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int) } - pub fn ttl(&self) -> io::Result { + pub(crate) fn ttl(&self) -> io::Result { let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?; Ok(raw as u32) } - pub fn take_error(&self) -> io::Result> { + pub(crate) fn take_error(&self) -> io::Result> { self.inner.take_error() } - pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + pub(crate) fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { self.inner.set_nonblocking(nonblocking) } - pub fn recv(&self, buf: &mut [u8]) -> io::Result { + pub(crate) fn recv(&self, buf: &mut [u8]) -> io::Result { self.inner.read(buf) } - pub fn peek(&self, buf: &mut [u8]) -> io::Result { + pub(crate) fn peek(&self, buf: &mut [u8]) -> io::Result { self.inner.peek(buf) } - pub fn send(&self, buf: &[u8]) -> io::Result { + pub(crate) fn send(&self, buf: &[u8]) -> io::Result { let len = cmp::min(buf.len(), ::MAX as usize) as wrlen_t; let ret = cvt(unsafe { c::send(self.inner.as_raw(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL) @@ -684,7 +703,7 @@ impl UdpSocket { Ok(ret as usize) } - pub fn connect(&self, addr: io::Result<&SocketAddr>) -> io::Result<()> { + pub(crate) fn connect(&self, addr: io::Result<&SocketAddr>) -> io::Result<()> { let (addr, len) = addr?.into_inner(); cvt_r(|| unsafe { c::connect(self.inner.as_raw(), addr.as_ptr(), len) }).map(drop) } @@ -724,7 +743,7 @@ pub(crate) union SocketAddrCRepr { } impl SocketAddrCRepr { - pub fn as_ptr(&self) -> *const c::sockaddr { + pub(crate) fn as_ptr(&self) -> *const c::sockaddr { self as *const _ as *const c::sockaddr } } diff --git a/library/std/src/sys_common/once/futex.rs b/library/std/src/sys_common/once/futex.rs index 42db5fad4b451..914c3ae3a7f50 100644 --- a/library/std/src/sys_common/once/futex.rs +++ b/library/std/src/sys_common/once/futex.rs @@ -29,19 +29,19 @@ const COMPLETE: u32 = 4; // variable. When the running thread finishes, it will wake all waiting threads using // `futex_wake_all`. -pub struct OnceState { +pub(crate) struct OnceState { poisoned: bool, set_state_to: Cell, } impl OnceState { #[inline] - pub fn is_poisoned(&self) -> bool { + pub(crate) fn is_poisoned(&self) -> bool { self.poisoned } #[inline] - pub fn poison(&self) { + pub(crate) fn poison(&self) { self.set_state_to.set(POISONED); } } @@ -62,18 +62,18 @@ impl<'a> Drop for CompletionGuard<'a> { } } -pub struct Once { +pub(crate) struct Once { state: AtomicU32, } impl Once { #[inline] - pub const fn new() -> Once { + pub(crate) const fn new() -> Once { Once { state: AtomicU32::new(INCOMPLETE) } } #[inline] - pub fn is_completed(&self) -> bool { + pub(crate) fn is_completed(&self) -> bool { // Use acquire ordering to make all initialization changes visible to the // current thread. self.state.load(Acquire) == COMPLETE @@ -94,7 +94,7 @@ impl Once { // so avoids the cost of dynamic dispatch. #[cold] #[track_caller] - pub fn call(&self, ignore_poisoning: bool, f: &mut impl FnMut(&public::OnceState)) { + pub(crate) fn call(&self, ignore_poisoning: bool, f: &mut impl FnMut(&public::OnceState)) { let mut state = self.state.load(Acquire); loop { match state { diff --git a/library/std/src/sys_common/once/mod.rs b/library/std/src/sys_common/once/mod.rs index 359697d831317..b9cff4725f68d 100644 --- a/library/std/src/sys_common/once/mod.rs +++ b/library/std/src/sys_common/once/mod.rs @@ -19,7 +19,7 @@ cfg_if::cfg_if! { target_os = "hermit", ))] { mod futex; - pub use futex::{Once, OnceState}; + pub(crate) use futex::{Once, OnceState}; } else if #[cfg(any( windows, target_family = "unix", diff --git a/library/std/src/sys_common/process.rs b/library/std/src/sys_common/process.rs index 18883048daef1..7378d456736f8 100644 --- a/library/std/src/sys_common/process.rs +++ b/library/std/src/sys_common/process.rs @@ -1,4 +1,4 @@ -#![allow(dead_code)] +#![allow(dead_code)] // not used on all platforms #![unstable(feature = "process_internals", issue = "none")] use crate::collections::BTreeMap; diff --git a/library/std/src/sys_common/thread.rs b/library/std/src/sys_common/thread.rs index 76466b2b37beb..bc456ab6125b3 100644 --- a/library/std/src/sys_common/thread.rs +++ b/library/std/src/sys_common/thread.rs @@ -2,7 +2,7 @@ use crate::env; use crate::sync::atomic::{self, Ordering}; use crate::sys::thread as imp; -pub fn min_stack() -> usize { +pub(crate) fn min_stack() -> usize { static MIN: atomic::AtomicUsize = atomic::AtomicUsize::new(0); match MIN.load(Ordering::Relaxed) { 0 => {} diff --git a/library/std/src/sys_common/thread_info.rs b/library/std/src/sys_common/thread_info.rs index 38c9e50009af5..d16af09af2fa3 100644 --- a/library/std/src/sys_common/thread_info.rs +++ b/library/std/src/sys_common/thread_info.rs @@ -30,15 +30,15 @@ impl ThreadInfo { } } -pub fn current_thread() -> Option { +pub(crate) fn current_thread() -> Option { ThreadInfo::with(|info| info.thread.clone()) } -pub fn stack_guard() -> Option { +pub(crate) fn stack_guard() -> Option { ThreadInfo::with(|info| info.stack_guard.clone()).and_then(|o| o) } -pub fn set(stack_guard: Option, thread: Thread) { +pub(crate) fn set(stack_guard: Option, thread: Thread) { THREAD_INFO.with(move |thread_info| { let mut thread_info = thread_info.borrow_mut(); rtassert!(thread_info.is_none()); diff --git a/library/std/src/sys_common/thread_local_dtor.rs b/library/std/src/sys_common/thread_local_dtor.rs index 844946eda031f..75d9d1180bb01 100644 --- a/library/std/src/sys_common/thread_local_dtor.rs +++ b/library/std/src/sys_common/thread_local_dtor.rs @@ -16,7 +16,7 @@ use crate::ptr; use crate::sys_common::thread_local_key::StaticKey; -pub unsafe fn register_dtor_fallback(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { +pub(crate) unsafe fn register_dtor_fallback(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { // The fallback implementation uses a vanilla OS-based TLS key to track // the list of destructors that need to be run for this thread. The key // then has its own destructor which runs all the other destructors. diff --git a/library/std/src/sys_common/thread_local_key.rs b/library/std/src/sys_common/thread_local_key.rs index 2672a2a75b017..05c329c24320a 100644 --- a/library/std/src/sys_common/thread_local_key.rs +++ b/library/std/src/sys_common/thread_local_key.rs @@ -77,7 +77,7 @@ use crate::sys::thread_local_key as imp; /// KEY.set(1 as *mut u8); /// } /// ``` -pub struct StaticKey { +pub(crate) struct StaticKey { /// Inner static TLS key (internals). key: AtomicUsize, /// Destructor for the TLS value. @@ -108,14 +108,14 @@ pub struct StaticKey { /// /// drop(key); // deallocate this TLS slot. /// ``` -pub struct Key { +pub(crate) struct Key { key: imp::Key, } /// Constant initialization value for static TLS keys. /// /// This value specifies no destructor by default. -pub const INIT: StaticKey = StaticKey::new(None); +pub(crate) const INIT: StaticKey = StaticKey::new(None); // Define a sentinel value that is unlikely to be returned // as a TLS key (but it may be returned). @@ -123,7 +123,7 @@ const KEY_SENTVAL: usize = 0; impl StaticKey { #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")] - pub const fn new(dtor: Option) -> StaticKey { + pub(crate) const fn new(dtor: Option) -> StaticKey { StaticKey { key: atomic::AtomicUsize::new(KEY_SENTVAL), dtor } } @@ -132,7 +132,7 @@ impl StaticKey { /// This will lazily allocate a TLS key from the OS if one has not already /// been allocated. #[inline] - pub unsafe fn get(&self) -> *mut u8 { + pub(crate) unsafe fn get(&self) -> *mut u8 { imp::get(self.key()) } @@ -141,7 +141,7 @@ impl StaticKey { /// This will lazily allocate a TLS key from the OS if one has not already /// been allocated. #[inline] - pub unsafe fn set(&self, val: *mut u8) { + pub(crate) unsafe fn set(&self, val: *mut u8) { imp::set(self.key(), val) } @@ -202,19 +202,19 @@ impl Key { /// Note that the destructor will not be run when the `Key` goes out of /// scope. #[inline] - pub fn new(dtor: Option) -> Key { + pub(crate) fn new(dtor: Option) -> Key { Key { key: unsafe { imp::create(dtor) } } } /// See StaticKey::get #[inline] - pub fn get(&self) -> *mut u8 { + pub(crate) fn get(&self) -> *mut u8 { unsafe { imp::get(self.key) } } /// See StaticKey::set #[inline] - pub fn set(&self, val: *mut u8) { + pub(crate) fn set(&self, val: *mut u8) { unsafe { imp::set(self.key, val) } } } diff --git a/library/std/src/sys_common/thread_parking/futex.rs b/library/std/src/sys_common/thread_parking/futex.rs index 588e7b27826f6..633c6b080a8a5 100644 --- a/library/std/src/sys_common/thread_parking/futex.rs +++ b/library/std/src/sys_common/thread_parking/futex.rs @@ -8,7 +8,7 @@ const PARKED: u32 = u32::MAX; const EMPTY: u32 = 0; const NOTIFIED: u32 = 1; -pub struct Parker { +pub(crate) struct Parker { state: AtomicU32, } @@ -35,13 +35,13 @@ pub struct Parker { impl Parker { /// Construct the futex parker. The UNIX parker implementation /// requires this to happen in-place. - pub unsafe fn new_in_place(parker: *mut Parker) { + pub(crate) unsafe fn new_in_place(parker: *mut Parker) { parker.write(Self { state: AtomicU32::new(EMPTY) }); } // Assumes this is only called by the thread that owns the Parker, // which means that `self.state != PARKED`. - pub unsafe fn park(self: Pin<&Self>) { + pub(crate) unsafe fn park(self: Pin<&Self>) { // Change NOTIFIED=>EMPTY or EMPTY=>PARKED, and directly return in the // first case. if self.state.fetch_sub(1, Acquire) == NOTIFIED { @@ -62,7 +62,7 @@ impl Parker { // Assumes this is only called by the thread that owns the Parker, // which means that `self.state != PARKED`. This implementation doesn't // require `Pin`, but other implementations do. - pub unsafe fn park_timeout(self: Pin<&Self>, timeout: Duration) { + pub(crate) unsafe fn park_timeout(self: Pin<&Self>, timeout: Duration) { // Change NOTIFIED=>EMPTY or EMPTY=>PARKED, and directly return in the // first case. if self.state.fetch_sub(1, Acquire) == NOTIFIED { @@ -83,7 +83,7 @@ impl Parker { // This implementation doesn't require `Pin`, but other implementations do. #[inline] - pub fn unpark(self: Pin<&Self>) { + pub(crate) fn unpark(self: Pin<&Self>) { // Change PARKED=>NOTIFIED, EMPTY=>NOTIFIED, or NOTIFIED=>NOTIFIED, and // wake the thread in the first case. // diff --git a/library/std/src/sys_common/thread_parking/mod.rs b/library/std/src/sys_common/thread_parking/mod.rs index e8e028bb3308f..9c190e8ad6f9f 100644 --- a/library/std/src/sys_common/thread_parking/mod.rs +++ b/library/std/src/sys_common/thread_parking/mod.rs @@ -10,7 +10,7 @@ cfg_if::cfg_if! { target_os = "hermit", ))] { mod futex; - pub use futex::Parker; + pub(crate) use futex::Parker; } else if #[cfg(any( target_os = "netbsd", all(target_vendor = "fortanix", target_env = "sgx"), diff --git a/library/std/src/sys_common/wstr.rs b/library/std/src/sys_common/wstr.rs index b230fd1a829f7..a3bcac3145f34 100644 --- a/library/std/src/sys_common/wstr.rs +++ b/library/std/src/sys_common/wstr.rs @@ -7,7 +7,7 @@ use crate::ptr::NonNull; /// A safe iterator over a LPWSTR /// (aka a pointer to a series of UTF-16 code units terminated by a NULL). -pub struct WStrUnits<'a> { +pub(crate) struct WStrUnits<'a> { // The pointer must never be null... lpwstr: NonNull, // ...and the memory it points to must be valid for this lifetime. @@ -19,11 +19,11 @@ impl WStrUnits<'_> { /// /// SAFETY: `lpwstr` must point to a null-terminated wide string that lives /// at least as long as the lifetime of this struct. - pub unsafe fn new(lpwstr: *const u16) -> Option { + pub(crate) unsafe fn new(lpwstr: *const u16) -> Option { Some(Self { lpwstr: NonNull::new(lpwstr as _)?, lifetime: PhantomData }) } - pub fn peek(&self) -> Option { + pub(crate) fn peek(&self) -> Option { // SAFETY: It's always safe to read the current item because we don't // ever move out of the array's bounds. unsafe { NonZeroU16::new(*self.lpwstr.as_ptr()) } @@ -31,7 +31,10 @@ impl WStrUnits<'_> { /// Advance the iterator while `predicate` returns true. /// Returns the number of items it advanced by. - pub fn advance_while bool>(&mut self, mut predicate: P) -> usize { + pub(crate) fn advance_while bool>( + &mut self, + mut predicate: P, + ) -> usize { let mut counter = 0; while let Some(w) = self.peek() { if !predicate(w) { diff --git a/library/std/src/thread/local.rs b/library/std/src/thread/local.rs index cf7c2e05a2e9d..4c1d2fa0eab58 100644 --- a/library/std/src/thread/local.rs +++ b/library/std/src/thread/local.rs @@ -785,16 +785,16 @@ mod lazy { use crate::hint; use crate::mem; - pub struct LazyKeyInner { + pub(crate) struct LazyKeyInner { inner: UnsafeCell>, } impl LazyKeyInner { - pub const fn new() -> LazyKeyInner { + pub(crate) const fn new() -> LazyKeyInner { LazyKeyInner { inner: UnsafeCell::new(None) } } - pub unsafe fn get(&self) -> Option<&'static T> { + pub(crate) unsafe fn get(&self) -> Option<&'static T> { // SAFETY: The caller must ensure no reference is ever handed out to // the inner cell nor mutable reference to the Option inside said // cell. This make it safe to hand a reference, though the lifetime @@ -804,7 +804,7 @@ mod lazy { /// The caller must ensure that no reference is active: this method /// needs unique access. - pub unsafe fn initialize T>(&self, init: F) -> &'static T { + pub(crate) unsafe fn initialize T>(&self, init: F) -> &'static T { // Execute the initialization up front, *then* move it into our slot, // just in case initialization fails. let value = init(); @@ -851,7 +851,7 @@ mod lazy { /// As such, callers of this method must ensure no `&` and `&mut` are /// available and used at the same time. #[allow(unused)] - pub unsafe fn take(&mut self) -> Option { + pub(crate) unsafe fn take(&mut self) -> Option { // SAFETY: See doc comment for this method. unsafe { (*self.inner.get()).take() } } @@ -902,7 +902,7 @@ pub mod statik { #[doc(hidden)] #[cfg(all(target_thread_local, not(all(target_family = "wasm", not(target_feature = "atomics"))),))] -pub mod fast { +pub(crate) mod fast { use super::lazy::LazyKeyInner; use crate::cell::Cell; use crate::sys::thread_local_dtor::register_dtor; @@ -1045,7 +1045,7 @@ pub mod fast { not(target_thread_local), not(all(target_family = "wasm", not(target_feature = "atomics"))), ))] -pub mod os { +pub(crate) mod os { use super::lazy::LazyKeyInner; use crate::cell::Cell; use crate::sys_common::thread_local_key::StaticKey as OsStaticKey;