From 95c4899e55e7aab68f06e67660257d73e6a46eda Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 7 Jun 2020 23:36:07 +0200 Subject: Added an example where explicitly dropping a lock is necessary/a good idea. --- src/libstd/sync/mutex.rs | 61 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) (limited to 'src/libstd') diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 797b22fdd12..6077e1a4029 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -107,6 +107,67 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// /// *guard += 1; /// ``` +/// +/// It is sometimes a good idea (or even necessary) to manually drop the mutex +/// to unlock it as soon as possible. If you need the resource until the end of +/// the scope, this is not needed. +/// +/// ``` +/// use std::sync::{Arc, Mutex}; +/// use std::thread; +/// +/// const N: usize = 3; +/// +/// // Some data to work with in multiple threads. +/// let data_mutex = Arc::new(Mutex::new([1, 2, 3, 4])); +/// // The result of all the work across all threads. +/// let res_mutex = Arc::new(Mutex::new(0)); +/// +/// // Threads other than the main thread. +/// let mut threads = Vec::with_capacity(N); +/// (0..N).for_each(|_| { +/// // Getting clones for the mutexes. +/// let data_mutex_clone = Arc::clone(&data_mutex); +/// let res_mutex_clone = Arc::clone(&res_mutex); +/// +/// threads.push(thread::spawn(move || { +/// let data = *data_mutex_clone.lock().unwrap(); +/// // This is the result of some important and long-ish work. +/// let result = data.iter().fold(0, |acc, x| acc + x * 2); +/// // We drop the `data` explicitely because it's not necessary anymore +/// // and the thread still has work to do. This allow other threads to +/// // start working on the data immediately, without waiting +/// // for the rest of the unrelated work to be done here. +/// std::mem::drop(data); +/// *res_mutex_clone.lock().unwrap() += result; +/// })); +/// }); +/// +/// let data = *data_mutex.lock().unwrap(); +/// // This is the result of some important and long-ish work. +/// let result = data.iter().fold(0, |acc, x| acc + x * 2); +/// // We drop the `data` explicitely because it's not necessary anymore +/// // and the thread still has work to do. This allow other threads to +/// // start working on the data immediately, without waiting +/// // for the rest of the unrelated work to be done here. +/// // +/// // It's even more important here because we `.join` the threads after that. +/// // If we had not dropped the lock, a thread could be waiting forever for +/// // it, causing a deadlock. +/// std::mem::drop(data); +/// // Here the lock is not assigned to a variable and so, even if the scope +/// // does not end after this line, the mutex is still released: +/// // there is no deadlock. +/// *res_mutex.lock().unwrap() += result; +/// +/// threads.into_iter().for_each(|thread| { +/// thread +/// .join() +/// .expect("The thread creating or execution failed !") +/// }); +/// +/// assert_eq!(*res_mutex.lock().unwrap(), 80); +/// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "mutex_type")] pub struct Mutex { -- cgit 1.4.1-3-g733a5 From 9c8f881ccd050f06387612e4b8aa18111c51a63b Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 7 Jun 2020 23:42:55 +0200 Subject: Improved the example to work with mutable data, providing a reason for the mutex holding it --- src/libstd/sync/mutex.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 6077e1a4029..633496154ae 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -119,7 +119,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// const N: usize = 3; /// /// // Some data to work with in multiple threads. -/// let data_mutex = Arc::new(Mutex::new([1, 2, 3, 4])); +/// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4])); /// // The result of all the work across all threads. /// let res_mutex = Arc::new(Mutex::new(0)); /// @@ -131,9 +131,10 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// let res_mutex_clone = Arc::clone(&res_mutex); /// /// threads.push(thread::spawn(move || { -/// let data = *data_mutex_clone.lock().unwrap(); +/// let mut data = data_mutex_clone.lock().unwrap(); /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); +/// data.push(result); /// // We drop the `data` explicitely because it's not necessary anymore /// // and the thread still has work to do. This allow other threads to /// // start working on the data immediately, without waiting @@ -143,9 +144,10 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// })); /// }); /// -/// let data = *data_mutex.lock().unwrap(); +/// let mut data = data_mutex.lock().unwrap(); /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); +/// data.push(result); /// // We drop the `data` explicitely because it's not necessary anymore /// // and the thread still has work to do. This allow other threads to /// // start working on the data immediately, without waiting @@ -166,7 +168,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// .expect("The thread creating or execution failed !") /// }); /// -/// assert_eq!(*res_mutex.lock().unwrap(), 80); +/// assert_eq!(*res_mutex.lock().unwrap(), 800); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "mutex_type")] -- cgit 1.4.1-3-g733a5 From fdef1a5915332a3f9012b41f4176cf2a16025257 Mon Sep 17 00:00:00 2001 From: Poliorcetics Date: Mon, 8 Jun 2020 16:29:47 +0200 Subject: Simply use drop instead of std::mem::drop Co-authored-by: LeSeulArtichaut --- src/libstd/sync/mutex.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 633496154ae..c2c86fae654 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -139,7 +139,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // and the thread still has work to do. This allow other threads to /// // start working on the data immediately, without waiting /// // for the rest of the unrelated work to be done here. -/// std::mem::drop(data); +/// drop(data); /// *res_mutex_clone.lock().unwrap() += result; /// })); /// }); @@ -156,7 +156,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // It's even more important here because we `.join` the threads after that. /// // If we had not dropped the lock, a thread could be waiting forever for /// // it, causing a deadlock. -/// std::mem::drop(data); +/// drop(data); /// // Here the lock is not assigned to a variable and so, even if the scope /// // does not end after this line, the mutex is still released: /// // there is no deadlock. -- cgit 1.4.1-3-g733a5 From 496818ccd79e9bc093552887c923168defb13c6c Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Mon, 8 Jun 2020 18:31:45 +0200 Subject: Add methods to go from a nul-terminated Vec to a CString, checked and unchecked. Doc tests have been written and the documentation on the error type updated too. --- src/libstd/ffi/c_str.rs | 80 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 77 insertions(+), 3 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 4bac9a4917d..f3a935ccc11 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -234,15 +234,18 @@ pub struct NulError(usize, Vec); /// An error indicating that a nul byte was not in the expected position. /// -/// The slice used to create a [`CStr`] must have one and only one nul -/// byte at the end of the slice. +/// The slice used to create a [`CStr`] or the vector used to create a +/// [`CString`] must have one and only one nul byte, positioned at the end. /// /// This error is created by the /// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on -/// [`CStr`]. See its documentation for more. +/// [`CStr`] or the [`from_vec_with_nul`][`CString::from_vec_with_nul`] method +/// on [`CString`]. See their documentation for more. /// /// [`CStr`]: struct.CStr.html /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul +/// [`CString`]: struct.CString.html +/// [`CString::from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul /// /// # Examples /// @@ -632,6 +635,77 @@ impl CString { let this = mem::ManuallyDrop::new(self); unsafe { ptr::read(&this.inner) } } + + /// Converts a `Vec` of `u8` to a `CString` without checking the invariants + /// on the given `Vec`. + /// + /// # Safety + /// + /// The given `Vec` **must** have one nul byte as its last element. + /// This means it cannot be empty nor have any other nul byte anywhere else. + /// + /// # Example + /// + /// ``` + /// use std::ffi::CString; + /// assert_eq!( + /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) }, + /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) } + /// ); + /// ``` + #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")] + pub unsafe fn from_vec_with_nul_unchecked(v: Vec) -> Self { + Self { inner: v.into_boxed_slice() } + } + + /// Attempts to converts a `Vec` of `u8` to a `CString`. + /// + /// Runtime checks are present to ensure there is only one nul byte in the + /// `Vec`, its last element. + /// + /// # Errors + /// + /// If a nul byte is present and not the last element or no nul bytes + /// is present, an error will be returned. + /// + /// # Examples + /// + /// A successful conversion will produce the same result as [`new`] when + /// called without the ending nul byte. + /// + /// ``` + /// use std::ffi::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()) + /// ); + /// ``` + /// + /// A incorrectly formatted vector will produce an error. + /// + /// ``` + /// use std::ffi::{CString, FromBytesWithNulError}; + /// // Interior nul byte + /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err(); + /// // No nul byte + /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err(); + /// ``` + /// + /// [`new`]: #method.new + #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")] + pub fn from_vec_with_nul(v: Vec) -> Result { + let nul_pos = memchr::memchr(0, &v); + match nul_pos { + Some(nul_pos) if nul_pos + 1 == v.len() => { + // SAFETY: We know there is only one nul byte, at the end + // of the vec. + Ok(unsafe { Self::from_vec_with_nul_unchecked(v) }) + } + Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)), + None => Err(FromBytesWithNulError::not_nul_terminated()), + } + } } // Turns this `CString` into an empty string to prevent -- cgit 1.4.1-3-g733a5 From b03164e6679284b984437fe82092682cf7c984f8 Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Tue, 9 Jun 2020 22:15:05 +0200 Subject: Move to unstable, linking the issue --- src/libstd/ffi/c_str.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index f3a935ccc11..6f7dc091897 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -653,7 +653,7 @@ impl CString { /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) } /// ); /// ``` - #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")] + #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] pub unsafe fn from_vec_with_nul_unchecked(v: Vec) -> Self { Self { inner: v.into_boxed_slice() } } @@ -693,7 +693,7 @@ impl CString { /// ``` /// /// [`new`]: #method.new - #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")] + #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] pub fn from_vec_with_nul(v: Vec) -> Result { let nul_pos = memchr::memchr(0, &v); match nul_pos { -- cgit 1.4.1-3-g733a5 From 1312d30a6a837f72c3f36f5dc1c575a29890aa2c Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Tue, 9 Jun 2020 22:40:30 +0200 Subject: Remove a lot of unecessary/duplicated comments --- src/libstd/sync/mutex.rs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index c2c86fae654..b3ef521d6ec 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -118,15 +118,11 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// /// const N: usize = 3; /// -/// // Some data to work with in multiple threads. /// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4])); -/// // The result of all the work across all threads. /// let res_mutex = Arc::new(Mutex::new(0)); /// -/// // Threads other than the main thread. /// let mut threads = Vec::with_capacity(N); /// (0..N).for_each(|_| { -/// // Getting clones for the mutexes. /// let data_mutex_clone = Arc::clone(&data_mutex); /// let res_mutex_clone = Arc::clone(&res_mutex); /// @@ -135,10 +131,6 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); /// data.push(result); -/// // We drop the `data` explicitely because it's not necessary anymore -/// // and the thread still has work to do. This allow other threads to -/// // start working on the data immediately, without waiting -/// // for the rest of the unrelated work to be done here. /// drop(data); /// *res_mutex_clone.lock().unwrap() += result; /// })); @@ -153,9 +145,9 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // start working on the data immediately, without waiting /// // for the rest of the unrelated work to be done here. /// // -/// // It's even more important here because we `.join` the threads after that. -/// // If we had not dropped the lock, a thread could be waiting forever for -/// // it, causing a deadlock. +/// // It's even more important here than in the threads because we `.join` the +/// // threads after that. If we had not dropped the lock, a thread could be +/// // waiting forever for it, causing a deadlock. /// drop(data); /// // Here the lock is not assigned to a variable and so, even if the scope /// // does not end after this line, the mutex is still released: -- cgit 1.4.1-3-g733a5 From 7f3bb398fa90d68c737dd7e00a3813e0620ba472 Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Wed, 10 Jun 2020 23:13:45 +0200 Subject: Add a TryFrom> impl that mirror from_vec_with_nul --- src/libstd/ffi/c_str.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'src/libstd') diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 6f7dc091897..3a3b51fd353 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -1,6 +1,7 @@ use crate::ascii; use crate::borrow::{Borrow, Cow}; use crate::cmp::Ordering; +use crate::convert::TryFrom; use crate::error::Error; use crate::fmt::{self, Write}; use crate::io; @@ -853,6 +854,19 @@ impl From> for CString { } } +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +impl TryFrom> for CString { + type Error = FromBytesWithNulError; + + /// See the document about [`from_vec_with_nul`] for more + /// informations about the behaviour of this method. + /// + /// [`from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul + fn try_from(value: Vec) -> Result { + Self::from_vec_with_nul(value) + } +} + #[stable(feature = "more_box_slice_clone", since = "1.29.0")] impl Clone for Box { #[inline] -- cgit 1.4.1-3-g733a5 From 6b955268d71907d9049a399a0e0a33f6448e1221 Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Thu, 11 Jun 2020 16:55:03 +0200 Subject: Fix the link in the TryFrom impl --- src/libstd/ffi/c_str.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/libstd') diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 3a3b51fd353..298f6c33457 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -861,7 +861,7 @@ impl TryFrom> for CString { /// See the document about [`from_vec_with_nul`] for more /// informations about the behaviour of this method. /// - /// [`from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul + /// [`from_vec_with_nul`]: CString::from_vec_with_nul fn try_from(value: Vec) -> Result { Self::from_vec_with_nul(value) } -- cgit 1.4.1-3-g733a5 From c45231ca555950cea450ba65f9d2d1962e3af6cd Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 12 Jun 2020 22:12:45 -0700 Subject: Revert heterogeneous SocketAddr PartialEq impls These lead to inference regressions (mostly in tests) in code that looks like: let socket = std::net::SocketAddrV4::new(std::net::Ipv4Addr::new(127, 0, 0, 1), 8080); assert_eq!(socket, "127.0.0.1:8080".parse().unwrap()); That compiles as of stable 1.44.0 but fails in beta with: error[E0284]: type annotations needed --> src/main.rs:3:41 | 3 | assert_eq!(socket, "127.0.0.1:8080".parse().unwrap()); | ^^^^^ cannot infer type for type parameter `F` declared on the associated function `parse` | = note: cannot satisfy `<_ as std::str::FromStr>::Err == _` help: consider specifying the type argument in the method call | 3 | assert_eq!(socket, "127.0.0.1:8080".parse::().unwrap()); | --- src/libstd/net/addr.rs | 40 ---------------------------------------- 1 file changed, 40 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs index b780340884e..7e3c3e8f304 100644 --- a/src/libstd/net/addr.rs +++ b/src/libstd/net/addr.rs @@ -694,42 +694,6 @@ impl PartialEq for SocketAddrV6 { && self.inner.sin6_scope_id == other.inner.sin6_scope_id } } -#[stable(feature = "socketaddr_ordering", since = "1.45.0")] -impl PartialEq for SocketAddr { - fn eq(&self, other: &SocketAddrV4) -> bool { - match self { - SocketAddr::V4(v4) => v4 == other, - SocketAddr::V6(_) => false, - } - } -} -#[stable(feature = "socketaddr_ordering", since = "1.45.0")] -impl PartialEq for SocketAddr { - fn eq(&self, other: &SocketAddrV6) -> bool { - match self { - SocketAddr::V4(_) => false, - SocketAddr::V6(v6) => v6 == other, - } - } -} -#[stable(feature = "socketaddr_ordering", since = "1.45.0")] -impl PartialEq for SocketAddrV4 { - fn eq(&self, other: &SocketAddr) -> bool { - match other { - SocketAddr::V4(v4) => self == v4, - SocketAddr::V6(_) => false, - } - } -} -#[stable(feature = "socketaddr_ordering", since = "1.45.0")] -impl PartialEq for SocketAddrV6 { - fn eq(&self, other: &SocketAddr) -> bool { - match other { - SocketAddr::V4(_) => false, - SocketAddr::V6(v6) => self == v6, - } - } -} #[stable(feature = "rust1", since = "1.0.0")] impl Eq for SocketAddrV4 {} #[stable(feature = "rust1", since = "1.0.0")] @@ -1242,12 +1206,8 @@ mod tests { // equality assert_eq!(v4_1, v4_1); assert_eq!(v6_1, v6_1); - assert_eq!(v4_1, SocketAddr::V4(v4_1)); - assert_eq!(v6_1, SocketAddr::V6(v6_1)); assert_eq!(SocketAddr::V4(v4_1), SocketAddr::V4(v4_1)); assert_eq!(SocketAddr::V6(v6_1), SocketAddr::V6(v6_1)); - assert!(v4_1 != SocketAddr::V6(v6_1)); - assert!(v6_1 != SocketAddr::V4(v4_1)); assert!(v4_1 != v4_2); assert!(v6_1 != v6_2); -- cgit 1.4.1-3-g733a5 From f747073fc1751afd2cfd4395283a4822b618f2da Mon Sep 17 00:00:00 2001 From: Poliorcetics Date: Sat, 13 Jun 2020 18:41:01 +0200 Subject: Apply suggestions from code review Co-authored-by: David Tolnay --- src/libstd/sync/mutex.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index b3ef521d6ec..6625d4659dc 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -108,8 +108,8 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// *guard += 1; /// ``` /// -/// It is sometimes a good idea (or even necessary) to manually drop the mutex -/// to unlock it as soon as possible. If you need the resource until the end of +/// It is sometimes necessary to manually drop the mutex +/// guard to unlock it as soon as possible. If you need the resource until the end of /// the scope, this is not needed. /// /// ``` @@ -140,16 +140,16 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); /// data.push(result); -/// // We drop the `data` explicitely because it's not necessary anymore +/// // We drop the `data` explicitly because it's not necessary anymore /// // and the thread still has work to do. This allow other threads to /// // start working on the data immediately, without waiting /// // for the rest of the unrelated work to be done here. /// // /// // It's even more important here than in the threads because we `.join` the -/// // threads after that. If we had not dropped the lock, a thread could be +/// // threads after that. If we had not dropped the mutex guard, a thread could be /// // waiting forever for it, causing a deadlock. /// drop(data); -/// // Here the lock is not assigned to a variable and so, even if the scope +/// // Here the mutex guard is not assigned to a variable and so, even if the scope /// // does not end after this line, the mutex is still released: /// // there is no deadlock. /// *res_mutex.lock().unwrap() += result; -- cgit 1.4.1-3-g733a5 From 34b3ff06e101f60cb69268ee83c93c177b63c322 Mon Sep 17 00:00:00 2001 From: Poliorcetics Date: Sat, 13 Jun 2020 18:43:37 +0200 Subject: Clarify the scope-related explanation Based on the review made by dtolnay. --- src/libstd/sync/mutex.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 6625d4659dc..37c8125b098 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -108,9 +108,8 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// *guard += 1; /// ``` /// -/// It is sometimes necessary to manually drop the mutex -/// guard to unlock it as soon as possible. If you need the resource until the end of -/// the scope, this is not needed. +/// It is sometimes necessary to manually drop the mutex guard +/// to unlock it sooner than the end of the enclosing scope. /// /// ``` /// use std::sync::{Arc, Mutex}; -- cgit 1.4.1-3-g733a5 From c010e711ca5ec02012afb83c0d99aec9d26a9eea Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 13 Jun 2020 10:11:02 -0700 Subject: Rewrap comments in Mutex example --- src/libstd/sync/mutex.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 37c8125b098..8478457eabf 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -108,8 +108,8 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// *guard += 1; /// ``` /// -/// It is sometimes necessary to manually drop the mutex guard -/// to unlock it sooner than the end of the enclosing scope. +/// It is sometimes necessary to manually drop the mutex guard to unlock it +/// sooner than the end of the enclosing scope. /// /// ``` /// use std::sync::{Arc, Mutex}; @@ -139,18 +139,18 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); /// data.push(result); -/// // We drop the `data` explicitly because it's not necessary anymore -/// // and the thread still has work to do. This allow other threads to -/// // start working on the data immediately, without waiting -/// // for the rest of the unrelated work to be done here. +/// // We drop the `data` explicitly because it's not necessary anymore and the +/// // thread still has work to do. This allow other threads to start working on +/// // the data immediately, without waiting for the rest of the unrelated work +/// // to be done here. /// // /// // It's even more important here than in the threads because we `.join` the -/// // threads after that. If we had not dropped the mutex guard, a thread could be -/// // waiting forever for it, causing a deadlock. +/// // threads after that. If we had not dropped the mutex guard, a thread could +/// // be waiting forever for it, causing a deadlock. /// drop(data); -/// // Here the mutex guard is not assigned to a variable and so, even if the scope -/// // does not end after this line, the mutex is still released: -/// // there is no deadlock. +/// // Here the mutex guard is not assigned to a variable and so, even if the +/// // scope does not end after this line, the mutex is still released: there is +/// // no deadlock. /// *res_mutex.lock().unwrap() += result; /// /// threads.into_iter().for_each(|thread| { -- cgit 1.4.1-3-g733a5 From 204c236ad5b632294d8794e729326be8053ab2aa Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 13 Jun 2020 10:21:11 -0700 Subject: Add test for comparing SocketAddr with inferred right-hand side --- src/libstd/net/addr.rs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src/libstd') diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs index 7e3c3e8f304..b8fa1a7f744 100644 --- a/src/libstd/net/addr.rs +++ b/src/libstd/net/addr.rs @@ -1228,5 +1228,10 @@ mod tests { assert!(v6_1 < v6_3); assert!(v4_3 > v4_1); assert!(v6_3 > v6_1); + + // compare with an inferred right-hand side + assert_eq!(v4_1, "224.120.45.1:23456".parse().unwrap()); + assert_eq!(v6_1, "[2001:db8:f00::1002]:23456".parse().unwrap()); + assert_eq!(SocketAddr::V4(v4_1), "224.120.45.1:23456".parse().unwrap()); } } -- cgit 1.4.1-3-g733a5 From 71d41d9e9f020c9eb527a47e16e4041dfcdaef84 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Sat, 13 Jun 2020 20:51:00 +0200 Subject: add TcpListener support for HermitCore Add basic support of TcpListerner for HermitCore. In addition, revise TcpStream to support peer_addr. --- src/libstd/sys/hermit/net.rs | 157 ++++++++++++++++++++++++++++++------------- 1 file changed, 111 insertions(+), 46 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 5b5379c8b05..2fef8d381ca 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -1,10 +1,13 @@ use crate::convert::TryFrom; use crate::fmt; use crate::io::{self, ErrorKind, IoSlice, IoSliceMut}; -use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; +use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use crate::str; +use crate::sync::Arc; use crate::sys::hermit::abi; +use crate::sys::hermit::abi::IpAddress::{Ipv4, Ipv6}; use crate::sys::{unsupported, Void}; +use crate::sys_common::AsInner; use crate::time::Duration; /// Checks whether the HermitCore's socket interface has been started already, and @@ -17,14 +20,37 @@ pub fn init() -> io::Result<()> { Ok(()) } -pub struct TcpStream(abi::Handle); +#[derive(Debug, Clone)] +pub struct Socket(abi::Handle); + +impl Socket { + fn new(handle: abi::Handle) -> Socket { + Socket(handle) + } +} + +impl AsInner for Socket { + fn as_inner(&self) -> &abi::Handle { + &self.0 + } +} + +impl Drop for Socket { + fn drop(&mut self) { + let _ = abi::tcpstream::close(self.0); + } +} + + +#[derive(Clone)] +pub struct TcpStream(Arc); impl TcpStream { pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result { let addr = addr?; match abi::tcpstream::connect(addr.ip().to_string().as_bytes(), addr.port(), None) { - Ok(handle) => Ok(TcpStream(handle)), + Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))), _ => { Err(io::Error::new(ErrorKind::Other, "Unable to initiate a connection on a socket")) } @@ -37,7 +63,7 @@ impl TcpStream { saddr.port(), Some(duration.as_millis() as u64), ) { - Ok(handle) => Ok(TcpStream(handle)), + Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))), _ => { Err(io::Error::new(ErrorKind::Other, "Unable to initiate a connection on a socket")) } @@ -45,31 +71,34 @@ impl TcpStream { } pub fn set_read_timeout(&self, duration: Option) -> io::Result<()> { - abi::tcpstream::set_read_timeout(self.0, duration.map(|d| d.as_millis() as u64)) + abi::tcpstream::set_read_timeout(*self.0.as_inner(), duration.map(|d| d.as_millis() as u64)) .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to set timeout value")) } pub fn set_write_timeout(&self, duration: Option) -> io::Result<()> { - abi::tcpstream::set_write_timeout(self.0, duration.map(|d| d.as_millis() as u64)) - .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to set timeout value")) + abi::tcpstream::set_write_timeout( + *self.0.as_inner(), + duration.map(|d| d.as_millis() as u64), + ) + .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to set timeout value")) } pub fn read_timeout(&self) -> io::Result> { - let duration = abi::tcpstream::get_read_timeout(self.0) + let duration = abi::tcpstream::get_read_timeout(*self.0.as_inner()) .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to determine timeout value"))?; Ok(duration.map(|d| Duration::from_millis(d))) } pub fn write_timeout(&self) -> io::Result> { - let duration = abi::tcpstream::get_write_timeout(self.0) + let duration = abi::tcpstream::get_write_timeout(*self.0.as_inner()) .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to determine timeout value"))?; Ok(duration.map(|d| Duration::from_millis(d))) } pub fn peek(&self, buf: &mut [u8]) -> io::Result { - abi::tcpstream::peek(self.0, buf) + abi::tcpstream::peek(*self.0.as_inner(), buf) .map_err(|_| io::Error::new(ErrorKind::Other, "set_nodelay failed")) } @@ -81,18 +110,11 @@ impl TcpStream { let mut size: usize = 0; for i in ioslice.iter_mut() { - let mut pos: usize = 0; - - while pos < i.len() { - let ret = abi::tcpstream::read(self.0, &mut i[pos..]) - .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to read on socket"))?; - - if ret == 0 { - return Ok(size); - } else { - size += ret; - pos += ret; - } + let ret = abi::tcpstream::read(*self.0.as_inner(), &mut i[0..]) + .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to read on socket"))?; + + if ret != 0 { + size += ret; } } @@ -112,7 +134,7 @@ impl TcpStream { let mut size: usize = 0; for i in ioslice.iter() { - size += abi::tcpstream::write(self.0, i) + size += abi::tcpstream::write(*self.0.as_inner(), i) .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to write on socket"))?; } @@ -125,7 +147,32 @@ impl TcpStream { } pub fn peer_addr(&self) -> io::Result { - Err(io::Error::new(ErrorKind::Other, "peer_addr isn't supported")) + let (ipaddr, port) = abi::tcpstream::peer_addr(*self.0.as_inner()) + .map_err(|_| io::Error::new(ErrorKind::Other, "peer_addr failed"))?; + + let saddr = match ipaddr { + Ipv4(ref addr) => SocketAddr::new( + IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), + port, + ), + Ipv6(ref addr) => SocketAddr::new( + IpAddr::V6(Ipv6Addr::new( + ((addr.0[0] as u16) << 8) | addr.0[1] as u16, + ((addr.0[2] as u16) << 8) | addr.0[3] as u16, + ((addr.0[4] as u16) << 8) | addr.0[5] as u16, + ((addr.0[6] as u16) << 8) | addr.0[7] as u16, + ((addr.0[8] as u16) << 8) | addr.0[9] as u16, + ((addr.0[10] as u16) << 8) | addr.0[11] as u16, + ((addr.0[12] as u16) << 8) | addr.0[13] as u16, + ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), + port, + ), + _ => { + return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); + }, + }; + + Ok(saddr) } pub fn socket_addr(&self) -> io::Result { @@ -133,34 +180,31 @@ impl TcpStream { } pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { - abi::tcpstream::shutdown(self.0, how as i32) + abi::tcpstream::shutdown(*self.0.as_inner(), how as i32) .map_err(|_| io::Error::new(ErrorKind::Other, "unable to shutdown socket")) } pub fn duplicate(&self) -> io::Result { - let handle = abi::tcpstream::duplicate(self.0) - .map_err(|_| io::Error::new(ErrorKind::Other, "unable to duplicate stream"))?; - - Ok(TcpStream(handle)) + Ok(self.clone()) } pub fn set_nodelay(&self, mode: bool) -> io::Result<()> { - abi::tcpstream::set_nodelay(self.0, mode) + abi::tcpstream::set_nodelay(*self.0.as_inner(), mode) .map_err(|_| io::Error::new(ErrorKind::Other, "set_nodelay failed")) } pub fn nodelay(&self) -> io::Result { - abi::tcpstream::nodelay(self.0) + abi::tcpstream::nodelay(*self.0.as_inner()) .map_err(|_| io::Error::new(ErrorKind::Other, "nodelay failed")) } pub fn set_ttl(&self, tll: u32) -> io::Result<()> { - abi::tcpstream::set_tll(self.0, tll) + abi::tcpstream::set_tll(*self.0.as_inner(), tll) .map_err(|_| io::Error::new(ErrorKind::Other, "unable to set TTL")) } pub fn ttl(&self) -> io::Result { - abi::tcpstream::get_tll(self.0) + abi::tcpstream::get_tll(*self.0.as_inner()) .map_err(|_| io::Error::new(ErrorKind::Other, "unable to get TTL")) } @@ -169,40 +213,61 @@ impl TcpStream { } pub fn set_nonblocking(&self, mode: bool) -> io::Result<()> { - abi::tcpstream::set_nonblocking(self.0, mode) + abi::tcpstream::set_nonblocking(*self.0.as_inner(), mode) .map_err(|_| io::Error::new(ErrorKind::Other, "unable to set blocking mode")) } } -impl Drop for TcpStream { - fn drop(&mut self) { - let _ = abi::tcpstream::close(self.0); - } -} - impl fmt::Debug for TcpStream { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } -pub struct TcpListener(abi::Handle); +#[derive(Clone)] +pub struct TcpListener(SocketAddr); impl TcpListener { - pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { - Err(io::Error::new(ErrorKind::Other, "not supported")) + pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result { + let addr = addr?; + + Ok(TcpListener(*addr)) } pub fn socket_addr(&self) -> io::Result { - Err(io::Error::new(ErrorKind::Other, "not supported")) + Ok(self.0) } pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { - Err(io::Error::new(ErrorKind::Other, "not supported")) + let (handle, ipaddr, port) = abi::tcplistener::accept(self.0.port()) + .map_err(|_| io::Error::new(ErrorKind::Other, "accept failed"))?; + let saddr = match ipaddr { + Ipv4(ref addr) => SocketAddr::new( + IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), + port, + ), + Ipv6(ref addr) => SocketAddr::new( + IpAddr::V6(Ipv6Addr::new( + ((addr.0[0] as u16) << 8) | addr.0[1] as u16, + ((addr.0[2] as u16) << 8) | addr.0[3] as u16, + ((addr.0[4] as u16) << 8) | addr.0[5] as u16, + ((addr.0[6] as u16) << 8) | addr.0[7] as u16, + ((addr.0[8] as u16) << 8) | addr.0[9] as u16, + ((addr.0[10] as u16) << 8) | addr.0[11] as u16, + ((addr.0[12] as u16) << 8) | addr.0[13] as u16, + ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), + port, + ), + _ => { + return Err(io::Error::new(ErrorKind::Other, "accept failed")); + }, + }; + + Ok((TcpStream(Arc::new(Socket(handle))), saddr)) } pub fn duplicate(&self) -> io::Result { - Err(io::Error::new(ErrorKind::Other, "not supported")) + Ok(self.clone()) } pub fn set_ttl(&self, _: u32) -> io::Result<()> { -- cgit 1.4.1-3-g733a5 From c99116afe37d5a1dde65ed8a2e107892be81b20a Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Sun, 14 Jun 2020 00:38:31 +0200 Subject: remove unused function --- src/libstd/sys/hermit/net.rs | 6 ------ 1 file changed, 6 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 2fef8d381ca..70c010e6232 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -23,12 +23,6 @@ pub fn init() -> io::Result<()> { #[derive(Debug, Clone)] pub struct Socket(abi::Handle); -impl Socket { - fn new(handle: abi::Handle) -> Socket { - Socket(handle) - } -} - impl AsInner for Socket { fn as_inner(&self) -> &abi::Handle { &self.0 -- cgit 1.4.1-3-g733a5 From fd86a847206dd2333c23c768b8c0564e15a05c1c Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Sun, 14 Jun 2020 00:39:14 +0200 Subject: use latest interface to HermitCore --- Cargo.lock | 4 ++-- src/libstd/Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/libstd') diff --git a/Cargo.lock b/Cargo.lock index bbbcf797f75..009767934d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1434,9 +1434,9 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.1.13" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91780f809e750b0a89f5544be56617ff6b1227ee485bcb06ebe10cdf89bd3b71" +checksum = "b9586eedd4ce6b3c498bc3b4dd92fc9f11166aa908a914071953768066c67909" dependencies = [ "compiler_builtins", "libc", diff --git a/src/libstd/Cargo.toml b/src/libstd/Cargo.toml index 6af1cbb34b6..83029a86420 100644 --- a/src/libstd/Cargo.toml +++ b/src/libstd/Cargo.toml @@ -41,7 +41,7 @@ dlmalloc = { version = "0.1", features = ['rustc-dep-of-std'] } fortanix-sgx-abi = { version = "0.3.2", features = ['rustc-dep-of-std'] } [target.'cfg(all(any(target_arch = "x86_64", target_arch = "aarch64"), target_os = "hermit"))'.dependencies] -hermit-abi = { version = "0.1.13", features = ['rustc-dep-of-std'] } +hermit-abi = { version = "0.1.14", features = ['rustc-dep-of-std'] } [target.wasm32-wasi.dependencies] wasi = { version = "0.9.0", features = ['rustc-dep-of-std'], default-features = false } -- cgit 1.4.1-3-g733a5 From 5f4eb27a0dc5d17e4a74f1a2d71a8f5a30916e3a Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 14 Jun 2020 19:21:44 +0200 Subject: Removing the TryFrom impl --- src/libstd/ffi/c_str.rs | 14 -------------- 1 file changed, 14 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 298f6c33457..6f7dc091897 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -1,7 +1,6 @@ use crate::ascii; use crate::borrow::{Borrow, Cow}; use crate::cmp::Ordering; -use crate::convert::TryFrom; use crate::error::Error; use crate::fmt::{self, Write}; use crate::io; @@ -854,19 +853,6 @@ impl From> for CString { } } -#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] -impl TryFrom> for CString { - type Error = FromBytesWithNulError; - - /// See the document about [`from_vec_with_nul`] for more - /// informations about the behaviour of this method. - /// - /// [`from_vec_with_nul`]: CString::from_vec_with_nul - fn try_from(value: Vec) -> Result { - Self::from_vec_with_nul(value) - } -} - #[stable(feature = "more_box_slice_clone", since = "1.29.0")] impl Clone for Box { #[inline] -- cgit 1.4.1-3-g733a5 From 685f06612dc8842b734181e380eae0f9b1a9483f Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 14 Jun 2020 23:21:40 +0200 Subject: Add a new error type for the new method --- src/libstd/ffi/c_str.rs | 96 +++++++++++++++++++++++++++++++++++++++++++++++++ src/libstd/ffi/mod.rs | 2 ++ 2 files changed, 98 insertions(+) (limited to 'src/libstd') diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 6f7dc091897..956100bca6a 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -260,6 +260,32 @@ pub struct FromBytesWithNulError { kind: FromBytesWithNulErrorKind, } +/// An error indicating that a nul byte was not in the expected position. +/// +/// The vector used to create a [`CString`] must have one and only one nul byte, +/// positioned at the end. +/// +/// This error is created by the [`from_vec_with_nul`] method on [`CString`]. +/// See its documentation for more. +/// +/// [`CString`]: struct.CString.html +/// [`from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul +/// +/// # Examples +/// +/// ``` +/// #![feature(cstring_from_vec_with_nul)] +/// use std::ffi::{CString, FromVecWithNulError}; +/// +/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err(); +/// ``` +#[derive(Clone, PartialEq, Eq, Debug)] +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +pub struct FromVecWithNulError { + error_kind: FromBytesWithNulErrorKind, + bytes: Vec, +} + #[derive(Clone, PartialEq, Eq, Debug)] enum FromBytesWithNulErrorKind { InteriorNul(usize), @@ -275,6 +301,59 @@ impl FromBytesWithNulError { } } +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +impl FromVecWithNulError { + /// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`]. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(cstring_from_vec_with_nul)] + /// use std::ffi::CString; + /// + /// // Some invalid bytes in a vector + /// let bytes = b"f\0oo".to_vec(); + /// + /// let value = CString::from_vec_with_nul(bytes.clone()); + /// + /// assert_eq!(&bytes[..], value.unwrap_err().as_bytes()); + /// ``` + /// + /// [`CString`]: struct.CString.html + pub fn as_bytes(&self) -> &[u8] { + &self.bytes[..] + } + + /// Returns the bytes that were attempted to convert to a [`CString`]. + /// + /// This method is carefully constructed to avoid allocation. It will + /// consume the error, moving out the bytes, so that a copy of the bytes + /// does not need to be made. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(cstring_from_vec_with_nul)] + /// use std::ffi::CString; + /// + /// // Some invalid bytes in a vector + /// let bytes = b"f\0oo".to_vec(); + /// + /// let value = CString::from_vec_with_nul(bytes.clone()); + /// + /// assert_eq!(bytes, value.unwrap_err().into_bytes()); + /// ``` + /// + /// [`CString`]: struct.CString.html + pub fn into_bytes(self) -> Vec { + self.bytes + } +} + /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`]. /// /// `CString` is just a wrapper over a buffer of bytes with a nul @@ -1039,6 +1118,23 @@ impl fmt::Display for FromBytesWithNulError { } } +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +impl Error for FromVecWithNulError {} + +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +impl fmt::Display for FromVecWithNulError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.error_kind { + FromBytesWithNulErrorKind::InteriorNul(pos) => { + write!(f, "data provided contains an interior nul byte at pos {}", pos) + } + FromBytesWithNulErrorKind::NotNulTerminated => { + write!(f, "data provided is not nul terminated") + } + } + } +} + impl IntoStringError { /// Consumes this error, returning original [`CString`] which generated the /// error. diff --git a/src/libstd/ffi/mod.rs b/src/libstd/ffi/mod.rs index 5aca7b7476a..f442d7fde1a 100644 --- a/src/libstd/ffi/mod.rs +++ b/src/libstd/ffi/mod.rs @@ -157,6 +157,8 @@ #[stable(feature = "cstr_from_bytes", since = "1.10.0")] pub use self::c_str::FromBytesWithNulError; +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +pub use self::c_str::FromVecWithNulError; #[stable(feature = "rust1", since = "1.0.0")] pub use self::c_str::{CStr, CString, IntoStringError, NulError}; -- cgit 1.4.1-3-g733a5 From 47cc5cca7e64a434fa15680b7dcc621ca6f1abbf Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 14 Jun 2020 23:22:36 +0200 Subject: Update to use the new error type and correctly compile the doc tests --- src/libstd/ffi/c_str.rs | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 956100bca6a..3537a9f8656 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -234,18 +234,14 @@ pub struct NulError(usize, Vec); /// An error indicating that a nul byte was not in the expected position. /// -/// The slice used to create a [`CStr`] or the vector used to create a -/// [`CString`] must have one and only one nul byte, positioned at the end. +/// The slice used to create a [`CStr`] must have one and only one nul byte, +/// positioned at the end. /// -/// This error is created by the -/// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on -/// [`CStr`] or the [`from_vec_with_nul`][`CString::from_vec_with_nul`] method -/// on [`CString`]. See their documentation for more. +/// This error is created by the [`from_bytes_with_nul`] method on [`CStr`]. +/// See its documentation for more. /// /// [`CStr`]: struct.CStr.html -/// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul -/// [`CString`]: struct.CString.html -/// [`CString::from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul +/// [`from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul /// /// # Examples /// @@ -726,6 +722,7 @@ impl CString { /// # Example /// /// ``` + /// #![feature(cstring_from_vec_with_nul)] /// use std::ffi::CString; /// assert_eq!( /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) }, @@ -753,27 +750,29 @@ impl CString { /// called without the ending nul byte. /// /// ``` + /// #![feature(cstring_from_vec_with_nul)] /// use std::ffi::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()) + /// CString::new(b"abc".to_vec()).expect("CString::new failed") /// ); /// ``` /// /// A incorrectly formatted vector will produce an error. /// /// ``` - /// use std::ffi::{CString, FromBytesWithNulError}; + /// #![feature(cstring_from_vec_with_nul)] + /// use std::ffi::{CString, FromVecWithNulError}; /// // Interior nul byte - /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err(); + /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err(); /// // No nul byte - /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err(); + /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err(); /// ``` /// /// [`new`]: #method.new #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] - pub fn from_vec_with_nul(v: Vec) -> Result { + pub fn from_vec_with_nul(v: Vec) -> Result { let nul_pos = memchr::memchr(0, &v); match nul_pos { Some(nul_pos) if nul_pos + 1 == v.len() => { @@ -781,8 +780,14 @@ impl CString { // of the vec. Ok(unsafe { Self::from_vec_with_nul_unchecked(v) }) } - Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)), - None => Err(FromBytesWithNulError::not_nul_terminated()), + Some(nul_pos) => Err(FromVecWithNulError { + error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos), + bytes: v, + }), + None => Err(FromVecWithNulError { + error_kind: FromBytesWithNulErrorKind::NotNulTerminated, + bytes: v, + }), } } } -- cgit 1.4.1-3-g733a5 From d221ffc68e543f4a38efcc2bd34f52145f89003b Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Sun, 14 Jun 2020 23:43:54 +0200 Subject: simplify conversion to IpAddr::V6 --- src/libstd/sys/hermit/net.rs | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 70c010e6232..cba8d6aaca6 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -150,15 +150,7 @@ impl TcpStream { port, ), Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new( - ((addr.0[0] as u16) << 8) | addr.0[1] as u16, - ((addr.0[2] as u16) << 8) | addr.0[3] as u16, - ((addr.0[4] as u16) << 8) | addr.0[5] as u16, - ((addr.0[6] as u16) << 8) | addr.0[7] as u16, - ((addr.0[8] as u16) << 8) | addr.0[9] as u16, - ((addr.0[10] as u16) << 8) | addr.0[11] as u16, - ((addr.0[12] as u16) << 8) | addr.0[13] as u16, - ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), + IpAddr::V6(Ipv6Addr::new(addr.0)), port, ), _ => { @@ -241,15 +233,7 @@ impl TcpListener { port, ), Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new( - ((addr.0[0] as u16) << 8) | addr.0[1] as u16, - ((addr.0[2] as u16) << 8) | addr.0[3] as u16, - ((addr.0[4] as u16) << 8) | addr.0[5] as u16, - ((addr.0[6] as u16) << 8) | addr.0[7] as u16, - ((addr.0[8] as u16) << 8) | addr.0[9] as u16, - ((addr.0[10] as u16) << 8) | addr.0[11] as u16, - ((addr.0[12] as u16) << 8) | addr.0[13] as u16, - ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), + IpAddr::V6(Ipv6Addr::new(addr.0)), port, ), _ => { -- cgit 1.4.1-3-g733a5 From 9d596b50f15dfff47fa2272ee63cdc9aeb9307fa Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 07:28:53 +0200 Subject: changes to pass the format check --- src/libstd/sys/hermit/net.rs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index cba8d6aaca6..ced554d8790 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -149,13 +149,10 @@ impl TcpStream { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(addr.0)), - port, - ), + Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::new(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); - }, + } }; Ok(saddr) @@ -232,13 +229,10 @@ impl TcpListener { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(addr.0)), - port, - ), + Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::new(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "accept failed")); - }, + } }; Ok((TcpStream(Arc::new(Socket(handle))), saddr)) -- cgit 1.4.1-3-g733a5 From 810ba395638f622b4e7f11c2f056382db4d2fa05 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 08:07:56 +0200 Subject: remove obsolete line --- src/libstd/sys/hermit/net.rs | 1 - 1 file changed, 1 deletion(-) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index ced554d8790..fbb562fa510 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -35,7 +35,6 @@ impl Drop for Socket { } } - #[derive(Clone)] pub struct TcpStream(Arc); -- cgit 1.4.1-3-g733a5 From aa53a037a286a05c88e61ca008d90354cccb1512 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 08:43:08 +0200 Subject: Revert "changes to pass the format check" This reverts commit 9d596b50f15dfff47fa2272ee63cdc9aeb9307fa. --- src/libstd/sys/hermit/net.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index fbb562fa510..8f96f8622c6 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -148,10 +148,13 @@ impl TcpStream { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::new(addr.0)), port), + Ipv6(ref addr) => SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(addr.0)), + port, + ), _ => { return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); - } + }, }; Ok(saddr) @@ -228,10 +231,13 @@ impl TcpListener { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::new(addr.0)), port), + Ipv6(ref addr) => SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(addr.0)), + port, + ), _ => { return Err(io::Error::new(ErrorKind::Other, "accept failed")); - } + }, }; Ok((TcpStream(Arc::new(Socket(handle))), saddr)) -- cgit 1.4.1-3-g733a5 From 9c9f21fb23ae59012e7aba162e1105d26fcd119b Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 08:43:44 +0200 Subject: Revert "simplify conversion to IpAddr::V6" This reverts commit d221ffc68e543f4a38efcc2bd34f52145f89003b. --- src/libstd/sys/hermit/net.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 8f96f8622c6..a02f1131329 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -149,7 +149,15 @@ impl TcpStream { port, ), Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(addr.0)), + IpAddr::V6(Ipv6Addr::new( + ((addr.0[0] as u16) << 8) | addr.0[1] as u16, + ((addr.0[2] as u16) << 8) | addr.0[3] as u16, + ((addr.0[4] as u16) << 8) | addr.0[5] as u16, + ((addr.0[6] as u16) << 8) | addr.0[7] as u16, + ((addr.0[8] as u16) << 8) | addr.0[9] as u16, + ((addr.0[10] as u16) << 8) | addr.0[11] as u16, + ((addr.0[12] as u16) << 8) | addr.0[13] as u16, + ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), port, ), _ => { @@ -232,7 +240,15 @@ impl TcpListener { port, ), Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(addr.0)), + IpAddr::V6(Ipv6Addr::new( + ((addr.0[0] as u16) << 8) | addr.0[1] as u16, + ((addr.0[2] as u16) << 8) | addr.0[3] as u16, + ((addr.0[4] as u16) << 8) | addr.0[5] as u16, + ((addr.0[6] as u16) << 8) | addr.0[7] as u16, + ((addr.0[8] as u16) << 8) | addr.0[9] as u16, + ((addr.0[10] as u16) << 8) | addr.0[11] as u16, + ((addr.0[12] as u16) << 8) | addr.0[13] as u16, + ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), port, ), _ => { -- cgit 1.4.1-3-g733a5 From 6c983a733550ff37cb603f409901f3b3d0eaa8c2 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 08:53:58 +0200 Subject: use Ipv6Addr::from to build the IPv6 address --- src/libstd/sys/hermit/net.rs | 26 ++------------------------ 1 file changed, 2 insertions(+), 24 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index a02f1131329..6410dec756d 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -148,18 +148,7 @@ impl TcpStream { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new( - ((addr.0[0] as u16) << 8) | addr.0[1] as u16, - ((addr.0[2] as u16) << 8) | addr.0[3] as u16, - ((addr.0[4] as u16) << 8) | addr.0[5] as u16, - ((addr.0[6] as u16) << 8) | addr.0[7] as u16, - ((addr.0[8] as u16) << 8) | addr.0[9] as u16, - ((addr.0[10] as u16) << 8) | addr.0[11] as u16, - ((addr.0[12] as u16) << 8) | addr.0[13] as u16, - ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), - port, - ), + Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); }, @@ -239,18 +228,7 @@ impl TcpListener { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new( - ((addr.0[0] as u16) << 8) | addr.0[1] as u16, - ((addr.0[2] as u16) << 8) | addr.0[3] as u16, - ((addr.0[4] as u16) << 8) | addr.0[5] as u16, - ((addr.0[6] as u16) << 8) | addr.0[7] as u16, - ((addr.0[8] as u16) << 8) | addr.0[9] as u16, - ((addr.0[10] as u16) << 8) | addr.0[11] as u16, - ((addr.0[12] as u16) << 8) | addr.0[13] as u16, - ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), - port, - ), + Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "accept failed")); }, -- cgit 1.4.1-3-g733a5 From a8e3746e9160b8a433c95df7114e5760592a62e8 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 09:29:32 +0200 Subject: add comment about the usage of Arc --- src/libstd/sys/hermit/net.rs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 6410dec756d..9146dfc55f4 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -35,6 +35,9 @@ impl Drop for Socket { } } +// Arc is used to count the number of used sockets. +// Only if all sockets are released, the drop +// method will close the socket. #[derive(Clone)] pub struct TcpStream(Arc); -- cgit 1.4.1-3-g733a5 From 76f1581a25a27029279bb5eac17971ba68df1dbe Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 10:05:14 +0200 Subject: remove obsolete , to pass the format check --- src/libstd/sys/hermit/net.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 9146dfc55f4..9e588c4265a 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -154,7 +154,7 @@ impl TcpStream { Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); - }, + } }; Ok(saddr) @@ -234,7 +234,7 @@ impl TcpListener { Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "accept failed")); - }, + } }; Ok((TcpStream(Arc::new(Socket(handle))), saddr)) -- cgit 1.4.1-3-g733a5