diff options
Diffstat (limited to 'src/libstd/sys_common')
| -rw-r--r-- | src/libstd/sys_common/alloc.rs | 30 | ||||
| -rw-r--r-- | src/libstd/sys_common/bytestring.rs | 4 | ||||
| -rw-r--r-- | src/libstd/sys_common/fs.rs | 14 | ||||
| -rw-r--r-- | src/libstd/sys_common/io.rs | 2 | ||||
| -rw-r--r-- | src/libstd/sys_common/net.rs | 256 | ||||
| -rw-r--r-- | src/libstd/sys_common/os_str_bytes.rs | 15 | ||||
| -rw-r--r-- | src/libstd/sys_common/poison.rs | 44 | ||||
| -rw-r--r-- | src/libstd/sys_common/process.rs | 14 | ||||
| -rw-r--r-- | src/libstd/sys_common/thread_info.rs | 28 | ||||
| -rw-r--r-- | src/libstd/sys_common/util.rs | 10 | ||||
| -rw-r--r-- | src/libstd/sys_common/wtf8.rs | 243 |
11 files changed, 346 insertions, 314 deletions
diff --git a/src/libstd/sys_common/alloc.rs b/src/libstd/sys_common/alloc.rs index 1cfc7ed17f2..713b9949f64 100644 --- a/src/libstd/sys_common/alloc.rs +++ b/src/libstd/sys_common/alloc.rs @@ -6,20 +6,24 @@ use crate::ptr; // The minimum alignment guaranteed by the architecture. This value is used to // add fast paths for low alignment values. -#[cfg(all(any(target_arch = "x86", - target_arch = "arm", - target_arch = "mips", - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "asmjs", - target_arch = "wasm32", - target_arch = "hexagon")))] +#[cfg(all(any( + target_arch = "x86", + target_arch = "arm", + target_arch = "mips", + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "asmjs", + target_arch = "wasm32", + target_arch = "hexagon" +)))] pub const MIN_ALIGN: usize = 8; -#[cfg(all(any(target_arch = "x86_64", - target_arch = "aarch64", - target_arch = "mips64", - target_arch = "s390x", - target_arch = "sparc64")))] +#[cfg(all(any( + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "mips64", + target_arch = "s390x", + target_arch = "sparc64" +)))] pub const MIN_ALIGN: usize = 16; pub unsafe fn realloc_fallback( diff --git a/src/libstd/sys_common/bytestring.rs b/src/libstd/sys_common/bytestring.rs index 429ecf6281b..dccc3bc4a19 100644 --- a/src/libstd/sys_common/bytestring.rs +++ b/src/libstd/sys_common/bytestring.rs @@ -25,7 +25,7 @@ pub fn debug_fmt_bytestring(slice: &[u8], f: &mut Formatter<'_>) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::fmt::{Formatter, Result, Debug}; + use crate::fmt::{Debug, Formatter, Result}; #[test] fn smoke() { @@ -37,7 +37,7 @@ mod tests { } } - let input = b"\xF0hello,\tworld"; + let input = b"\xF0hello,\tworld"; let expected = r#""\xF0hello,\tworld""#; let output = format!("{:?}", Helper(input)); diff --git a/src/libstd/sys_common/fs.rs b/src/libstd/sys_common/fs.rs index 7152fcd215c..e30e8018a31 100644 --- a/src/libstd/sys_common/fs.rs +++ b/src/libstd/sys_common/fs.rs @@ -1,13 +1,15 @@ #![allow(dead_code)] // not used on all platforms -use crate::path::Path; use crate::fs; use crate::io::{self, Error, ErrorKind}; +use crate::path::Path; pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { if !from.is_file() { - return Err(Error::new(ErrorKind::InvalidInput, - "the source path is not an existing regular file")) + return Err(Error::new( + ErrorKind::InvalidInput, + "the source path is not an existing regular file", + )); } let mut reader = fs::File::open(from)?; @@ -21,11 +23,7 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { pub fn remove_dir_all(path: &Path) -> io::Result<()> { let filetype = fs::symlink_metadata(path)?.file_type(); - if filetype.is_symlink() { - fs::remove_file(path) - } else { - remove_dir_all_recursive(path) - } + if filetype.is_symlink() { fs::remove_file(path) } else { remove_dir_all_recursive(path) } } fn remove_dir_all_recursive(path: &Path) -> io::Result<()> { diff --git a/src/libstd/sys_common/io.rs b/src/libstd/sys_common/io.rs index 8789abe55c3..7c1d98a5abd 100644 --- a/src/libstd/sys_common/io.rs +++ b/src/libstd/sys_common/io.rs @@ -3,9 +3,9 @@ pub const DEFAULT_BUF_SIZE: usize = 8 * 1024; #[cfg(test)] #[allow(dead_code)] // not used on emscripten pub mod test { - use crate::path::{Path, PathBuf}; use crate::env; use crate::fs; + use crate::path::{Path, PathBuf}; use rand::RngCore; pub struct TempDir(PathBuf); diff --git a/src/libstd/sys_common/net.rs b/src/libstd/sys_common/net.rs index 391f670346f..9d40d9f0afd 100644 --- a/src/libstd/sys_common/net.rs +++ b/src/libstd/sys_common/net.rs @@ -1,79 +1,119 @@ use crate::cmp; +use crate::convert::{TryFrom, TryInto}; use crate::ffi::CString; use crate::fmt; use crate::io::{self, Error, ErrorKind, IoSlice, IoSliceMut}; use crate::mem; -use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr}; +use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use crate::ptr; -use crate::sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t}; use crate::sys::net::netc as c; +use crate::sys::net::{cvt, cvt_gai, cvt_r, init, wrlen_t, Socket}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; -use crate::convert::{TryFrom, TryInto}; use libc::{c_int, c_void}; -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd", target_os = "netbsd", - target_os = "solaris", target_os = "haiku", target_os = "l4re"))] -use crate::sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP; -#[cfg(not(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd", target_os = "netbsd", - target_os = "solaris", target_os = "haiku", target_os = "l4re")))] +#[cfg(not(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re" +)))] use crate::sys::net::netc::IPV6_ADD_MEMBERSHIP; -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd", target_os = "netbsd", - target_os = "solaris", target_os = "haiku", target_os = "l4re"))] -use crate::sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP; -#[cfg(not(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd", target_os = "netbsd", - target_os = "solaris", target_os = "haiku", target_os = "l4re")))] +#[cfg(not(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re" +)))] use crate::sys::net::netc::IPV6_DROP_MEMBERSHIP; +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re" +))] +use crate::sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP; +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "haiku", + target_os = "l4re" +))] +use crate::sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP; -#[cfg(any(target_os = "linux", target_os = "android", - target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd", target_os = "netbsd", - target_os = "haiku"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "haiku" +))] use libc::MSG_NOSIGNAL; -#[cfg(not(any(target_os = "linux", target_os = "android", - target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd", target_os = "netbsd", - target_os = "haiku")))] +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "haiku" +)))] const MSG_NOSIGNAL: c_int = 0x0; //////////////////////////////////////////////////////////////////////////////// // sockaddr and misc bindings //////////////////////////////////////////////////////////////////////////////// -pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int, - payload: T) -> io::Result<()> { +pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int, payload: T) -> io::Result<()> { unsafe { let payload = &payload as *const T as *const c_void; - cvt(c::setsockopt(*sock.as_inner(), opt, val, payload, - mem::size_of::<T>() as c::socklen_t))?; + cvt(c::setsockopt( + *sock.as_inner(), + opt, + val, + payload, + mem::size_of::<T>() as c::socklen_t, + ))?; Ok(()) } } -pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int, - val: c_int) -> io::Result<T> { +pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int, val: c_int) -> io::Result<T> { unsafe { let mut slot: T = mem::zeroed(); let mut len = mem::size_of::<T>() as c::socklen_t; - cvt(c::getsockopt(*sock.as_inner(), opt, val, - &mut slot as *mut _ as *mut _, - &mut len))?; + cvt(c::getsockopt(*sock.as_inner(), opt, val, &mut slot as *mut _ as *mut _, &mut len))?; assert_eq!(len as usize, mem::size_of::<T>()); Ok(slot) } } fn sockname<F>(f: F) -> io::Result<SocketAddr> - where F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int +where + F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int, { unsafe { let mut storage: c::sockaddr_storage = mem::zeroed(); @@ -83,8 +123,7 @@ fn sockname<F>(f: F) -> io::Result<SocketAddr> } } -pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, - len: usize) -> io::Result<SocketAddr> { +pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, len: usize) -> io::Result<SocketAddr> { match storage.ss_family as c_int { c::AF_INET => { assert!(len as usize >= mem::size_of::<c::sockaddr_in>()); @@ -98,9 +137,7 @@ pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, *(storage as *const _ as *const c::sockaddr_in6) }))) } - _ => { - Err(Error::new(ErrorKind::InvalidInput, "invalid argument")) - } + _ => Err(Error::new(ErrorKind::InvalidInput, "invalid argument")), } } @@ -121,7 +158,7 @@ fn to_ipv6mr_interface(value: u32) -> libc::c_uint { pub struct LookupHost { original: *mut c::addrinfo, cur: *mut c::addrinfo, - port: u16 + port: u16, } impl LookupHost { @@ -137,9 +174,7 @@ impl Iterator for LookupHost { unsafe { let cur = self.cur.as_ref()?; self.cur = cur.ai_next; - match sockaddr_to_addr(mem::transmute(cur.ai_addr), - cur.ai_addrlen as usize) - { + match sockaddr_to_addr(mem::transmute(cur.ai_addr), cur.ai_addrlen as usize) { Ok(addr) => return Some(addr), Err(_) => continue, } @@ -162,13 +197,12 @@ impl TryFrom<&str> for LookupHost { fn try_from(s: &str) -> io::Result<LookupHost> { macro_rules! try_opt { - ($e:expr, $msg:expr) => ( + ($e:expr, $msg:expr) => { match $e { Some(r) => r, - None => return Err(io::Error::new(io::ErrorKind::InvalidInput, - $msg)), + None => return Err(io::Error::new(io::ErrorKind::InvalidInput, $msg)), } - ) + }; } // split the string by ':' and convert the second part to u16 @@ -192,9 +226,8 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost { hints.ai_socktype = c::SOCK_STREAM; let mut res = ptr::null_mut(); unsafe { - cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)).map(|_| { - LookupHost { original: res, cur: res, port } - }) + cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)) + .map(|_| LookupHost { original: res, cur: res, port }) } } } @@ -228,9 +261,13 @@ impl TcpStream { Ok(TcpStream { inner: sock }) } - pub fn socket(&self) -> &Socket { &self.inner } + pub fn socket(&self) -> &Socket { + &self.inner + } - pub fn into_socket(self) -> Socket { self.inner } + pub fn into_socket(self) -> Socket { + self.inner + } pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { self.inner.set_timeout(dur, c::SO_RCVTIMEO) @@ -263,10 +300,7 @@ impl TcpStream { pub fn write(&self, buf: &[u8]) -> io::Result<usize> { let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t; let ret = cvt(unsafe { - c::send(*self.inner.as_inner(), - buf.as_ptr() as *const c_void, - len, - MSG_NOSIGNAL) + c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL) })?; Ok(ret as usize) } @@ -276,15 +310,11 @@ impl TcpStream { } pub fn peer_addr(&self) -> io::Result<SocketAddr> { - sockname(|buf, len| unsafe { - c::getpeername(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getpeername(*self.inner.as_inner(), buf, len) }) } pub fn socket_addr(&self) -> io::Result<SocketAddr> { - sockname(|buf, len| unsafe { - c::getsockname(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) }) } pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { @@ -339,9 +369,8 @@ impl fmt::Debug for TcpStream { res.field("peer", &peer); } - let name = if cfg!(windows) {"socket"} else {"fd"}; - res.field(name, &self.inner.as_inner()) - .finish() + let name = if cfg!(windows) { "socket" } else { "fd" }; + res.field(name, &self.inner.as_inner()).finish() } } @@ -365,8 +394,7 @@ impl TcpListener { // to quickly rebind a socket, without needing to wait for // the OS to clean up the previous one. if !cfg!(windows) { - setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, - 1 as c_int)?; + setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, 1 as c_int)?; } // Bind our new socket @@ -378,23 +406,24 @@ impl TcpListener { Ok(TcpListener { inner: sock }) } - pub fn socket(&self) -> &Socket { &self.inner } + pub fn socket(&self) -> &Socket { + &self.inner + } - pub fn into_socket(self) -> Socket { self.inner } + pub fn into_socket(self) -> Socket { + self.inner + } pub fn socket_addr(&self) -> io::Result<SocketAddr> { - sockname(|buf, len| unsafe { - c::getsockname(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) }) } pub 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)?; + let sock = self.inner.accept(&mut storage as *mut _ as *mut _, &mut len)?; let addr = sockaddr_to_addr(&storage, len as usize)?; - Ok((TcpStream { inner: sock, }, addr)) + Ok((TcpStream { inner: sock }, addr)) } pub fn duplicate(&self) -> io::Result<TcpListener> { @@ -442,9 +471,8 @@ impl fmt::Debug for TcpListener { res.field("addr", &addr); } - let name = if cfg!(windows) {"socket"} else {"fd"}; - res.field(name, &self.inner.as_inner()) - .finish() + let name = if cfg!(windows) { "socket" } else { "fd" }; + res.field(name, &self.inner.as_inner()).finish() } } @@ -468,20 +496,20 @@ impl UdpSocket { Ok(UdpSocket { inner: sock }) } - pub fn socket(&self) -> &Socket { &self.inner } + pub fn socket(&self) -> &Socket { + &self.inner + } - pub fn into_socket(self) -> Socket { self.inner } + pub fn into_socket(self) -> Socket { + self.inner + } pub fn peer_addr(&self) -> io::Result<SocketAddr> { - sockname(|buf, len| unsafe { - c::getpeername(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getpeername(*self.inner.as_inner(), buf, len) }) } pub fn socket_addr(&self) -> io::Result<SocketAddr> { - sockname(|buf, len| unsafe { - c::getsockname(*self.inner.as_inner(), buf, len) - }) + sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) }) } pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { @@ -496,9 +524,14 @@ impl UdpSocket { let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t; let (dstp, dstlen) = dst.into_inner(); let ret = cvt(unsafe { - c::sendto(*self.inner.as_inner(), - buf.as_ptr() as *const c_void, len, - MSG_NOSIGNAL, dstp, dstlen) + c::sendto( + *self.inner.as_inner(), + buf.as_ptr() as *const c_void, + len, + MSG_NOSIGNAL, + dstp, + dstlen, + ) })?; Ok(ret as usize) } @@ -559,8 +592,7 @@ impl UdpSocket { Ok(raw != 0) } - pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) - -> io::Result<()> { + pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { let mreq = c::ip_mreq { imr_multiaddr: *multiaddr.as_inner(), imr_interface: *interface.as_inner(), @@ -568,8 +600,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 fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { let mreq = c::ipv6_mreq { ipv6mr_multiaddr: *multiaddr.as_inner(), ipv6mr_interface: to_ipv6mr_interface(interface), @@ -577,8 +608,7 @@ 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 fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { let mreq = c::ip_mreq { imr_multiaddr: *multiaddr.as_inner(), imr_interface: *interface.as_inner(), @@ -586,8 +616,7 @@ 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 fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { let mreq = c::ipv6_mreq { ipv6mr_multiaddr: *multiaddr.as_inner(), ipv6mr_interface: to_ipv6mr_interface(interface), @@ -623,10 +652,7 @@ impl UdpSocket { pub fn send(&self, buf: &[u8]) -> io::Result<usize> { let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t; let ret = cvt(unsafe { - c::send(*self.inner.as_inner(), - buf.as_ptr() as *const c_void, - len, - MSG_NOSIGNAL) + c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL) })?; Ok(ret as usize) } @@ -651,9 +677,8 @@ impl fmt::Debug for UdpSocket { res.field("addr", &addr); } - let name = if cfg!(windows) {"socket"} else {"fd"}; - res.field(name, &self.inner.as_inner()) - .finish() + let name = if cfg!(windows) { "socket" } else { "fd" }; + res.field(name, &self.inner.as_inner()).finish() } } @@ -667,10 +692,15 @@ mod tests { let mut addrs = HashMap::new(); let lh = match LookupHost::try_from(("localhost", 0)) { Ok(lh) => lh, - Err(e) => panic!("couldn't resolve `localhost': {}", e) + Err(e) => panic!("couldn't resolve `localhost': {}", e), }; - for sa in lh { *addrs.entry(sa).or_insert(0) += 1; }; - assert_eq!(addrs.iter().filter(|&(_, &v)| v > 1).collect::<Vec<_>>(), vec![], - "There should be no duplicate localhost entries"); + for sa in lh { + *addrs.entry(sa).or_insert(0) += 1; + } + assert_eq!( + addrs.iter().filter(|&(_, &v)| v > 1).collect::<Vec<_>>(), + vec![], + "There should be no duplicate localhost entries" + ); } } diff --git a/src/libstd/sys_common/os_str_bytes.rs b/src/libstd/sys_common/os_str_bytes.rs index 3753269adfe..a2608ad4000 100644 --- a/src/libstd/sys_common/os_str_bytes.rs +++ b/src/libstd/sys_common/os_str_bytes.rs @@ -4,18 +4,18 @@ use crate::borrow::Cow; use crate::ffi::{OsStr, OsString}; use crate::fmt; -use crate::str; use crate::mem; use crate::rc::Rc; +use crate::str; use crate::sync::Arc; -use crate::sys_common::{FromInner, IntoInner, AsInner}; use crate::sys_common::bytestring::debug_fmt_bytestring; +use crate::sys_common::{AsInner, FromInner, IntoInner}; use core::str::lossy::Utf8Lossy; #[derive(Clone, Hash)] pub(crate) struct Buf { - pub inner: Vec<u8> + pub inner: Vec<u8>, } // FIXME: @@ -25,7 +25,7 @@ pub(crate) struct Buf { // Anyway, `Slice` representation and layout are considered implementation detail, are // not documented and must not be relied upon. pub(crate) struct Slice { - pub inner: [u8] + pub inner: [u8], } impl fmt::Debug for Slice { @@ -64,7 +64,6 @@ impl AsInner<[u8]> for Buf { } } - impl Buf { pub fn from_string(s: String) -> Buf { Buf { inner: s.into_bytes() } @@ -72,9 +71,7 @@ impl Buf { #[inline] pub fn with_capacity(capacity: usize) -> Buf { - Buf { - inner: Vec::with_capacity(capacity) - } + Buf { inner: Vec::with_capacity(capacity) } } #[inline] @@ -112,7 +109,7 @@ impl Buf { } pub fn into_string(self) -> Result<String, Buf> { - String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } ) + String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() }) } pub fn push_slice(&mut self, s: &Slice) { diff --git a/src/libstd/sys_common/poison.rs b/src/libstd/sys_common/poison.rs index adac45f2d59..0157b952996 100644 --- a/src/libstd/sys_common/poison.rs +++ b/src/libstd/sys_common/poison.rs @@ -1,9 +1,11 @@ -use crate::error::{Error}; +use crate::error::Error; use crate::fmt; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::thread; -pub struct Flag { failed: AtomicBool } +pub struct Flag { + failed: AtomicBool, +} // Note that the Ordering uses to access the `failed` field of `Flag` below is // always `Relaxed`, and that's because this isn't actually protecting any data, @@ -24,11 +26,7 @@ impl Flag { #[inline] pub fn borrow(&self) -> LockResult<Guard> { let ret = Guard { panicking: thread::panicking() }; - if self.get() { - Err(PoisonError::new(ret)) - } else { - Ok(ret) - } + if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) } } #[inline] @@ -192,17 +190,23 @@ impl<T> PoisonError<T> { /// println!("recovered {} items", data.len()); /// ``` #[stable(feature = "sync_poison", since = "1.2.0")] - pub fn into_inner(self) -> T { self.guard } + pub fn into_inner(self) -> T { + self.guard + } /// Reaches into this error indicating that a lock is poisoned, returning a /// reference to the underlying guard to allow access regardless. #[stable(feature = "sync_poison", since = "1.2.0")] - pub fn get_ref(&self) -> &T { &self.guard } + pub fn get_ref(&self) -> &T { + &self.guard + } /// Reaches into this error indicating that a lock is poisoned, returning a /// mutable reference to the underlying guard to allow access regardless. #[stable(feature = "sync_poison", since = "1.2.0")] - pub fn get_mut(&mut self) -> &mut T { &mut self.guard } + pub fn get_mut(&mut self) -> &mut T { + &mut self.guard + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -217,7 +221,7 @@ impl<T> fmt::Debug for TryLockError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f), - TryLockError::WouldBlock => "WouldBlock".fmt(f) + TryLockError::WouldBlock => "WouldBlock".fmt(f), } } } @@ -227,8 +231,9 @@ impl<T> fmt::Display for TryLockError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { TryLockError::Poisoned(..) => "poisoned lock: another task failed inside", - TryLockError::WouldBlock => "try_lock failed because the operation would block" - }.fmt(f) + TryLockError::WouldBlock => "try_lock failed because the operation would block", + } + .fmt(f) } } @@ -237,23 +242,24 @@ impl<T> Error for TryLockError<T> { fn description(&self) -> &str { match *self { TryLockError::Poisoned(ref p) => p.description(), - TryLockError::WouldBlock => "try_lock failed because the operation would block" + TryLockError::WouldBlock => "try_lock failed because the operation would block", } } fn cause(&self) -> Option<&dyn Error> { match *self { TryLockError::Poisoned(ref p) => Some(p), - _ => None + _ => None, } } } -pub fn map_result<T, U, F>(result: LockResult<T>, f: F) - -> LockResult<U> - where F: FnOnce(T) -> U { +pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U> +where + F: FnOnce(T) -> U, +{ match result { Ok(t) => Ok(f(t)), - Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))) + Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))), } } diff --git a/src/libstd/sys_common/process.rs b/src/libstd/sys_common/process.rs index bdf66fca359..55b421794c4 100644 --- a/src/libstd/sys_common/process.rs +++ b/src/libstd/sys_common/process.rs @@ -11,16 +11,12 @@ use crate::sys::process::EnvKey; pub struct CommandEnv { clear: bool, saw_path: bool, - vars: BTreeMap<EnvKey, Option<OsString>> + vars: BTreeMap<EnvKey, Option<OsString>>, } impl Default for CommandEnv { fn default() -> Self { - CommandEnv { - clear: false, - saw_path: false, - vars: Default::default() - } + CommandEnv { clear: false, saw_path: false, vars: Default::default() } } } @@ -64,11 +60,7 @@ impl CommandEnv { } pub fn capture_if_changed(&self) -> Option<BTreeMap<EnvKey, OsString>> { - if self.is_unchanged() { - None - } else { - Some(self.capture()) - } + if self.is_unchanged() { None } else { Some(self.capture()) } } // The following functions build up changes diff --git a/src/libstd/sys_common/thread_info.rs b/src/libstd/sys_common/thread_info.rs index b3c21ec508a..f09d16c33e6 100644 --- a/src/libstd/sys_common/thread_info.rs +++ b/src/libstd/sys_common/thread_info.rs @@ -12,16 +12,19 @@ struct ThreadInfo { thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = RefCell::new(None) } impl ThreadInfo { - fn with<R, F>(f: F) -> Option<R> where F: FnOnce(&mut ThreadInfo) -> R { - THREAD_INFO.try_with(move |c| { - if c.borrow().is_none() { - *c.borrow_mut() = Some(ThreadInfo { - stack_guard: None, - thread: Thread::new(None), - }) - } - f(c.borrow_mut().as_mut().unwrap()) - }).ok() + fn with<R, F>(f: F) -> Option<R> + where + F: FnOnce(&mut ThreadInfo) -> R, + { + THREAD_INFO + .try_with(move |c| { + if c.borrow().is_none() { + *c.borrow_mut() = + Some(ThreadInfo { stack_guard: None, thread: Thread::new(None) }) + } + f(c.borrow_mut().as_mut().unwrap()) + }) + .ok() } } @@ -35,10 +38,7 @@ pub fn stack_guard() -> Option<Guard> { pub fn set(stack_guard: Option<Guard>, thread: Thread) { THREAD_INFO.with(|c| assert!(c.borrow().is_none())); - THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo{ - stack_guard, - thread, - })); + THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo { stack_guard, thread })); } pub fn reset_guard(stack_guard: Option<Guard>) { diff --git a/src/libstd/sys_common/util.rs b/src/libstd/sys_common/util.rs index 7936dd35999..00f7db4c037 100644 --- a/src/libstd/sys_common/util.rs +++ b/src/libstd/sys_common/util.rs @@ -16,11 +16,15 @@ pub fn dumb_print(args: fmt::Arguments<'_>) { pub fn abort(args: fmt::Arguments<'_>) -> ! { dumb_print(format_args!("fatal runtime error: {}\n", args)); - unsafe { crate::sys::abort_internal(); } + unsafe { + crate::sys::abort_internal(); + } } #[allow(dead_code)] // stack overflow detection not enabled on all platforms pub unsafe fn report_overflow() { - dumb_print(format_args!("\nthread '{}' has overflowed its stack\n", - thread::current().name().unwrap_or("<unknown>"))); + dumb_print(format_args!( + "\nthread '{}' has overflowed its stack\n", + thread::current().name().unwrap_or("<unknown>") + )); } diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index 81e606fc165..1d96cdfe460 100644 --- a/src/libstd/sys_common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs @@ -39,7 +39,7 @@ const UTF8_REPLACEMENT_CHARACTER: &str = "\u{FFFD}"; /// a code point that is not a surrogate (U+D800 to U+DFFF). #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)] pub struct CodePoint { - value: u32 + value: u32, } /// Format the code point as `U+` followed by four to six hexadecimal digits. @@ -66,8 +66,8 @@ impl CodePoint { #[inline] pub fn from_u32(value: u32) -> Option<CodePoint> { match value { - 0 ..= 0x10FFFF => Some(CodePoint { value }), - _ => None + 0..=0x10FFFF => Some(CodePoint { value }), + _ => None, } } @@ -91,8 +91,8 @@ impl CodePoint { #[inline] pub fn to_char(&self) -> Option<char> { match self.value { - 0xD800 ..= 0xDFFF => None, - _ => Some(unsafe { char::from_u32_unchecked(self.value) }) + 0xD800..=0xDFFF => None, + _ => Some(unsafe { char::from_u32_unchecked(self.value) }), } } @@ -112,7 +112,7 @@ impl CodePoint { /// if they’re not in a surrogate pair. #[derive(Eq, PartialEq, Ord, PartialOrd, Clone)] pub struct Wtf8Buf { - bytes: Vec<u8> + bytes: Vec<u8>, } impl ops::Deref for Wtf8Buf { @@ -188,9 +188,7 @@ impl Wtf8Buf { Err(surrogate) => { let surrogate = surrogate.unpaired_surrogate(); // Surrogates are known to be in the code point range. - let code_point = unsafe { - CodePoint::from_u32_unchecked(surrogate as u32) - }; + let code_point = unsafe { CodePoint::from_u32_unchecked(surrogate as u32) }; // Skip the WTF-8 concatenation check, // surrogate pairs are already decoded by decode_utf16 string.push_code_point_unchecked(code_point) @@ -203,9 +201,7 @@ impl Wtf8Buf { /// Copied from String::push /// This does **not** include the WTF-8 concatenation check. fn push_code_point_unchecked(&mut self, code_point: CodePoint) { - let c = unsafe { - char::from_u32_unchecked(code_point.value) - }; + let c = unsafe { char::from_u32_unchecked(code_point.value) }; let mut bytes = [0; 4]; let bytes = c.encode_utf8(&mut bytes).as_bytes(); self.bytes.extend_from_slice(bytes) @@ -278,7 +274,7 @@ impl Wtf8Buf { self.push_char(decode_surrogate_pair(lead, trail)); self.bytes.extend_from_slice(other_without_trail_surrogate); } - _ => self.bytes.extend_from_slice(&other.bytes) + _ => self.bytes.extend_from_slice(&other.bytes), } } @@ -300,7 +296,7 @@ impl Wtf8Buf { let len_without_lead_surrogate = self.len() - 3; self.bytes.truncate(len_without_lead_surrogate); self.push_char(decode_surrogate_pair(lead, trail as u16)); - return + return; } } @@ -347,8 +343,8 @@ impl Wtf8Buf { pos = surrogate_pos + 3; self.bytes[surrogate_pos..pos] .copy_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes()); - }, - None => return unsafe { String::from_utf8_unchecked(self.bytes) } + } + None => return unsafe { String::from_utf8_unchecked(self.bytes) }, } } } @@ -371,7 +367,7 @@ impl Wtf8Buf { /// This replaces surrogate code point pairs with supplementary code points, /// like concatenating ill-formed UTF-16 strings effectively would. impl FromIterator<CodePoint> for Wtf8Buf { - fn from_iter<T: IntoIterator<Item=CodePoint>>(iter: T) -> Wtf8Buf { + fn from_iter<T: IntoIterator<Item = CodePoint>>(iter: T) -> Wtf8Buf { let mut string = Wtf8Buf::new(); string.extend(iter); string @@ -383,7 +379,7 @@ impl FromIterator<CodePoint> for Wtf8Buf { /// This replaces surrogate code point pairs with supplementary code points, /// like concatenating ill-formed UTF-16 strings effectively would. impl Extend<CodePoint> for Wtf8Buf { - fn extend<T: IntoIterator<Item=CodePoint>>(&mut self, iter: T) { + fn extend<T: IntoIterator<Item = CodePoint>>(&mut self, iter: T) { let iterator = iter.into_iter(); let (low, _high) = iterator.size_hint(); // Lower bound of one byte per code point (ASCII only) @@ -398,11 +394,13 @@ impl Extend<CodePoint> for Wtf8Buf { /// if they’re not in a surrogate pair. #[derive(Eq, Ord, PartialEq, PartialOrd)] pub struct Wtf8 { - bytes: [u8] + bytes: [u8], } impl AsInner<[u8]> for Wtf8 { - fn as_inner(&self) -> &[u8] { &self.bytes } + fn as_inner(&self) -> &[u8] { + &self.bytes + } } /// Format the slice with double quotes, @@ -421,19 +419,13 @@ impl fmt::Debug for Wtf8 { formatter.write_str("\"")?; let mut pos = 0; while let Some((surrogate_pos, surrogate)) = self.next_surrogate(pos) { - write_str_escaped( - formatter, - unsafe { str::from_utf8_unchecked( - &self.bytes[pos .. surrogate_pos] - )}, - )?; + write_str_escaped(formatter, unsafe { + str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos]) + })?; write!(formatter, "\\u{{{:x}}}", surrogate)?; pos = surrogate_pos + 3; } - write_str_escaped( - formatter, - unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) }, - )?; + write_str_escaped(formatter, unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?; formatter.write_str("\"") } } @@ -446,20 +438,14 @@ impl fmt::Display for Wtf8 { match self.next_surrogate(pos) { Some((surrogate_pos, _)) => { formatter.write_str(unsafe { - str::from_utf8_unchecked(&wtf8_bytes[pos .. surrogate_pos]) + str::from_utf8_unchecked(&wtf8_bytes[pos..surrogate_pos]) })?; formatter.write_str(UTF8_REPLACEMENT_CHARACTER)?; pos = surrogate_pos + 3; - }, + } None => { - let s = unsafe { - str::from_utf8_unchecked(&wtf8_bytes[pos..]) - }; - if pos == 0 { - return s.fmt(formatter) - } else { - return formatter.write_str(s) - } + let s = unsafe { str::from_utf8_unchecked(&wtf8_bytes[pos..]) }; + if pos == 0 { return s.fmt(formatter) } else { return formatter.write_str(s) } } } } @@ -513,8 +499,8 @@ impl Wtf8 { #[inline] pub fn ascii_byte_at(&self, position: usize) -> u8 { match self.bytes[position] { - ascii_byte @ 0x00 ..= 0x7F => ascii_byte, - _ => 0xFF + ascii_byte @ 0x00..=0x7F => ascii_byte, + _ => 0xFF, } } @@ -558,13 +544,13 @@ impl Wtf8 { loop { match self.next_surrogate(pos) { Some((surrogate_pos, _)) => { - utf8_bytes.extend_from_slice(&wtf8_bytes[pos .. surrogate_pos]); + utf8_bytes.extend_from_slice(&wtf8_bytes[pos..surrogate_pos]); utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes()); pos = surrogate_pos + 3; - }, + } None => { utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]); - return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) }) + return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) }); } } } @@ -594,9 +580,9 @@ impl Wtf8 { } else if b == 0xED { match (iter.next(), iter.next()) { (Some(&b2), Some(&b3)) if b2 >= 0xA0 => { - return Some((pos, decode_surrogate(b2, b3))) + return Some((pos, decode_surrogate(b2, b3))); } - _ => pos += 3 + _ => pos += 3, } } else if b < 0xF0 { iter.next(); @@ -615,11 +601,11 @@ impl Wtf8 { fn final_lead_surrogate(&self) -> Option<u16> { let len = self.len(); if len < 3 { - return None + return None; } match &self.bytes[(len - 3)..] { &[0xED, b2 @ 0xA0..=0xAF, b3] => Some(decode_surrogate(b2, b3)), - _ => None + _ => None, } } @@ -627,11 +613,11 @@ impl Wtf8 { fn initial_trail_surrogate(&self) -> Option<u16> { let len = self.len(); if len < 3 { - return None + return None; } match &self.bytes[..3] { &[0xED, b2 @ 0xB0..=0xBF, b3] => Some(decode_surrogate(b2, b3)), - _ => None + _ => None, } } @@ -661,7 +647,6 @@ impl Wtf8 { } } - /// Returns a slice of the given string for the byte range [`begin`..`end`). /// /// # Panics @@ -674,9 +659,10 @@ impl ops::Index<ops::Range<usize>> for Wtf8 { #[inline] fn index(&self, range: ops::Range<usize>) -> &Wtf8 { // is_code_point_boundary checks that the index is in [0, .len()] - if range.start <= range.end && - is_code_point_boundary(self, range.start) && - is_code_point_boundary(self, range.end) { + if range.start <= range.end + && is_code_point_boundary(self, range.start) + && is_code_point_boundary(self, range.end) + { unsafe { slice_unchecked(self, range.start, range.end) } } else { slice_error_fail(self, range.start, range.end) @@ -748,7 +734,9 @@ fn decode_surrogate_pair(lead: u16, trail: u16) -> char { /// Copied from core::str::StrPrelude::is_char_boundary #[inline] pub fn is_code_point_boundary(slice: &Wtf8, index: usize) -> bool { - if index == slice.len() { return true; } + if index == slice.len() { + return true; + } match slice.bytes.get(index) { None => false, Some(&b) => b < 128 || b >= 192, @@ -759,18 +747,14 @@ pub fn is_code_point_boundary(slice: &Wtf8, index: usize) -> bool { #[inline] pub unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 { // memory layout of an &[u8] and &Wtf8 are the same - Wtf8::from_bytes_unchecked(slice::from_raw_parts( - s.bytes.as_ptr().add(begin), - end - begin - )) + Wtf8::from_bytes_unchecked(slice::from_raw_parts(s.bytes.as_ptr().add(begin), end - begin)) } /// Copied from core::str::raw::slice_error_fail #[inline(never)] pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! { assert!(begin <= end); - panic!("index {} and/or {} in `{:?}` do not lie on character boundary", - begin, end, s); + panic!("index {} and/or {} in `{:?}` do not lie on character boundary", begin, end, s); } /// Iterator for the code points of a WTF-8 string. @@ -778,7 +762,7 @@ pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! { /// Created with the method `.code_points()`. #[derive(Clone)] pub struct Wtf8CodePoints<'a> { - bytes: slice::Iter<'a, u8> + bytes: slice::Iter<'a, u8>, } impl<'a> Iterator for Wtf8CodePoints<'a> { @@ -801,7 +785,7 @@ impl<'a> Iterator for Wtf8CodePoints<'a> { #[derive(Clone)] pub struct EncodeWide<'a> { code_points: Wtf8CodePoints<'a>, - extra: u16 + extra: u16, } // Copied from libunicode/u_str.rs @@ -819,9 +803,7 @@ impl<'a> Iterator for EncodeWide<'a> { let mut buf = [0; 2]; self.code_points.next().map(|code_point| { - let c = unsafe { - char::from_u32_unchecked(code_point.value) - }; + let c = unsafe { char::from_u32_unchecked(code_point.value) }; let n = c.encode_utf16(&mut buf).len(); if n == 2 { self.extra = buf[1]; @@ -864,13 +846,15 @@ impl Hash for Wtf8 { } impl Wtf8 { - pub fn make_ascii_uppercase(&mut self) { self.bytes.make_ascii_uppercase() } + pub fn make_ascii_uppercase(&mut self) { + self.bytes.make_ascii_uppercase() + } } #[cfg(test)] mod tests { - use crate::borrow::Cow; use super::*; + use crate::borrow::Cow; #[test] fn code_point_from_u32() { @@ -882,7 +866,9 @@ mod tests { #[test] fn code_point_to_u32() { - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } assert_eq!(c(0).to_u32(), 0); assert_eq!(c(0xD800).to_u32(), 0xD800); assert_eq!(c(0x10FFFF).to_u32(), 0x10FFFF); @@ -902,7 +888,9 @@ mod tests { #[test] fn code_point_to_char() { - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } assert_eq!(c(0x61).to_char(), Some('a')); assert_eq!(c(0x1F4A9).to_char(), Some('💩')); assert_eq!(c(0xD800).to_char(), None); @@ -910,7 +898,9 @@ mod tests { #[test] fn code_point_to_char_lossy() { - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } assert_eq!(c(0x61).to_char_lossy(), 'a'); assert_eq!(c(0x1F4A9).to_char_lossy(), '💩'); assert_eq!(c(0xD800).to_char_lossy(), '\u{FFFD}'); @@ -924,23 +914,25 @@ mod tests { #[test] fn wtf8buf_from_str() { assert_eq!(Wtf8Buf::from_str("").bytes, b""); - assert_eq!(Wtf8Buf::from_str("aé 💩").bytes, - b"a\xC3\xA9 \xF0\x9F\x92\xA9"); + assert_eq!(Wtf8Buf::from_str("aé 💩").bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); } #[test] fn wtf8buf_from_string() { assert_eq!(Wtf8Buf::from_string(String::from("")).bytes, b""); - assert_eq!(Wtf8Buf::from_string(String::from("aé 💩")).bytes, - b"a\xC3\xA9 \xF0\x9F\x92\xA9"); + assert_eq!( + Wtf8Buf::from_string(String::from("aé 💩")).bytes, + b"a\xC3\xA9 \xF0\x9F\x92\xA9" + ); } #[test] fn wtf8buf_from_wide() { assert_eq!(Wtf8Buf::from_wide(&[]).bytes, b""); - assert_eq!(Wtf8Buf::from_wide( - &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes, - b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9"); + assert_eq!( + Wtf8Buf::from_wide(&[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes, + b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9" + ); } #[test] @@ -966,41 +958,43 @@ mod tests { string.push(CodePoint::from_char('💩')); assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } let mut string = Wtf8Buf::new(); - string.push(c(0xD83D)); // lead - string.push(c(0xDCA9)); // trail - assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic! + string.push(c(0xD83D)); // lead + string.push(c(0xDCA9)); // trail + assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic! let mut string = Wtf8Buf::new(); - string.push(c(0xD83D)); // lead - string.push(c(0x20)); // not surrogate - string.push(c(0xDCA9)); // trail + string.push(c(0xD83D)); // lead + string.push(c(0x20)); // not surrogate + string.push(c(0xDCA9)); // trail assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9"); let mut string = Wtf8Buf::new(); - string.push(c(0xD800)); // lead - string.push(c(0xDBFF)); // lead + string.push(c(0xD800)); // lead + string.push(c(0xDBFF)); // lead assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF"); let mut string = Wtf8Buf::new(); - string.push(c(0xD800)); // lead - string.push(c(0xE000)); // not surrogate + string.push(c(0xD800)); // lead + string.push(c(0xE000)); // not surrogate assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80"); let mut string = Wtf8Buf::new(); - string.push(c(0xD7FF)); // not surrogate - string.push(c(0xDC00)); // trail + string.push(c(0xD7FF)); // not surrogate + string.push(c(0xDC00)); // trail assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80"); let mut string = Wtf8Buf::new(); - string.push(c(0x61)); // not surrogate, < 3 bytes - string.push(c(0xDC00)); // trail + string.push(c(0x61)); // not surrogate, < 3 bytes + string.push(c(0xDC00)); // trail assert_eq!(string.bytes, b"\x61\xED\xB0\x80"); let mut string = Wtf8Buf::new(); - string.push(c(0xDC00)); // trail + string.push(c(0xDC00)); // trail assert_eq!(string.bytes, b"\xED\xB0\x80"); } @@ -1011,41 +1005,43 @@ mod tests { string.push_wtf8(Wtf8::from_str(" 💩")); assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); - fn w(v: &[u8]) -> &Wtf8 { unsafe { Wtf8::from_bytes_unchecked(v) } } + fn w(v: &[u8]) -> &Wtf8 { + unsafe { Wtf8::from_bytes_unchecked(v) } + } let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xA0\xBD")); // lead - string.push_wtf8(w(b"\xED\xB2\xA9")); // trail - assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic! + string.push_wtf8(w(b"\xED\xA0\xBD")); // lead + string.push_wtf8(w(b"\xED\xB2\xA9")); // trail + assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic! let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xA0\xBD")); // lead - string.push_wtf8(w(b" ")); // not surrogate - string.push_wtf8(w(b"\xED\xB2\xA9")); // trail + string.push_wtf8(w(b"\xED\xA0\xBD")); // lead + string.push_wtf8(w(b" ")); // not surrogate + string.push_wtf8(w(b"\xED\xB2\xA9")); // trail assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xA0\x80")); // lead - string.push_wtf8(w(b"\xED\xAF\xBF")); // lead + string.push_wtf8(w(b"\xED\xA0\x80")); // lead + string.push_wtf8(w(b"\xED\xAF\xBF")); // lead assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xA0\x80")); // lead - string.push_wtf8(w(b"\xEE\x80\x80")); // not surrogate + string.push_wtf8(w(b"\xED\xA0\x80")); // lead + string.push_wtf8(w(b"\xEE\x80\x80")); // not surrogate assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\x9F\xBF")); // not surrogate - string.push_wtf8(w(b"\xED\xB0\x80")); // trail + string.push_wtf8(w(b"\xED\x9F\xBF")); // not surrogate + string.push_wtf8(w(b"\xED\xB0\x80")); // trail assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"a")); // not surrogate, < 3 bytes - string.push_wtf8(w(b"\xED\xB0\x80")); // trail + string.push_wtf8(w(b"a")); // not surrogate, < 3 bytes + string.push_wtf8(w(b"\xED\xB0\x80")); // trail assert_eq!(string.bytes, b"\x61\xED\xB0\x80"); let mut string = Wtf8Buf::new(); - string.push_wtf8(w(b"\xED\xB0\x80")); // trail + string.push_wtf8(w(b"\xED\xB0\x80")); // trail assert_eq!(string.bytes, b"\xED\xB0\x80"); } @@ -1093,7 +1089,7 @@ mod tests { } assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); - assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! + assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9"); assert_eq!(f(&[0xD800, 0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF"); assert_eq!(f(&[0xD800, 0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80"); @@ -1105,16 +1101,17 @@ mod tests { #[test] fn wtf8buf_extend() { fn e(initial: &[u32], extended: &[u32]) -> Wtf8Buf { - fn c(value: &u32) -> CodePoint { CodePoint::from_u32(*value).unwrap() } + fn c(value: &u32) -> CodePoint { + CodePoint::from_u32(*value).unwrap() + } let mut string = initial.iter().map(c).collect::<Wtf8Buf>(); string.extend(extended.iter().map(c)); string } - assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes, - b"a\xC3\xA9 \xF0\x9F\x92\xA9"); + assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9"); - assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! + assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9"); assert_eq!(e(&[0xD800], &[0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF"); assert_eq!(e(&[0xD800], &[0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80"); @@ -1156,13 +1153,13 @@ mod tests { #[test] fn wtf8_slice() { - assert_eq!(&Wtf8::from_str("aé 💩")[1.. 4].bytes, b"\xC3\xA9 "); + assert_eq!(&Wtf8::from_str("aé 💩")[1..4].bytes, b"\xC3\xA9 "); } #[test] #[should_panic] fn wtf8_slice_not_code_point_boundary() { - &Wtf8::from_str("aé 💩")[2.. 4]; + &Wtf8::from_str("aé 💩")[2..4]; } #[test] @@ -1199,7 +1196,9 @@ mod tests { #[test] fn wtf8_code_points() { - fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() } + fn c(value: u32) -> CodePoint { + CodePoint::from_u32(value).unwrap() + } fn cp(string: &Wtf8Buf) -> Vec<Option<char>> { string.code_points().map(|c| c.to_char()).collect::<Vec<_>>() } @@ -1249,7 +1248,9 @@ mod tests { let mut string = Wtf8Buf::from_str("aé "); string.push(CodePoint::from_u32(0xD83D).unwrap()); string.push_char('💩'); - assert_eq!(string.encode_wide().collect::<Vec<_>>(), - vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]); + assert_eq!( + string.encode_wide().collect::<Vec<_>>(), + vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9] + ); } } |
