Skip to content
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
4 changes: 1 addition & 3 deletions library/core/src/array/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,14 @@ pub use iter::IntoIter;
///
/// Creating multiple copies of a `String`:
/// ```rust
/// #![feature(array_repeat)]
///
/// use std::array;
///
/// let string = "Hello there!".to_string();
/// let strings = array::repeat(string);
/// assert_eq!(strings, ["Hello there!", "Hello there!"]);
/// ```
#[inline]
#[unstable(feature = "array_repeat", issue = "126695")]
#[stable(feature = "array_repeat", since = "CURRENT_RUSTC_VERSION")]
pub fn repeat<T: Clone, const N: usize>(val: T) -> [T; N] {
from_trusted_iterator(repeat_n(val, N))
}
Expand Down
14 changes: 14 additions & 0 deletions library/core/src/num/uint_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1491,6 +1491,20 @@ macro_rules! uint_impl {
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
// Inform compiler of optimizations when the base is known at
// compile time and there's a cheaper method available.
//
// Note: Like all optimizations, this is not guaranteed to be
// applied by the compiler. If you want those specific bases,
// use `.checked_ilog2()` or `.checked_ilog10()` directly.
if core::intrinsics::is_val_statically_known(base) {
if base == 2 {
return self.checked_ilog2();
} else if base == 10 {
return self.checked_ilog10();
}
}

if self <= 0 || base <= 1 {
None
} else if self < base {
Expand Down
36 changes: 36 additions & 0 deletions library/core/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,42 @@ impl Duration {
Duration { secs, nanos: subsec_nanos }
}

/// Creates a new `Duration` from the specified number of nanoseconds.
///
/// # Panics
///
/// Panics if the given number of nanoseconds is greater than [`Duration::MAX`].
///
/// # Examples
///
/// ```
/// #![feature(duration_from_nanos_u128)]
/// use std::time::Duration;
///
/// let nanos = 10_u128.pow(24) + 321;
/// let duration = Duration::from_nanos_u128(nanos);
///
/// assert_eq!(10_u64.pow(15), duration.as_secs());
/// assert_eq!(321, duration.subsec_nanos());
/// ```
#[unstable(feature = "duration_from_nanos_u128", issue = "139201")]
// This is necessary because of const `try_from`, but can be removed if a trait-free impl is used instead
#[rustc_const_unstable(feature = "duration_from_nanos_u128", issue = "139201")]
#[must_use]
#[inline]
#[track_caller]
pub const fn from_nanos_u128(nanos: u128) -> Duration {
const NANOS_PER_SEC: u128 = self::NANOS_PER_SEC as u128;
let Ok(secs) = u64::try_from(nanos / NANOS_PER_SEC) else {
panic!("overflow in `Duration::from_nanos_u128`");
};
let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
// SAFETY: x % 1_000_000_000 < 1_000_000_000 also, subsec_nanos >= 0 since u128 >=0 and u32 >=0
let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) };

Duration { secs: secs as u64, nanos: subsec_nanos }
}

/// Creates a new `Duration` from the specified number of weeks.
///
/// # Panics
Expand Down
1 change: 1 addition & 0 deletions library/coretests/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
#![feature(drop_guard)]
#![feature(duration_constants)]
#![feature(duration_constructors)]
#![feature(duration_from_nanos_u128)]
#![feature(error_generic_member_access)]
#![feature(exact_div)]
#![feature(exact_size_is_empty)]
Expand Down
19 changes: 19 additions & 0 deletions library/coretests/tests/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ fn from_weeks_overflow() {
let _ = Duration::from_weeks(overflow);
}

#[test]
#[should_panic]
fn from_nanos_u128_overflow() {
let nanos_per_sec: u128 = 1_000_000_000;
let overflow = (u64::MAX as u128 * nanos_per_sec) + (nanos_per_sec - 1) + 1;
let _ = Duration::from_nanos_u128(overflow);
}

#[test]
fn constructor_weeks() {
assert_eq!(Duration::from_weeks(1), Duration::from_secs(7 * 24 * 60 * 60));
Expand Down Expand Up @@ -81,6 +89,8 @@ fn secs() {
assert_eq!(Duration::from_micros(1_000_001).as_secs(), 1);
assert_eq!(Duration::from_nanos(999_999_999).as_secs(), 0);
assert_eq!(Duration::from_nanos(1_000_000_001).as_secs(), 1);
assert_eq!(Duration::from_nanos_u128(999_999_999).as_secs(), 0);
assert_eq!(Duration::from_nanos_u128(1_000_000_001).as_secs(), 1);
}

#[test]
Expand All @@ -95,6 +105,8 @@ fn millis() {
assert_eq!(Duration::from_micros(1_001_000).subsec_millis(), 1);
assert_eq!(Duration::from_nanos(999_999_999).subsec_millis(), 999);
assert_eq!(Duration::from_nanos(1_001_000_000).subsec_millis(), 1);
assert_eq!(Duration::from_nanos_u128(999_999_999).subsec_millis(), 999);
assert_eq!(Duration::from_nanos_u128(1_001_000_001).subsec_millis(), 1);
}

#[test]
Expand All @@ -109,6 +121,8 @@ fn micros() {
assert_eq!(Duration::from_micros(1_000_001).subsec_micros(), 1);
assert_eq!(Duration::from_nanos(999_999_999).subsec_micros(), 999_999);
assert_eq!(Duration::from_nanos(1_000_001_000).subsec_micros(), 1);
assert_eq!(Duration::from_nanos_u128(999_999_999).subsec_micros(), 999_999);
assert_eq!(Duration::from_nanos_u128(1_000_001_000).subsec_micros(), 1);
}

#[test]
Expand All @@ -123,6 +137,8 @@ fn nanos() {
assert_eq!(Duration::from_micros(1_000_001).subsec_nanos(), 1000);
assert_eq!(Duration::from_nanos(999_999_999).subsec_nanos(), 999_999_999);
assert_eq!(Duration::from_nanos(1_000_000_001).subsec_nanos(), 1);
assert_eq!(Duration::from_nanos_u128(999_999_999).subsec_nanos(), 999_999_999);
assert_eq!(Duration::from_nanos_u128(1_000_000_001).subsec_nanos(), 1);
}

#[test]
Expand Down Expand Up @@ -520,6 +536,9 @@ fn duration_const() {
const FROM_NANOS: Duration = Duration::from_nanos(1_000_000_000);
assert_eq!(FROM_NANOS, Duration::SECOND);

const FROM_NANOS_U128: Duration = Duration::from_nanos_u128(NANOS);
assert_eq!(FROM_NANOS_U128, Duration::SECOND);

const MAX: Duration = Duration::new(u64::MAX, 999_999_999);

const CHECKED_ADD: Option<Duration> = MAX.checked_add(Duration::SECOND);
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ pub struct DirBuilder {
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
fn inner(path: &Path) -> io::Result<Vec<u8>> {
let mut file = File::open(path)?;
let size = file.metadata().map(|m| m.len() as usize).ok();
let size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok();
let mut bytes = Vec::try_with_capacity(size.unwrap_or(0))?;
io::default_read_to_end(&mut file, &mut bytes, size)?;
Ok(bytes)
Expand Down Expand Up @@ -346,7 +346,7 @@ pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
fn inner(path: &Path) -> io::Result<String> {
let mut file = File::open(path)?;
let size = file.metadata().map(|m| m.len() as usize).ok();
let size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok();
let mut string = String::new();
string.try_reserve_exact(size.unwrap_or(0))?;
io::default_read_to_string(&mut file, &mut string, size)?;
Expand Down
8 changes: 3 additions & 5 deletions library/std/src/sync/barrier.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::fmt;
// FIXME(nonpoison_mutex,nonpoison_condvar): switch to nonpoison versions once they are available
use crate::sync::{Condvar, Mutex};
use crate::sync::nonpoison::{Condvar, Mutex};

/// A barrier enables multiple threads to synchronize the beginning
/// of some computation.
Expand Down Expand Up @@ -118,12 +117,11 @@ impl Barrier {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn wait(&self) -> BarrierWaitResult {
let mut lock = self.lock.lock().unwrap();
let mut lock = self.lock.lock();
let local_gen = lock.generation_id;
lock.count += 1;
if lock.count < self.num_threads {
let _guard =
self.cvar.wait_while(lock, |state| local_gen == state.generation_id).unwrap();
let _guard = self.cvar.wait_while(lock, |state| local_gen == state.generation_id);
BarrierWaitResult(false)
} else {
lock.count = 0;
Expand Down
65 changes: 64 additions & 1 deletion library/std/src/sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ pub use self::poison::{LockResult, PoisonError};
#[doc(inline)]
pub use self::poison::{
Mutex, MutexGuard, TryLockError, TryLockResult,
Condvar, WaitTimeoutResult,
Condvar,
Once, OnceState,
RwLock, RwLockReadGuard, RwLockWriteGuard,
};
Expand All @@ -234,3 +234,66 @@ mod barrier;
mod lazy_lock;
mod once_lock;
mod reentrant_lock;

/// A type indicating whether a timed wait on a condition variable returned
/// due to a time out or not.
///
/// It is returned by the [`wait_timeout`] method.
///
/// [`wait_timeout`]: Condvar::wait_timeout
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[stable(feature = "wait_timeout", since = "1.5.0")]
pub struct WaitTimeoutResult(bool);

impl WaitTimeoutResult {
/// Returns `true` if the wait was known to have timed out.
///
/// # Examples
///
/// This example spawns a thread which will sleep 20 milliseconds before
/// updating a boolean value and then notifying the condvar.
///
/// The main thread will wait with a 10 millisecond timeout on the condvar
/// and will leave the loop upon timeout.
///
/// ```
/// use std::sync::{Arc, Condvar, Mutex};
/// use std::thread;
/// use std::time::Duration;
///
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
/// let pair2 = Arc::clone(&pair);
///
/// # let handle =
/// thread::spawn(move || {
/// let (lock, cvar) = &*pair2;
///
/// // Let's wait 20 milliseconds before notifying the condvar.
/// thread::sleep(Duration::from_millis(20));
///
/// let mut started = lock.lock().unwrap();
/// // We update the boolean value.
/// *started = true;
/// cvar.notify_one();
/// });
///
/// // Wait for the thread to start up.
/// let (lock, cvar) = &*pair;
/// loop {
/// // Let's put a timeout on the condvar's wait.
/// let result = cvar.wait_timeout(lock.lock().unwrap(), Duration::from_millis(10)).unwrap();
/// // 10 milliseconds have passed.
/// if result.1.timed_out() {
/// // timed out now and we can leave.
/// break
/// }
/// }
/// # // Prevent leaks for Miri.
/// # let _ = handle.join();
/// ```
#[must_use]
#[stable(feature = "wait_timeout", since = "1.5.0")]
pub fn timed_out(&self) -> bool {
self.0
}
}
3 changes: 3 additions & 0 deletions library/std/src/sync/nonpoison.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ impl fmt::Display for WouldBlock {
}
}

#[unstable(feature = "nonpoison_condvar", issue = "134645")]
pub use self::condvar::Condvar;
#[unstable(feature = "mapped_lock_guards", issue = "117108")]
pub use self::mutex::MappedMutexGuard;
#[unstable(feature = "nonpoison_mutex", issue = "134645")]
Expand All @@ -38,5 +40,6 @@ pub use self::rwlock::{MappedRwLockReadGuard, MappedRwLockWriteGuard};
#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
pub use self::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};

mod condvar;
mod mutex;
mod rwlock;
Loading
Loading