Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/net/tcp.rs +1083 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/net/test.rs +44 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/net/udp.rs +848 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/num/f128.rs +1086 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/num/f16.rs +1046 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/num/f32.rs +1276 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/num/f64.rs +1276 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/num/mod.rs +28 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/os/mod.rs +198 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/prelude/mod.rs +192 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/prelude/v1.rs +186 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/process/tests.rs +669 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/barrier.rs +167 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/lazy_lock.rs +422 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/mod.rs +307 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/mpsc.rs +1214 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/nonpoison.rs +45 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/once.rs +395 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/once_lock.rs +709 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/oneshot.rs +466 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/poison.rs +389 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/reentrant_lock.rs +432 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/hermit.rs +27 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/mod.rs +110 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/motor.rs +28 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/sgx.rs +99 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/solid.rs +30 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/uefi.rs +49 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/unix.rs +87 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/vexos.rs +96 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/wasm.rs +173 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/windows.rs +216 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/xous.rs +74 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/zkvm.rs +15 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/common.rs +101 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/mod.rs +60 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/motor.rs +13 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/sgx.rs +110 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/uefi.rs +118 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/unix.rs +191 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/unsupported.rs +42 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/wasip1.rs +26 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/wasip2.rs +6 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/windows.rs +410 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/xous.rs +20 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/zkvm.rs +94 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/backtrace.rs +238 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/cmath.rs +114 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/configure_builtins.rs +62 -0
- rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/env/common.rs +31 -0
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/net/tcp.rs
ADDED
|
@@ -0,0 +1,1083 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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::fmt;
|
| 15 |
+
use crate::io::prelude::*;
|
| 16 |
+
use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
|
| 17 |
+
use crate::iter::FusedIterator;
|
| 18 |
+
use crate::net::{Shutdown, SocketAddr, ToSocketAddrs};
|
| 19 |
+
use crate::sys::{AsInner, FromInner, IntoInner, net as net_imp};
|
| 20 |
+
use crate::time::Duration;
|
| 21 |
+
|
| 22 |
+
/// A TCP stream between a local and a remote socket.
|
| 23 |
+
///
|
| 24 |
+
/// After creating a `TcpStream` by either [`connect`]ing to a remote host or
|
| 25 |
+
/// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
|
| 26 |
+
/// by [reading] and [writing] to it.
|
| 27 |
+
///
|
| 28 |
+
/// The connection will be closed when the value is dropped. The reading and writing
|
| 29 |
+
/// portions of the connection can also be shut down individually with the [`shutdown`]
|
| 30 |
+
/// method.
|
| 31 |
+
///
|
| 32 |
+
/// The Transmission Control Protocol is specified in [IETF RFC 793].
|
| 33 |
+
///
|
| 34 |
+
/// [`accept`]: TcpListener::accept
|
| 35 |
+
/// [`connect`]: TcpStream::connect
|
| 36 |
+
/// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
|
| 37 |
+
/// [reading]: Read
|
| 38 |
+
/// [`shutdown`]: TcpStream::shutdown
|
| 39 |
+
/// [writing]: Write
|
| 40 |
+
///
|
| 41 |
+
/// # Examples
|
| 42 |
+
///
|
| 43 |
+
/// ```no_run
|
| 44 |
+
/// use std::io::prelude::*;
|
| 45 |
+
/// use std::net::TcpStream;
|
| 46 |
+
///
|
| 47 |
+
/// fn main() -> std::io::Result<()> {
|
| 48 |
+
/// let mut stream = TcpStream::connect("127.0.0.1:34254")?;
|
| 49 |
+
///
|
| 50 |
+
/// stream.write(&[1])?;
|
| 51 |
+
/// stream.read(&mut [0; 128])?;
|
| 52 |
+
/// Ok(())
|
| 53 |
+
/// } // the stream is closed here
|
| 54 |
+
/// ```
|
| 55 |
+
///
|
| 56 |
+
/// # Platform-specific Behavior
|
| 57 |
+
///
|
| 58 |
+
/// On Unix, writes to the underlying socket in `SOCK_STREAM` mode are made with
|
| 59 |
+
/// `MSG_NOSIGNAL` flag. This suppresses the emission of the `SIGPIPE` signal when writing
|
| 60 |
+
/// to disconnected socket. In some cases, getting a `SIGPIPE` would trigger process termination.
|
| 61 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 62 |
+
pub struct TcpStream(net_imp::TcpStream);
|
| 63 |
+
|
| 64 |
+
/// A TCP socket server, listening for connections.
|
| 65 |
+
///
|
| 66 |
+
/// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
|
| 67 |
+
/// for incoming TCP connections. These can be accepted by calling [`accept`] or by
|
| 68 |
+
/// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
|
| 69 |
+
///
|
| 70 |
+
/// The socket will be closed when the value is dropped.
|
| 71 |
+
///
|
| 72 |
+
/// The Transmission Control Protocol is specified in [IETF RFC 793].
|
| 73 |
+
///
|
| 74 |
+
/// [`accept`]: TcpListener::accept
|
| 75 |
+
/// [`bind`]: TcpListener::bind
|
| 76 |
+
/// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
|
| 77 |
+
///
|
| 78 |
+
/// # Examples
|
| 79 |
+
///
|
| 80 |
+
/// ```no_run
|
| 81 |
+
/// use std::net::{TcpListener, TcpStream};
|
| 82 |
+
///
|
| 83 |
+
/// fn handle_client(stream: TcpStream) {
|
| 84 |
+
/// // ...
|
| 85 |
+
/// }
|
| 86 |
+
///
|
| 87 |
+
/// fn main() -> std::io::Result<()> {
|
| 88 |
+
/// let listener = TcpListener::bind("127.0.0.1:80")?;
|
| 89 |
+
///
|
| 90 |
+
/// // accept connections and process them serially
|
| 91 |
+
/// for stream in listener.incoming() {
|
| 92 |
+
/// handle_client(stream?);
|
| 93 |
+
/// }
|
| 94 |
+
/// Ok(())
|
| 95 |
+
/// }
|
| 96 |
+
/// ```
|
| 97 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 98 |
+
pub struct TcpListener(net_imp::TcpListener);
|
| 99 |
+
|
| 100 |
+
/// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
|
| 101 |
+
///
|
| 102 |
+
/// This `struct` is created by the [`TcpListener::incoming`] method.
|
| 103 |
+
/// See its documentation for more.
|
| 104 |
+
///
|
| 105 |
+
/// [`accept`]: TcpListener::accept
|
| 106 |
+
#[must_use = "iterators are lazy and do nothing unless consumed"]
|
| 107 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 108 |
+
#[derive(Debug)]
|
| 109 |
+
pub struct Incoming<'a> {
|
| 110 |
+
listener: &'a TcpListener,
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
/// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
|
| 114 |
+
///
|
| 115 |
+
/// This `struct` is created by the [`TcpListener::into_incoming`] method.
|
| 116 |
+
/// See its documentation for more.
|
| 117 |
+
///
|
| 118 |
+
/// [`accept`]: TcpListener::accept
|
| 119 |
+
#[derive(Debug)]
|
| 120 |
+
#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
|
| 121 |
+
pub struct IntoIncoming {
|
| 122 |
+
listener: TcpListener,
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
impl TcpStream {
|
| 126 |
+
/// Opens a TCP connection to a remote host.
|
| 127 |
+
///
|
| 128 |
+
/// `addr` is an address of the remote host. Anything which implements
|
| 129 |
+
/// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
|
| 130 |
+
/// documentation for concrete examples.
|
| 131 |
+
///
|
| 132 |
+
/// If `addr` yields multiple addresses, `connect` will be attempted with
|
| 133 |
+
/// each of the addresses until a connection is successful. If none of
|
| 134 |
+
/// the addresses result in a successful connection, the error returned from
|
| 135 |
+
/// the last connection attempt (the last address) is returned.
|
| 136 |
+
///
|
| 137 |
+
/// # Examples
|
| 138 |
+
///
|
| 139 |
+
/// Open a TCP connection to `127.0.0.1:8080`:
|
| 140 |
+
///
|
| 141 |
+
/// ```no_run
|
| 142 |
+
/// use std::net::TcpStream;
|
| 143 |
+
///
|
| 144 |
+
/// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
|
| 145 |
+
/// println!("Connected to the server!");
|
| 146 |
+
/// } else {
|
| 147 |
+
/// println!("Couldn't connect to server...");
|
| 148 |
+
/// }
|
| 149 |
+
/// ```
|
| 150 |
+
///
|
| 151 |
+
/// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
|
| 152 |
+
/// a TCP connection to `127.0.0.1:8081`:
|
| 153 |
+
///
|
| 154 |
+
/// ```no_run
|
| 155 |
+
/// use std::net::{SocketAddr, TcpStream};
|
| 156 |
+
///
|
| 157 |
+
/// let addrs = [
|
| 158 |
+
/// SocketAddr::from(([127, 0, 0, 1], 8080)),
|
| 159 |
+
/// SocketAddr::from(([127, 0, 0, 1], 8081)),
|
| 160 |
+
/// ];
|
| 161 |
+
/// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
|
| 162 |
+
/// println!("Connected to the server!");
|
| 163 |
+
/// } else {
|
| 164 |
+
/// println!("Couldn't connect to server...");
|
| 165 |
+
/// }
|
| 166 |
+
/// ```
|
| 167 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 168 |
+
pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
|
| 169 |
+
net_imp::TcpStream::connect(addr).map(TcpStream)
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
/// Opens a TCP connection to a remote host with a timeout.
|
| 173 |
+
///
|
| 174 |
+
/// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
|
| 175 |
+
/// timeout must be applied to individual addresses.
|
| 176 |
+
///
|
| 177 |
+
/// It is an error to pass a zero `Duration` to this function.
|
| 178 |
+
///
|
| 179 |
+
/// Unlike other methods on `TcpStream`, this does not correspond to a
|
| 180 |
+
/// single system call. It instead calls `connect` in nonblocking mode and
|
| 181 |
+
/// then uses an OS-specific mechanism to await the completion of the
|
| 182 |
+
/// connection request.
|
| 183 |
+
#[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
|
| 184 |
+
pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
|
| 185 |
+
net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
/// Returns the socket address of the remote peer of this TCP connection.
|
| 189 |
+
///
|
| 190 |
+
/// # Examples
|
| 191 |
+
///
|
| 192 |
+
/// ```no_run
|
| 193 |
+
/// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
|
| 194 |
+
///
|
| 195 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 196 |
+
/// .expect("Couldn't connect to the server...");
|
| 197 |
+
/// assert_eq!(stream.peer_addr().unwrap(),
|
| 198 |
+
/// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
|
| 199 |
+
/// ```
|
| 200 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 201 |
+
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
|
| 202 |
+
self.0.peer_addr()
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
/// Returns the socket address of the local half of this TCP connection.
|
| 206 |
+
///
|
| 207 |
+
/// # Examples
|
| 208 |
+
///
|
| 209 |
+
/// ```no_run
|
| 210 |
+
/// use std::net::{IpAddr, Ipv4Addr, TcpStream};
|
| 211 |
+
///
|
| 212 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 213 |
+
/// .expect("Couldn't connect to the server...");
|
| 214 |
+
/// assert_eq!(stream.local_addr().unwrap().ip(),
|
| 215 |
+
/// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
|
| 216 |
+
/// ```
|
| 217 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 218 |
+
pub fn local_addr(&self) -> io::Result<SocketAddr> {
|
| 219 |
+
self.0.socket_addr()
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
/// Shuts down the read, write, or both halves of this connection.
|
| 223 |
+
///
|
| 224 |
+
/// This function will cause all pending and future I/O on the specified
|
| 225 |
+
/// portions to return immediately with an appropriate value (see the
|
| 226 |
+
/// documentation of [`Shutdown`]).
|
| 227 |
+
///
|
| 228 |
+
/// # Platform-specific behavior
|
| 229 |
+
///
|
| 230 |
+
/// Calling this function multiple times may result in different behavior,
|
| 231 |
+
/// depending on the operating system. On Linux, the second call will
|
| 232 |
+
/// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
|
| 233 |
+
/// This may change in the future.
|
| 234 |
+
///
|
| 235 |
+
/// # Examples
|
| 236 |
+
///
|
| 237 |
+
/// ```no_run
|
| 238 |
+
/// use std::net::{Shutdown, TcpStream};
|
| 239 |
+
///
|
| 240 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 241 |
+
/// .expect("Couldn't connect to the server...");
|
| 242 |
+
/// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
|
| 243 |
+
/// ```
|
| 244 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 245 |
+
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
|
| 246 |
+
self.0.shutdown(how)
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
/// Creates a new independently owned handle to the underlying socket.
|
| 250 |
+
///
|
| 251 |
+
/// The returned `TcpStream` is a reference to the same stream that this
|
| 252 |
+
/// object references. Both handles will read and write the same stream of
|
| 253 |
+
/// data, and options set on one stream will be propagated to the other
|
| 254 |
+
/// stream.
|
| 255 |
+
///
|
| 256 |
+
/// # Examples
|
| 257 |
+
///
|
| 258 |
+
/// ```no_run
|
| 259 |
+
/// use std::net::TcpStream;
|
| 260 |
+
///
|
| 261 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 262 |
+
/// .expect("Couldn't connect to the server...");
|
| 263 |
+
/// let stream_clone = stream.try_clone().expect("clone failed...");
|
| 264 |
+
/// ```
|
| 265 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 266 |
+
pub fn try_clone(&self) -> io::Result<TcpStream> {
|
| 267 |
+
self.0.duplicate().map(TcpStream)
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
/// Sets the read timeout to the timeout specified.
|
| 271 |
+
///
|
| 272 |
+
/// If the value specified is [`None`], then [`read`] calls will block
|
| 273 |
+
/// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
|
| 274 |
+
/// passed to this method.
|
| 275 |
+
///
|
| 276 |
+
/// # Platform-specific behavior
|
| 277 |
+
///
|
| 278 |
+
/// Platforms may return a different error code whenever a read times out as
|
| 279 |
+
/// a result of setting this option. For example Unix typically returns an
|
| 280 |
+
/// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
|
| 281 |
+
///
|
| 282 |
+
/// [`read`]: Read::read
|
| 283 |
+
/// [`WouldBlock`]: io::ErrorKind::WouldBlock
|
| 284 |
+
/// [`TimedOut`]: io::ErrorKind::TimedOut
|
| 285 |
+
///
|
| 286 |
+
/// # Examples
|
| 287 |
+
///
|
| 288 |
+
/// ```no_run
|
| 289 |
+
/// use std::net::TcpStream;
|
| 290 |
+
///
|
| 291 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 292 |
+
/// .expect("Couldn't connect to the server...");
|
| 293 |
+
/// stream.set_read_timeout(None).expect("set_read_timeout call failed");
|
| 294 |
+
/// ```
|
| 295 |
+
///
|
| 296 |
+
/// An [`Err`] is returned if the zero [`Duration`] is passed to this
|
| 297 |
+
/// method:
|
| 298 |
+
///
|
| 299 |
+
/// ```no_run
|
| 300 |
+
/// use std::io;
|
| 301 |
+
/// use std::net::TcpStream;
|
| 302 |
+
/// use std::time::Duration;
|
| 303 |
+
///
|
| 304 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
|
| 305 |
+
/// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
|
| 306 |
+
/// let err = result.unwrap_err();
|
| 307 |
+
/// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
|
| 308 |
+
/// ```
|
| 309 |
+
#[stable(feature = "socket_timeout", since = "1.4.0")]
|
| 310 |
+
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
|
| 311 |
+
self.0.set_read_timeout(dur)
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
/// Sets the write timeout to the timeout specified.
|
| 315 |
+
///
|
| 316 |
+
/// If the value specified is [`None`], then [`write`] calls will block
|
| 317 |
+
/// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
|
| 318 |
+
/// passed to this method.
|
| 319 |
+
///
|
| 320 |
+
/// # Platform-specific behavior
|
| 321 |
+
///
|
| 322 |
+
/// Platforms may return a different error code whenever a write times out
|
| 323 |
+
/// as a result of setting this option. For example Unix typically returns
|
| 324 |
+
/// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
|
| 325 |
+
///
|
| 326 |
+
/// [`write`]: Write::write
|
| 327 |
+
/// [`WouldBlock`]: io::ErrorKind::WouldBlock
|
| 328 |
+
/// [`TimedOut`]: io::ErrorKind::TimedOut
|
| 329 |
+
///
|
| 330 |
+
/// # Examples
|
| 331 |
+
///
|
| 332 |
+
/// ```no_run
|
| 333 |
+
/// use std::net::TcpStream;
|
| 334 |
+
///
|
| 335 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 336 |
+
/// .expect("Couldn't connect to the server...");
|
| 337 |
+
/// stream.set_write_timeout(None).expect("set_write_timeout call failed");
|
| 338 |
+
/// ```
|
| 339 |
+
///
|
| 340 |
+
/// An [`Err`] is returned if the zero [`Duration`] is passed to this
|
| 341 |
+
/// method:
|
| 342 |
+
///
|
| 343 |
+
/// ```no_run
|
| 344 |
+
/// use std::io;
|
| 345 |
+
/// use std::net::TcpStream;
|
| 346 |
+
/// use std::time::Duration;
|
| 347 |
+
///
|
| 348 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
|
| 349 |
+
/// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
|
| 350 |
+
/// let err = result.unwrap_err();
|
| 351 |
+
/// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
|
| 352 |
+
/// ```
|
| 353 |
+
#[stable(feature = "socket_timeout", since = "1.4.0")]
|
| 354 |
+
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
|
| 355 |
+
self.0.set_write_timeout(dur)
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
/// Returns the read timeout of this socket.
|
| 359 |
+
///
|
| 360 |
+
/// If the timeout is [`None`], then [`read`] calls will block indefinitely.
|
| 361 |
+
///
|
| 362 |
+
/// # Platform-specific behavior
|
| 363 |
+
///
|
| 364 |
+
/// Some platforms do not provide access to the current timeout.
|
| 365 |
+
///
|
| 366 |
+
/// [`read`]: Read::read
|
| 367 |
+
///
|
| 368 |
+
/// # Examples
|
| 369 |
+
///
|
| 370 |
+
/// ```no_run
|
| 371 |
+
/// use std::net::TcpStream;
|
| 372 |
+
///
|
| 373 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 374 |
+
/// .expect("Couldn't connect to the server...");
|
| 375 |
+
/// stream.set_read_timeout(None).expect("set_read_timeout call failed");
|
| 376 |
+
/// assert_eq!(stream.read_timeout().unwrap(), None);
|
| 377 |
+
/// ```
|
| 378 |
+
#[stable(feature = "socket_timeout", since = "1.4.0")]
|
| 379 |
+
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
|
| 380 |
+
self.0.read_timeout()
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
/// Returns the write timeout of this socket.
|
| 384 |
+
///
|
| 385 |
+
/// If the timeout is [`None`], then [`write`] calls will block indefinitely.
|
| 386 |
+
///
|
| 387 |
+
/// # Platform-specific behavior
|
| 388 |
+
///
|
| 389 |
+
/// Some platforms do not provide access to the current timeout.
|
| 390 |
+
///
|
| 391 |
+
/// [`write`]: Write::write
|
| 392 |
+
///
|
| 393 |
+
/// # Examples
|
| 394 |
+
///
|
| 395 |
+
/// ```no_run
|
| 396 |
+
/// use std::net::TcpStream;
|
| 397 |
+
///
|
| 398 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 399 |
+
/// .expect("Couldn't connect to the server...");
|
| 400 |
+
/// stream.set_write_timeout(None).expect("set_write_timeout call failed");
|
| 401 |
+
/// assert_eq!(stream.write_timeout().unwrap(), None);
|
| 402 |
+
/// ```
|
| 403 |
+
#[stable(feature = "socket_timeout", since = "1.4.0")]
|
| 404 |
+
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
|
| 405 |
+
self.0.write_timeout()
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
/// Receives data on the socket from the remote address to which it is
|
| 409 |
+
/// connected, without removing that data from the queue. On success,
|
| 410 |
+
/// returns the number of bytes peeked.
|
| 411 |
+
///
|
| 412 |
+
/// Successive calls return the same data. This is accomplished by passing
|
| 413 |
+
/// `MSG_PEEK` as a flag to the underlying `recv` system call.
|
| 414 |
+
///
|
| 415 |
+
/// # Examples
|
| 416 |
+
///
|
| 417 |
+
/// ```no_run
|
| 418 |
+
/// use std::net::TcpStream;
|
| 419 |
+
///
|
| 420 |
+
/// let stream = TcpStream::connect("127.0.0.1:8000")
|
| 421 |
+
/// .expect("Couldn't connect to the server...");
|
| 422 |
+
/// let mut buf = [0; 10];
|
| 423 |
+
/// let len = stream.peek(&mut buf).expect("peek failed");
|
| 424 |
+
/// ```
|
| 425 |
+
#[stable(feature = "peek", since = "1.18.0")]
|
| 426 |
+
pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
|
| 427 |
+
self.0.peek(buf)
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
/// Sets the value of the `SO_LINGER` option on this socket.
|
| 431 |
+
///
|
| 432 |
+
/// This value controls how the socket is closed when data remains
|
| 433 |
+
/// to be sent. If `SO_LINGER` is set, the socket will remain open
|
| 434 |
+
/// for the specified duration as the system attempts to send pending data.
|
| 435 |
+
/// Otherwise, the system may close the socket immediately, or wait for a
|
| 436 |
+
/// default timeout.
|
| 437 |
+
///
|
| 438 |
+
/// # Examples
|
| 439 |
+
///
|
| 440 |
+
/// ```no_run
|
| 441 |
+
/// #![feature(tcp_linger)]
|
| 442 |
+
///
|
| 443 |
+
/// use std::net::TcpStream;
|
| 444 |
+
/// use std::time::Duration;
|
| 445 |
+
///
|
| 446 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 447 |
+
/// .expect("Couldn't connect to the server...");
|
| 448 |
+
/// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
|
| 449 |
+
/// ```
|
| 450 |
+
#[unstable(feature = "tcp_linger", issue = "88494")]
|
| 451 |
+
pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
|
| 452 |
+
self.0.set_linger(linger)
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
/// Gets the value of the `SO_LINGER` option on this socket.
|
| 456 |
+
///
|
| 457 |
+
/// For more information about this option, see [`TcpStream::set_linger`].
|
| 458 |
+
///
|
| 459 |
+
/// # Examples
|
| 460 |
+
///
|
| 461 |
+
/// ```no_run
|
| 462 |
+
/// #![feature(tcp_linger)]
|
| 463 |
+
///
|
| 464 |
+
/// use std::net::TcpStream;
|
| 465 |
+
/// use std::time::Duration;
|
| 466 |
+
///
|
| 467 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 468 |
+
/// .expect("Couldn't connect to the server...");
|
| 469 |
+
/// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
|
| 470 |
+
/// assert_eq!(stream.linger().unwrap(), Some(Duration::from_secs(0)));
|
| 471 |
+
/// ```
|
| 472 |
+
#[unstable(feature = "tcp_linger", issue = "88494")]
|
| 473 |
+
pub fn linger(&self) -> io::Result<Option<Duration>> {
|
| 474 |
+
self.0.linger()
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
/// Sets the value of the `TCP_NODELAY` option on this socket.
|
| 478 |
+
///
|
| 479 |
+
/// If set, this option disables the Nagle algorithm. This means that
|
| 480 |
+
/// segments are always sent as soon as possible, even if there is only a
|
| 481 |
+
/// small amount of data. When not set, data is buffered until there is a
|
| 482 |
+
/// sufficient amount to send out, thereby avoiding the frequent sending of
|
| 483 |
+
/// small packets.
|
| 484 |
+
///
|
| 485 |
+
/// # Examples
|
| 486 |
+
///
|
| 487 |
+
/// ```no_run
|
| 488 |
+
/// use std::net::TcpStream;
|
| 489 |
+
///
|
| 490 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 491 |
+
/// .expect("Couldn't connect to the server...");
|
| 492 |
+
/// stream.set_nodelay(true).expect("set_nodelay call failed");
|
| 493 |
+
/// ```
|
| 494 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 495 |
+
pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
|
| 496 |
+
self.0.set_nodelay(nodelay)
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
/// Gets the value of the `TCP_NODELAY` option on this socket.
|
| 500 |
+
///
|
| 501 |
+
/// For more information about this option, see [`TcpStream::set_nodelay`].
|
| 502 |
+
///
|
| 503 |
+
/// # Examples
|
| 504 |
+
///
|
| 505 |
+
/// ```no_run
|
| 506 |
+
/// use std::net::TcpStream;
|
| 507 |
+
///
|
| 508 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 509 |
+
/// .expect("Couldn't connect to the server...");
|
| 510 |
+
/// stream.set_nodelay(true).expect("set_nodelay call failed");
|
| 511 |
+
/// assert_eq!(stream.nodelay().unwrap_or(false), true);
|
| 512 |
+
/// ```
|
| 513 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 514 |
+
pub fn nodelay(&self) -> io::Result<bool> {
|
| 515 |
+
self.0.nodelay()
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
/// Sets the value for the `IP_TTL` option on this socket.
|
| 519 |
+
///
|
| 520 |
+
/// This value sets the time-to-live field that is used in every packet sent
|
| 521 |
+
/// from this socket.
|
| 522 |
+
///
|
| 523 |
+
/// # Examples
|
| 524 |
+
///
|
| 525 |
+
/// ```no_run
|
| 526 |
+
/// use std::net::TcpStream;
|
| 527 |
+
///
|
| 528 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 529 |
+
/// .expect("Couldn't connect to the server...");
|
| 530 |
+
/// stream.set_ttl(100).expect("set_ttl call failed");
|
| 531 |
+
/// ```
|
| 532 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 533 |
+
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
|
| 534 |
+
self.0.set_ttl(ttl)
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
/// Gets the value of the `IP_TTL` option for this socket.
|
| 538 |
+
///
|
| 539 |
+
/// For more information about this option, see [`TcpStream::set_ttl`].
|
| 540 |
+
///
|
| 541 |
+
/// # Examples
|
| 542 |
+
///
|
| 543 |
+
/// ```no_run
|
| 544 |
+
/// use std::net::TcpStream;
|
| 545 |
+
///
|
| 546 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 547 |
+
/// .expect("Couldn't connect to the server...");
|
| 548 |
+
/// stream.set_ttl(100).expect("set_ttl call failed");
|
| 549 |
+
/// assert_eq!(stream.ttl().unwrap_or(0), 100);
|
| 550 |
+
/// ```
|
| 551 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 552 |
+
pub fn ttl(&self) -> io::Result<u32> {
|
| 553 |
+
self.0.ttl()
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
/// Gets the value of the `SO_ERROR` option on this socket.
|
| 557 |
+
///
|
| 558 |
+
/// This will retrieve the stored error in the underlying socket, clearing
|
| 559 |
+
/// the field in the process. This can be useful for checking errors between
|
| 560 |
+
/// calls.
|
| 561 |
+
///
|
| 562 |
+
/// # Examples
|
| 563 |
+
///
|
| 564 |
+
/// ```no_run
|
| 565 |
+
/// use std::net::TcpStream;
|
| 566 |
+
///
|
| 567 |
+
/// let stream = TcpStream::connect("127.0.0.1:8080")
|
| 568 |
+
/// .expect("Couldn't connect to the server...");
|
| 569 |
+
/// stream.take_error().expect("No error was expected...");
|
| 570 |
+
/// ```
|
| 571 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 572 |
+
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
|
| 573 |
+
self.0.take_error()
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
/// Moves this TCP stream into or out of nonblocking mode.
|
| 577 |
+
///
|
| 578 |
+
/// This will result in `read`, `write`, `recv` and `send` system operations
|
| 579 |
+
/// becoming nonblocking, i.e., immediately returning from their calls.
|
| 580 |
+
/// If the IO operation is successful, `Ok` is returned and no further
|
| 581 |
+
/// action is required. If the IO operation could not be completed and needs
|
| 582 |
+
/// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
|
| 583 |
+
/// returned.
|
| 584 |
+
///
|
| 585 |
+
/// On Unix platforms, calling this method corresponds to calling `fcntl`
|
| 586 |
+
/// `FIONBIO`. On Windows calling this method corresponds to calling
|
| 587 |
+
/// `ioctlsocket` `FIONBIO`.
|
| 588 |
+
///
|
| 589 |
+
/// # Examples
|
| 590 |
+
///
|
| 591 |
+
/// Reading bytes from a TCP stream in non-blocking mode:
|
| 592 |
+
///
|
| 593 |
+
/// ```no_run
|
| 594 |
+
/// use std::io::{self, Read};
|
| 595 |
+
/// use std::net::TcpStream;
|
| 596 |
+
///
|
| 597 |
+
/// let mut stream = TcpStream::connect("127.0.0.1:7878")
|
| 598 |
+
/// .expect("Couldn't connect to the server...");
|
| 599 |
+
/// stream.set_nonblocking(true).expect("set_nonblocking call failed");
|
| 600 |
+
///
|
| 601 |
+
/// # fn wait_for_fd() { unimplemented!() }
|
| 602 |
+
/// let mut buf = vec![];
|
| 603 |
+
/// loop {
|
| 604 |
+
/// match stream.read_to_end(&mut buf) {
|
| 605 |
+
/// Ok(_) => break,
|
| 606 |
+
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
|
| 607 |
+
/// // wait until network socket is ready, typically implemented
|
| 608 |
+
/// // via platform-specific APIs such as epoll or IOCP
|
| 609 |
+
/// wait_for_fd();
|
| 610 |
+
/// }
|
| 611 |
+
/// Err(e) => panic!("encountered IO error: {e}"),
|
| 612 |
+
/// };
|
| 613 |
+
/// };
|
| 614 |
+
/// println!("bytes: {buf:?}");
|
| 615 |
+
/// ```
|
| 616 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 617 |
+
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
|
| 618 |
+
self.0.set_nonblocking(nonblocking)
|
| 619 |
+
}
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
// In addition to the `impl`s here, `TcpStream` also has `impl`s for
|
| 623 |
+
// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
|
| 624 |
+
// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
|
| 625 |
+
// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
|
| 626 |
+
// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
|
| 627 |
+
|
| 628 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 629 |
+
impl Read for TcpStream {
|
| 630 |
+
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
| 631 |
+
self.0.read(buf)
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
|
| 635 |
+
self.0.read_buf(buf)
|
| 636 |
+
}
|
| 637 |
+
|
| 638 |
+
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
|
| 639 |
+
self.0.read_vectored(bufs)
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
#[inline]
|
| 643 |
+
fn is_read_vectored(&self) -> bool {
|
| 644 |
+
self.0.is_read_vectored()
|
| 645 |
+
}
|
| 646 |
+
}
|
| 647 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 648 |
+
impl Write for TcpStream {
|
| 649 |
+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
| 650 |
+
self.0.write(buf)
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
|
| 654 |
+
self.0.write_vectored(bufs)
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
#[inline]
|
| 658 |
+
fn is_write_vectored(&self) -> bool {
|
| 659 |
+
self.0.is_write_vectored()
|
| 660 |
+
}
|
| 661 |
+
|
| 662 |
+
#[inline]
|
| 663 |
+
fn flush(&mut self) -> io::Result<()> {
|
| 664 |
+
Ok(())
|
| 665 |
+
}
|
| 666 |
+
}
|
| 667 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 668 |
+
impl Read for &TcpStream {
|
| 669 |
+
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
| 670 |
+
self.0.read(buf)
|
| 671 |
+
}
|
| 672 |
+
|
| 673 |
+
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
|
| 674 |
+
self.0.read_buf(buf)
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
|
| 678 |
+
self.0.read_vectored(bufs)
|
| 679 |
+
}
|
| 680 |
+
|
| 681 |
+
#[inline]
|
| 682 |
+
fn is_read_vectored(&self) -> bool {
|
| 683 |
+
self.0.is_read_vectored()
|
| 684 |
+
}
|
| 685 |
+
}
|
| 686 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 687 |
+
impl Write for &TcpStream {
|
| 688 |
+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
| 689 |
+
self.0.write(buf)
|
| 690 |
+
}
|
| 691 |
+
|
| 692 |
+
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
|
| 693 |
+
self.0.write_vectored(bufs)
|
| 694 |
+
}
|
| 695 |
+
|
| 696 |
+
#[inline]
|
| 697 |
+
fn is_write_vectored(&self) -> bool {
|
| 698 |
+
self.0.is_write_vectored()
|
| 699 |
+
}
|
| 700 |
+
|
| 701 |
+
#[inline]
|
| 702 |
+
fn flush(&mut self) -> io::Result<()> {
|
| 703 |
+
Ok(())
|
| 704 |
+
}
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
impl AsInner<net_imp::TcpStream> for TcpStream {
|
| 708 |
+
#[inline]
|
| 709 |
+
fn as_inner(&self) -> &net_imp::TcpStream {
|
| 710 |
+
&self.0
|
| 711 |
+
}
|
| 712 |
+
}
|
| 713 |
+
|
| 714 |
+
impl FromInner<net_imp::TcpStream> for TcpStream {
|
| 715 |
+
fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
|
| 716 |
+
TcpStream(inner)
|
| 717 |
+
}
|
| 718 |
+
}
|
| 719 |
+
|
| 720 |
+
impl IntoInner<net_imp::TcpStream> for TcpStream {
|
| 721 |
+
fn into_inner(self) -> net_imp::TcpStream {
|
| 722 |
+
self.0
|
| 723 |
+
}
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 727 |
+
impl fmt::Debug for TcpStream {
|
| 728 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 729 |
+
self.0.fmt(f)
|
| 730 |
+
}
|
| 731 |
+
}
|
| 732 |
+
|
| 733 |
+
impl TcpListener {
|
| 734 |
+
/// Creates a new `TcpListener` which will be bound to the specified
|
| 735 |
+
/// address.
|
| 736 |
+
///
|
| 737 |
+
/// The returned listener is ready for accepting connections.
|
| 738 |
+
///
|
| 739 |
+
/// Binding with a port number of 0 will request that the OS assigns a port
|
| 740 |
+
/// to this listener. The port allocated can be queried via the
|
| 741 |
+
/// [`TcpListener::local_addr`] method.
|
| 742 |
+
///
|
| 743 |
+
/// The address type can be any implementor of [`ToSocketAddrs`] trait. See
|
| 744 |
+
/// its documentation for concrete examples.
|
| 745 |
+
///
|
| 746 |
+
/// If `addr` yields multiple addresses, `bind` will be attempted with
|
| 747 |
+
/// each of the addresses until one succeeds and returns the listener. If
|
| 748 |
+
/// none of the addresses succeed in creating a listener, the error returned
|
| 749 |
+
/// from the last attempt (the last address) is returned.
|
| 750 |
+
///
|
| 751 |
+
/// # Examples
|
| 752 |
+
///
|
| 753 |
+
/// Creates a TCP listener bound to `127.0.0.1:80`:
|
| 754 |
+
///
|
| 755 |
+
/// ```no_run
|
| 756 |
+
/// use std::net::TcpListener;
|
| 757 |
+
///
|
| 758 |
+
/// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
|
| 759 |
+
/// ```
|
| 760 |
+
///
|
| 761 |
+
/// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
|
| 762 |
+
/// TCP listener bound to `127.0.0.1:443`:
|
| 763 |
+
///
|
| 764 |
+
/// ```no_run
|
| 765 |
+
/// use std::net::{SocketAddr, TcpListener};
|
| 766 |
+
///
|
| 767 |
+
/// let addrs = [
|
| 768 |
+
/// SocketAddr::from(([127, 0, 0, 1], 80)),
|
| 769 |
+
/// SocketAddr::from(([127, 0, 0, 1], 443)),
|
| 770 |
+
/// ];
|
| 771 |
+
/// let listener = TcpListener::bind(&addrs[..]).unwrap();
|
| 772 |
+
/// ```
|
| 773 |
+
///
|
| 774 |
+
/// Creates a TCP listener bound to a port assigned by the operating system
|
| 775 |
+
/// at `127.0.0.1`.
|
| 776 |
+
///
|
| 777 |
+
/// ```no_run
|
| 778 |
+
/// use std::net::TcpListener;
|
| 779 |
+
///
|
| 780 |
+
/// let socket = TcpListener::bind("127.0.0.1:0").unwrap();
|
| 781 |
+
/// ```
|
| 782 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 783 |
+
pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
|
| 784 |
+
net_imp::TcpListener::bind(addr).map(TcpListener)
|
| 785 |
+
}
|
| 786 |
+
|
| 787 |
+
/// Returns the local socket address of this listener.
|
| 788 |
+
///
|
| 789 |
+
/// # Examples
|
| 790 |
+
///
|
| 791 |
+
/// ```no_run
|
| 792 |
+
/// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
|
| 793 |
+
///
|
| 794 |
+
/// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
|
| 795 |
+
/// assert_eq!(listener.local_addr().unwrap(),
|
| 796 |
+
/// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
|
| 797 |
+
/// ```
|
| 798 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 799 |
+
pub fn local_addr(&self) -> io::Result<SocketAddr> {
|
| 800 |
+
self.0.socket_addr()
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
/// Creates a new independently owned handle to the underlying socket.
|
| 804 |
+
///
|
| 805 |
+
/// The returned [`TcpListener`] is a reference to the same socket that this
|
| 806 |
+
/// object references. Both handles can be used to accept incoming
|
| 807 |
+
/// connections and options set on one listener will affect the other.
|
| 808 |
+
///
|
| 809 |
+
/// # Examples
|
| 810 |
+
///
|
| 811 |
+
/// ```no_run
|
| 812 |
+
/// use std::net::TcpListener;
|
| 813 |
+
///
|
| 814 |
+
/// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
|
| 815 |
+
/// let listener_clone = listener.try_clone().unwrap();
|
| 816 |
+
/// ```
|
| 817 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 818 |
+
pub fn try_clone(&self) -> io::Result<TcpListener> {
|
| 819 |
+
self.0.duplicate().map(TcpListener)
|
| 820 |
+
}
|
| 821 |
+
|
| 822 |
+
/// Accept a new incoming connection from this listener.
|
| 823 |
+
///
|
| 824 |
+
/// This function will block the calling thread until a new TCP connection
|
| 825 |
+
/// is established. When established, the corresponding [`TcpStream`] and the
|
| 826 |
+
/// remote peer's address will be returned.
|
| 827 |
+
///
|
| 828 |
+
/// # Examples
|
| 829 |
+
///
|
| 830 |
+
/// ```no_run
|
| 831 |
+
/// use std::net::TcpListener;
|
| 832 |
+
///
|
| 833 |
+
/// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
|
| 834 |
+
/// match listener.accept() {
|
| 835 |
+
/// Ok((_socket, addr)) => println!("new client: {addr:?}"),
|
| 836 |
+
/// Err(e) => println!("couldn't get client: {e:?}"),
|
| 837 |
+
/// }
|
| 838 |
+
/// ```
|
| 839 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 840 |
+
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
|
| 841 |
+
// On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
|
| 842 |
+
// the `a` variable here is technically unused.
|
| 843 |
+
#[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
|
| 844 |
+
self.0.accept().map(|(a, b)| (TcpStream(a), b))
|
| 845 |
+
}
|
| 846 |
+
|
| 847 |
+
/// Returns an iterator over the connections being received on this
|
| 848 |
+
/// listener.
|
| 849 |
+
///
|
| 850 |
+
/// The returned iterator will never return [`None`] and will also not yield
|
| 851 |
+
/// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
|
| 852 |
+
/// calling [`TcpListener::accept`] in a loop.
|
| 853 |
+
///
|
| 854 |
+
/// # Examples
|
| 855 |
+
///
|
| 856 |
+
/// ```no_run
|
| 857 |
+
/// use std::net::{TcpListener, TcpStream};
|
| 858 |
+
///
|
| 859 |
+
/// fn handle_connection(stream: TcpStream) {
|
| 860 |
+
/// //...
|
| 861 |
+
/// }
|
| 862 |
+
///
|
| 863 |
+
/// fn main() -> std::io::Result<()> {
|
| 864 |
+
/// let listener = TcpListener::bind("127.0.0.1:80")?;
|
| 865 |
+
///
|
| 866 |
+
/// for stream in listener.incoming() {
|
| 867 |
+
/// match stream {
|
| 868 |
+
/// Ok(stream) => {
|
| 869 |
+
/// handle_connection(stream);
|
| 870 |
+
/// }
|
| 871 |
+
/// Err(e) => { /* connection failed */ }
|
| 872 |
+
/// }
|
| 873 |
+
/// }
|
| 874 |
+
/// Ok(())
|
| 875 |
+
/// }
|
| 876 |
+
/// ```
|
| 877 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 878 |
+
pub fn incoming(&self) -> Incoming<'_> {
|
| 879 |
+
Incoming { listener: self }
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
/// Turn this into an iterator over the connections being received on this
|
| 883 |
+
/// listener.
|
| 884 |
+
///
|
| 885 |
+
/// The returned iterator will never return [`None`] and will also not yield
|
| 886 |
+
/// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
|
| 887 |
+
/// calling [`TcpListener::accept`] in a loop.
|
| 888 |
+
///
|
| 889 |
+
/// # Examples
|
| 890 |
+
///
|
| 891 |
+
/// ```no_run
|
| 892 |
+
/// #![feature(tcplistener_into_incoming)]
|
| 893 |
+
/// use std::net::{TcpListener, TcpStream};
|
| 894 |
+
///
|
| 895 |
+
/// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
|
| 896 |
+
/// let listener = TcpListener::bind(("127.0.0.1", port)).unwrap();
|
| 897 |
+
/// listener.into_incoming()
|
| 898 |
+
/// .filter_map(Result::ok) /* Ignore failed connections */
|
| 899 |
+
/// }
|
| 900 |
+
///
|
| 901 |
+
/// fn main() -> std::io::Result<()> {
|
| 902 |
+
/// for stream in listen_on(80) {
|
| 903 |
+
/// /* handle the connection here */
|
| 904 |
+
/// }
|
| 905 |
+
/// Ok(())
|
| 906 |
+
/// }
|
| 907 |
+
/// ```
|
| 908 |
+
#[must_use = "`self` will be dropped if the result is not used"]
|
| 909 |
+
#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
|
| 910 |
+
pub fn into_incoming(self) -> IntoIncoming {
|
| 911 |
+
IntoIncoming { listener: self }
|
| 912 |
+
}
|
| 913 |
+
|
| 914 |
+
/// Sets the value for the `IP_TTL` option on this socket.
|
| 915 |
+
///
|
| 916 |
+
/// This value sets the time-to-live field that is used in every packet sent
|
| 917 |
+
/// from this socket.
|
| 918 |
+
///
|
| 919 |
+
/// # Examples
|
| 920 |
+
///
|
| 921 |
+
/// ```no_run
|
| 922 |
+
/// use std::net::TcpListener;
|
| 923 |
+
///
|
| 924 |
+
/// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
|
| 925 |
+
/// listener.set_ttl(100).expect("could not set TTL");
|
| 926 |
+
/// ```
|
| 927 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 928 |
+
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
|
| 929 |
+
self.0.set_ttl(ttl)
|
| 930 |
+
}
|
| 931 |
+
|
| 932 |
+
/// Gets the value of the `IP_TTL` option for this socket.
|
| 933 |
+
///
|
| 934 |
+
/// For more information about this option, see [`TcpListener::set_ttl`].
|
| 935 |
+
///
|
| 936 |
+
/// # Examples
|
| 937 |
+
///
|
| 938 |
+
/// ```no_run
|
| 939 |
+
/// use std::net::TcpListener;
|
| 940 |
+
///
|
| 941 |
+
/// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
|
| 942 |
+
/// listener.set_ttl(100).expect("could not set TTL");
|
| 943 |
+
/// assert_eq!(listener.ttl().unwrap_or(0), 100);
|
| 944 |
+
/// ```
|
| 945 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 946 |
+
pub fn ttl(&self) -> io::Result<u32> {
|
| 947 |
+
self.0.ttl()
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 951 |
+
#[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
|
| 952 |
+
#[allow(missing_docs)]
|
| 953 |
+
pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
|
| 954 |
+
self.0.set_only_v6(only_v6)
|
| 955 |
+
}
|
| 956 |
+
|
| 957 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 958 |
+
#[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
|
| 959 |
+
#[allow(missing_docs)]
|
| 960 |
+
pub fn only_v6(&self) -> io::Result<bool> {
|
| 961 |
+
self.0.only_v6()
|
| 962 |
+
}
|
| 963 |
+
|
| 964 |
+
/// Gets the value of the `SO_ERROR` option on this socket.
|
| 965 |
+
///
|
| 966 |
+
/// This will retrieve the stored error in the underlying socket, clearing
|
| 967 |
+
/// the field in the process. This can be useful for checking errors between
|
| 968 |
+
/// calls.
|
| 969 |
+
///
|
| 970 |
+
/// # Examples
|
| 971 |
+
///
|
| 972 |
+
/// ```no_run
|
| 973 |
+
/// use std::net::TcpListener;
|
| 974 |
+
///
|
| 975 |
+
/// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
|
| 976 |
+
/// listener.take_error().expect("No error was expected");
|
| 977 |
+
/// ```
|
| 978 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 979 |
+
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
|
| 980 |
+
self.0.take_error()
|
| 981 |
+
}
|
| 982 |
+
|
| 983 |
+
/// Moves this TCP stream into or out of nonblocking mode.
|
| 984 |
+
///
|
| 985 |
+
/// This will result in the `accept` operation becoming nonblocking,
|
| 986 |
+
/// i.e., immediately returning from their calls. If the IO operation is
|
| 987 |
+
/// successful, `Ok` is returned and no further action is required. If the
|
| 988 |
+
/// IO operation could not be completed and needs to be retried, an error
|
| 989 |
+
/// with kind [`io::ErrorKind::WouldBlock`] is returned.
|
| 990 |
+
///
|
| 991 |
+
/// On Unix platforms, calling this method corresponds to calling `fcntl`
|
| 992 |
+
/// `FIONBIO`. On Windows calling this method corresponds to calling
|
| 993 |
+
/// `ioctlsocket` `FIONBIO`.
|
| 994 |
+
///
|
| 995 |
+
/// # Examples
|
| 996 |
+
///
|
| 997 |
+
/// Bind a TCP listener to an address, listen for connections, and read
|
| 998 |
+
/// bytes in nonblocking mode:
|
| 999 |
+
///
|
| 1000 |
+
/// ```no_run
|
| 1001 |
+
/// use std::io;
|
| 1002 |
+
/// use std::net::TcpListener;
|
| 1003 |
+
///
|
| 1004 |
+
/// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
|
| 1005 |
+
/// listener.set_nonblocking(true).expect("Cannot set non-blocking");
|
| 1006 |
+
///
|
| 1007 |
+
/// # fn wait_for_fd() { unimplemented!() }
|
| 1008 |
+
/// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
|
| 1009 |
+
/// for stream in listener.incoming() {
|
| 1010 |
+
/// match stream {
|
| 1011 |
+
/// Ok(s) => {
|
| 1012 |
+
/// // do something with the TcpStream
|
| 1013 |
+
/// handle_connection(s);
|
| 1014 |
+
/// }
|
| 1015 |
+
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
|
| 1016 |
+
/// // wait until network socket is ready, typically implemented
|
| 1017 |
+
/// // via platform-specific APIs such as epoll or IOCP
|
| 1018 |
+
/// wait_for_fd();
|
| 1019 |
+
/// continue;
|
| 1020 |
+
/// }
|
| 1021 |
+
/// Err(e) => panic!("encountered IO error: {e}"),
|
| 1022 |
+
/// }
|
| 1023 |
+
/// }
|
| 1024 |
+
/// ```
|
| 1025 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 1026 |
+
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
|
| 1027 |
+
self.0.set_nonblocking(nonblocking)
|
| 1028 |
+
}
|
| 1029 |
+
}
|
| 1030 |
+
|
| 1031 |
+
// In addition to the `impl`s here, `TcpListener` also has `impl`s for
|
| 1032 |
+
// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
|
| 1033 |
+
// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
|
| 1034 |
+
// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
|
| 1035 |
+
// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
|
| 1036 |
+
|
| 1037 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1038 |
+
impl<'a> Iterator for Incoming<'a> {
|
| 1039 |
+
type Item = io::Result<TcpStream>;
|
| 1040 |
+
fn next(&mut self) -> Option<io::Result<TcpStream>> {
|
| 1041 |
+
Some(self.listener.accept().map(|p| p.0))
|
| 1042 |
+
}
|
| 1043 |
+
}
|
| 1044 |
+
|
| 1045 |
+
#[stable(feature = "tcp_listener_incoming_fused_iterator", since = "1.64.0")]
|
| 1046 |
+
impl FusedIterator for Incoming<'_> {}
|
| 1047 |
+
|
| 1048 |
+
#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
|
| 1049 |
+
impl Iterator for IntoIncoming {
|
| 1050 |
+
type Item = io::Result<TcpStream>;
|
| 1051 |
+
fn next(&mut self) -> Option<io::Result<TcpStream>> {
|
| 1052 |
+
Some(self.listener.accept().map(|p| p.0))
|
| 1053 |
+
}
|
| 1054 |
+
}
|
| 1055 |
+
|
| 1056 |
+
#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
|
| 1057 |
+
impl FusedIterator for IntoIncoming {}
|
| 1058 |
+
|
| 1059 |
+
impl AsInner<net_imp::TcpListener> for TcpListener {
|
| 1060 |
+
#[inline]
|
| 1061 |
+
fn as_inner(&self) -> &net_imp::TcpListener {
|
| 1062 |
+
&self.0
|
| 1063 |
+
}
|
| 1064 |
+
}
|
| 1065 |
+
|
| 1066 |
+
impl FromInner<net_imp::TcpListener> for TcpListener {
|
| 1067 |
+
fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
|
| 1068 |
+
TcpListener(inner)
|
| 1069 |
+
}
|
| 1070 |
+
}
|
| 1071 |
+
|
| 1072 |
+
impl IntoInner<net_imp::TcpListener> for TcpListener {
|
| 1073 |
+
fn into_inner(self) -> net_imp::TcpListener {
|
| 1074 |
+
self.0
|
| 1075 |
+
}
|
| 1076 |
+
}
|
| 1077 |
+
|
| 1078 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1079 |
+
impl fmt::Debug for TcpListener {
|
| 1080 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 1081 |
+
self.0.fmt(f)
|
| 1082 |
+
}
|
| 1083 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/net/test.rs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#![allow(warnings)] // not used on emscripten
|
| 2 |
+
|
| 3 |
+
use crate::env;
|
| 4 |
+
use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
|
| 5 |
+
use crate::sync::atomic::{AtomicUsize, Ordering};
|
| 6 |
+
|
| 7 |
+
static PORT: AtomicUsize = AtomicUsize::new(0);
|
| 8 |
+
const BASE_PORT: u16 = 19600;
|
| 9 |
+
|
| 10 |
+
pub fn next_test_ip4() -> SocketAddr {
|
| 11 |
+
let port = PORT.fetch_add(1, Ordering::Relaxed) as u16 + BASE_PORT;
|
| 12 |
+
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
pub fn next_test_ip6() -> SocketAddr {
|
| 16 |
+
let port = PORT.fetch_add(1, Ordering::Relaxed) as u16 + BASE_PORT;
|
| 17 |
+
SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), port, 0, 0))
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
pub fn sa4(a: Ipv4Addr, p: u16) -> SocketAddr {
|
| 21 |
+
SocketAddr::V4(SocketAddrV4::new(a, p))
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
pub fn sa6(a: Ipv6Addr, p: u16) -> SocketAddr {
|
| 25 |
+
SocketAddr::V6(SocketAddrV6::new(a, p, 0, 0))
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
pub fn tsa<A: ToSocketAddrs>(a: A) -> Result<Vec<SocketAddr>, String> {
|
| 29 |
+
match a.to_socket_addrs() {
|
| 30 |
+
Ok(a) => Ok(a.collect()),
|
| 31 |
+
Err(e) => Err(e.to_string()),
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
pub fn compare_ignore_zoneid(a: &SocketAddr, b: &SocketAddr) -> bool {
|
| 36 |
+
match (a, b) {
|
| 37 |
+
(SocketAddr::V6(a), SocketAddr::V6(b)) => {
|
| 38 |
+
a.ip().segments() == b.ip().segments()
|
| 39 |
+
&& a.flowinfo() == b.flowinfo()
|
| 40 |
+
&& a.port() == b.port()
|
| 41 |
+
}
|
| 42 |
+
_ => a == b,
|
| 43 |
+
}
|
| 44 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/net/udp.rs
ADDED
|
@@ -0,0 +1,848 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#[cfg(all(
|
| 2 |
+
test,
|
| 3 |
+
not(any(
|
| 4 |
+
target_os = "emscripten",
|
| 5 |
+
all(target_os = "wasi", target_env = "p1"),
|
| 6 |
+
target_env = "sgx",
|
| 7 |
+
target_os = "xous",
|
| 8 |
+
target_os = "trusty",
|
| 9 |
+
))
|
| 10 |
+
))]
|
| 11 |
+
mod tests;
|
| 12 |
+
|
| 13 |
+
use crate::fmt;
|
| 14 |
+
use crate::io::{self, ErrorKind};
|
| 15 |
+
use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
|
| 16 |
+
use crate::sys::{AsInner, FromInner, IntoInner, net as net_imp};
|
| 17 |
+
use crate::time::Duration;
|
| 18 |
+
|
| 19 |
+
/// A UDP socket.
|
| 20 |
+
///
|
| 21 |
+
/// After creating a `UdpSocket` by [`bind`]ing it to a socket address, data can be
|
| 22 |
+
/// [sent to] and [received from] any other socket address.
|
| 23 |
+
///
|
| 24 |
+
/// Although UDP is a connectionless protocol, this implementation provides an interface
|
| 25 |
+
/// to set an address where data should be sent and received from. After setting a remote
|
| 26 |
+
/// address with [`connect`], data can be sent to and received from that address with
|
| 27 |
+
/// [`send`] and [`recv`].
|
| 28 |
+
///
|
| 29 |
+
/// As stated in the User Datagram Protocol's specification in [IETF RFC 768], UDP is
|
| 30 |
+
/// an unordered, unreliable protocol; refer to [`TcpListener`] and [`TcpStream`] for TCP
|
| 31 |
+
/// primitives.
|
| 32 |
+
///
|
| 33 |
+
/// [`bind`]: UdpSocket::bind
|
| 34 |
+
/// [`connect`]: UdpSocket::connect
|
| 35 |
+
/// [IETF RFC 768]: https://tools.ietf.org/html/rfc768
|
| 36 |
+
/// [`recv`]: UdpSocket::recv
|
| 37 |
+
/// [received from]: UdpSocket::recv_from
|
| 38 |
+
/// [`send`]: UdpSocket::send
|
| 39 |
+
/// [sent to]: UdpSocket::send_to
|
| 40 |
+
/// [`TcpListener`]: crate::net::TcpListener
|
| 41 |
+
/// [`TcpStream`]: crate::net::TcpStream
|
| 42 |
+
///
|
| 43 |
+
/// # Examples
|
| 44 |
+
///
|
| 45 |
+
/// ```no_run
|
| 46 |
+
/// use std::net::UdpSocket;
|
| 47 |
+
///
|
| 48 |
+
/// fn main() -> std::io::Result<()> {
|
| 49 |
+
/// {
|
| 50 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254")?;
|
| 51 |
+
///
|
| 52 |
+
/// // Receives a single datagram message on the socket. If `buf` is too small to hold
|
| 53 |
+
/// // the message, it will be cut off.
|
| 54 |
+
/// let mut buf = [0; 10];
|
| 55 |
+
/// let (amt, src) = socket.recv_from(&mut buf)?;
|
| 56 |
+
///
|
| 57 |
+
/// // Redeclare `buf` as slice of the received data and send reverse data back to origin.
|
| 58 |
+
/// let buf = &mut buf[..amt];
|
| 59 |
+
/// buf.reverse();
|
| 60 |
+
/// socket.send_to(buf, &src)?;
|
| 61 |
+
/// } // the socket is closed here
|
| 62 |
+
/// Ok(())
|
| 63 |
+
/// }
|
| 64 |
+
/// ```
|
| 65 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 66 |
+
pub struct UdpSocket(net_imp::UdpSocket);
|
| 67 |
+
|
| 68 |
+
impl UdpSocket {
|
| 69 |
+
/// Creates a UDP socket from the given address.
|
| 70 |
+
///
|
| 71 |
+
/// The address type can be any implementor of [`ToSocketAddrs`] trait. See
|
| 72 |
+
/// its documentation for concrete examples.
|
| 73 |
+
///
|
| 74 |
+
/// If `addr` yields multiple addresses, `bind` will be attempted with
|
| 75 |
+
/// each of the addresses until one succeeds and returns the socket. If none
|
| 76 |
+
/// of the addresses succeed in creating a socket, the error returned from
|
| 77 |
+
/// the last attempt (the last address) is returned.
|
| 78 |
+
///
|
| 79 |
+
/// # Examples
|
| 80 |
+
///
|
| 81 |
+
/// Creates a UDP socket bound to `127.0.0.1:3400`:
|
| 82 |
+
///
|
| 83 |
+
/// ```no_run
|
| 84 |
+
/// use std::net::UdpSocket;
|
| 85 |
+
///
|
| 86 |
+
/// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
|
| 87 |
+
/// ```
|
| 88 |
+
///
|
| 89 |
+
/// Creates a UDP socket bound to `127.0.0.1:3400`. If the socket cannot be
|
| 90 |
+
/// bound to that address, create a UDP socket bound to `127.0.0.1:3401`:
|
| 91 |
+
///
|
| 92 |
+
/// ```no_run
|
| 93 |
+
/// use std::net::{SocketAddr, UdpSocket};
|
| 94 |
+
///
|
| 95 |
+
/// let addrs = [
|
| 96 |
+
/// SocketAddr::from(([127, 0, 0, 1], 3400)),
|
| 97 |
+
/// SocketAddr::from(([127, 0, 0, 1], 3401)),
|
| 98 |
+
/// ];
|
| 99 |
+
/// let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address");
|
| 100 |
+
/// ```
|
| 101 |
+
///
|
| 102 |
+
/// Creates a UDP socket bound to a port assigned by the operating system
|
| 103 |
+
/// at `127.0.0.1`.
|
| 104 |
+
///
|
| 105 |
+
/// ```no_run
|
| 106 |
+
/// use std::net::UdpSocket;
|
| 107 |
+
///
|
| 108 |
+
/// let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
|
| 109 |
+
/// ```
|
| 110 |
+
///
|
| 111 |
+
/// Note that `bind` declares the scope of your network connection.
|
| 112 |
+
/// You can only receive datagrams from and send datagrams to
|
| 113 |
+
/// participants in that view of the network.
|
| 114 |
+
/// For instance, binding to a loopback address as in the example
|
| 115 |
+
/// above will prevent you from sending datagrams to another device
|
| 116 |
+
/// in your local network.
|
| 117 |
+
///
|
| 118 |
+
/// In order to limit your view of the network the least, `bind` to
|
| 119 |
+
/// [`Ipv4Addr::UNSPECIFIED`] or [`Ipv6Addr::UNSPECIFIED`].
|
| 120 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 121 |
+
pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
|
| 122 |
+
net_imp::UdpSocket::bind(addr).map(UdpSocket)
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
/// Receives a single datagram message on the socket. On success, returns the number
|
| 126 |
+
/// of bytes read and the origin.
|
| 127 |
+
///
|
| 128 |
+
/// The function must be called with valid byte array `buf` of sufficient size to
|
| 129 |
+
/// hold the message bytes. If a message is too long to fit in the supplied buffer,
|
| 130 |
+
/// excess bytes may be discarded.
|
| 131 |
+
///
|
| 132 |
+
/// # Examples
|
| 133 |
+
///
|
| 134 |
+
/// ```no_run
|
| 135 |
+
/// use std::net::UdpSocket;
|
| 136 |
+
///
|
| 137 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 138 |
+
/// let mut buf = [0; 10];
|
| 139 |
+
/// let (number_of_bytes, src_addr) = socket.recv_from(&mut buf)
|
| 140 |
+
/// .expect("Didn't receive data");
|
| 141 |
+
/// let filled_buf = &mut buf[..number_of_bytes];
|
| 142 |
+
/// ```
|
| 143 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 144 |
+
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
| 145 |
+
self.0.recv_from(buf)
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
/// Receives a single datagram message on the socket, without removing it from the
|
| 149 |
+
/// queue. On success, returns the number of bytes read and the origin.
|
| 150 |
+
///
|
| 151 |
+
/// The function must be called with valid byte array `buf` of sufficient size to
|
| 152 |
+
/// hold the message bytes. If a message is too long to fit in the supplied buffer,
|
| 153 |
+
/// excess bytes may be discarded.
|
| 154 |
+
///
|
| 155 |
+
/// Successive calls return the same data. This is accomplished by passing
|
| 156 |
+
/// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
|
| 157 |
+
///
|
| 158 |
+
/// Do not use this function to implement busy waiting, instead use `libc::poll` to
|
| 159 |
+
/// synchronize IO events on one or more sockets.
|
| 160 |
+
///
|
| 161 |
+
/// # Examples
|
| 162 |
+
///
|
| 163 |
+
/// ```no_run
|
| 164 |
+
/// use std::net::UdpSocket;
|
| 165 |
+
///
|
| 166 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 167 |
+
/// let mut buf = [0; 10];
|
| 168 |
+
/// let (number_of_bytes, src_addr) = socket.peek_from(&mut buf)
|
| 169 |
+
/// .expect("Didn't receive data");
|
| 170 |
+
/// let filled_buf = &mut buf[..number_of_bytes];
|
| 171 |
+
/// ```
|
| 172 |
+
#[stable(feature = "peek", since = "1.18.0")]
|
| 173 |
+
pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
| 174 |
+
self.0.peek_from(buf)
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
/// Sends data on the socket to the given address. On success, returns the
|
| 178 |
+
/// number of bytes written. Note that the operating system may refuse
|
| 179 |
+
/// buffers larger than 65507. However, partial writes are not possible
|
| 180 |
+
/// until buffer sizes above `i32::MAX`.
|
| 181 |
+
///
|
| 182 |
+
/// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
|
| 183 |
+
/// documentation for concrete examples.
|
| 184 |
+
///
|
| 185 |
+
/// It is possible for `addr` to yield multiple addresses, but `send_to`
|
| 186 |
+
/// will only send data to the first address yielded by `addr`.
|
| 187 |
+
///
|
| 188 |
+
/// This will return an error when the IP version of the local socket
|
| 189 |
+
/// does not match that returned from [`ToSocketAddrs`].
|
| 190 |
+
///
|
| 191 |
+
/// See [Issue #34202] for more details.
|
| 192 |
+
///
|
| 193 |
+
/// # Examples
|
| 194 |
+
///
|
| 195 |
+
/// ```no_run
|
| 196 |
+
/// use std::net::UdpSocket;
|
| 197 |
+
///
|
| 198 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 199 |
+
/// socket.send_to(&[0; 10], "127.0.0.1:4242").expect("couldn't send data");
|
| 200 |
+
/// ```
|
| 201 |
+
///
|
| 202 |
+
/// [Issue #34202]: https://github.com/rust-lang/rust/issues/34202
|
| 203 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 204 |
+
pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
|
| 205 |
+
match addr.to_socket_addrs()?.next() {
|
| 206 |
+
Some(addr) => self.0.send_to(buf, &addr),
|
| 207 |
+
None => Err(io::const_error!(ErrorKind::InvalidInput, "no addresses to send data to")),
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
/// Returns the socket address of the remote peer this socket was connected to.
|
| 212 |
+
///
|
| 213 |
+
/// # Examples
|
| 214 |
+
///
|
| 215 |
+
/// ```no_run
|
| 216 |
+
/// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
|
| 217 |
+
///
|
| 218 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 219 |
+
/// socket.connect("192.168.0.1:41203").expect("couldn't connect to address");
|
| 220 |
+
/// assert_eq!(socket.peer_addr().unwrap(),
|
| 221 |
+
/// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 41203)));
|
| 222 |
+
/// ```
|
| 223 |
+
///
|
| 224 |
+
/// If the socket isn't connected, it will return a [`NotConnected`] error.
|
| 225 |
+
///
|
| 226 |
+
/// [`NotConnected`]: io::ErrorKind::NotConnected
|
| 227 |
+
///
|
| 228 |
+
/// ```no_run
|
| 229 |
+
/// use std::net::UdpSocket;
|
| 230 |
+
///
|
| 231 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 232 |
+
/// assert_eq!(socket.peer_addr().unwrap_err().kind(),
|
| 233 |
+
/// std::io::ErrorKind::NotConnected);
|
| 234 |
+
/// ```
|
| 235 |
+
#[stable(feature = "udp_peer_addr", since = "1.40.0")]
|
| 236 |
+
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
|
| 237 |
+
self.0.peer_addr()
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
/// Returns the socket address that this socket was created from.
|
| 241 |
+
///
|
| 242 |
+
/// # Examples
|
| 243 |
+
///
|
| 244 |
+
/// ```no_run
|
| 245 |
+
/// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
|
| 246 |
+
///
|
| 247 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 248 |
+
/// assert_eq!(socket.local_addr().unwrap(),
|
| 249 |
+
/// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)));
|
| 250 |
+
/// ```
|
| 251 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 252 |
+
pub fn local_addr(&self) -> io::Result<SocketAddr> {
|
| 253 |
+
self.0.socket_addr()
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
/// Creates a new independently owned handle to the underlying socket.
|
| 257 |
+
///
|
| 258 |
+
/// The returned `UdpSocket` is a reference to the same socket that this
|
| 259 |
+
/// object references. Both handles will read and write the same port, and
|
| 260 |
+
/// options set on one socket will be propagated to the other.
|
| 261 |
+
///
|
| 262 |
+
/// # Examples
|
| 263 |
+
///
|
| 264 |
+
/// ```no_run
|
| 265 |
+
/// use std::net::UdpSocket;
|
| 266 |
+
///
|
| 267 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 268 |
+
/// let socket_clone = socket.try_clone().expect("couldn't clone the socket");
|
| 269 |
+
/// ```
|
| 270 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 271 |
+
pub fn try_clone(&self) -> io::Result<UdpSocket> {
|
| 272 |
+
self.0.duplicate().map(UdpSocket)
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
/// Sets the read timeout to the timeout specified.
|
| 276 |
+
///
|
| 277 |
+
/// If the value specified is [`None`], then [`read`] calls will block
|
| 278 |
+
/// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
|
| 279 |
+
/// passed to this method.
|
| 280 |
+
///
|
| 281 |
+
/// # Platform-specific behavior
|
| 282 |
+
///
|
| 283 |
+
/// Platforms may return a different error code whenever a read times out as
|
| 284 |
+
/// a result of setting this option. For example Unix typically returns an
|
| 285 |
+
/// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
|
| 286 |
+
///
|
| 287 |
+
/// [`read`]: io::Read::read
|
| 288 |
+
/// [`WouldBlock`]: io::ErrorKind::WouldBlock
|
| 289 |
+
/// [`TimedOut`]: io::ErrorKind::TimedOut
|
| 290 |
+
///
|
| 291 |
+
/// # Examples
|
| 292 |
+
///
|
| 293 |
+
/// ```no_run
|
| 294 |
+
/// use std::net::UdpSocket;
|
| 295 |
+
///
|
| 296 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 297 |
+
/// socket.set_read_timeout(None).expect("set_read_timeout call failed");
|
| 298 |
+
/// ```
|
| 299 |
+
///
|
| 300 |
+
/// An [`Err`] is returned if the zero [`Duration`] is passed to this
|
| 301 |
+
/// method:
|
| 302 |
+
///
|
| 303 |
+
/// ```no_run
|
| 304 |
+
/// use std::io;
|
| 305 |
+
/// use std::net::UdpSocket;
|
| 306 |
+
/// use std::time::Duration;
|
| 307 |
+
///
|
| 308 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
|
| 309 |
+
/// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
|
| 310 |
+
/// let err = result.unwrap_err();
|
| 311 |
+
/// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
|
| 312 |
+
/// ```
|
| 313 |
+
#[stable(feature = "socket_timeout", since = "1.4.0")]
|
| 314 |
+
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
|
| 315 |
+
self.0.set_read_timeout(dur)
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
/// Sets the write timeout to the timeout specified.
|
| 319 |
+
///
|
| 320 |
+
/// If the value specified is [`None`], then [`write`] calls will block
|
| 321 |
+
/// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
|
| 322 |
+
/// passed to this method.
|
| 323 |
+
///
|
| 324 |
+
/// # Platform-specific behavior
|
| 325 |
+
///
|
| 326 |
+
/// Platforms may return a different error code whenever a write times out
|
| 327 |
+
/// as a result of setting this option. For example Unix typically returns
|
| 328 |
+
/// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
|
| 329 |
+
///
|
| 330 |
+
/// [`write`]: io::Write::write
|
| 331 |
+
/// [`WouldBlock`]: io::ErrorKind::WouldBlock
|
| 332 |
+
/// [`TimedOut`]: io::ErrorKind::TimedOut
|
| 333 |
+
///
|
| 334 |
+
/// # Examples
|
| 335 |
+
///
|
| 336 |
+
/// ```no_run
|
| 337 |
+
/// use std::net::UdpSocket;
|
| 338 |
+
///
|
| 339 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 340 |
+
/// socket.set_write_timeout(None).expect("set_write_timeout call failed");
|
| 341 |
+
/// ```
|
| 342 |
+
///
|
| 343 |
+
/// An [`Err`] is returned if the zero [`Duration`] is passed to this
|
| 344 |
+
/// method:
|
| 345 |
+
///
|
| 346 |
+
/// ```no_run
|
| 347 |
+
/// use std::io;
|
| 348 |
+
/// use std::net::UdpSocket;
|
| 349 |
+
/// use std::time::Duration;
|
| 350 |
+
///
|
| 351 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
|
| 352 |
+
/// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
|
| 353 |
+
/// let err = result.unwrap_err();
|
| 354 |
+
/// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
|
| 355 |
+
/// ```
|
| 356 |
+
#[stable(feature = "socket_timeout", since = "1.4.0")]
|
| 357 |
+
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
|
| 358 |
+
self.0.set_write_timeout(dur)
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
/// Returns the read timeout of this socket.
|
| 362 |
+
///
|
| 363 |
+
/// If the timeout is [`None`], then [`read`] calls will block indefinitely.
|
| 364 |
+
///
|
| 365 |
+
/// [`read`]: io::Read::read
|
| 366 |
+
///
|
| 367 |
+
/// # Examples
|
| 368 |
+
///
|
| 369 |
+
/// ```no_run
|
| 370 |
+
/// use std::net::UdpSocket;
|
| 371 |
+
///
|
| 372 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 373 |
+
/// socket.set_read_timeout(None).expect("set_read_timeout call failed");
|
| 374 |
+
/// assert_eq!(socket.read_timeout().unwrap(), None);
|
| 375 |
+
/// ```
|
| 376 |
+
#[stable(feature = "socket_timeout", since = "1.4.0")]
|
| 377 |
+
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
|
| 378 |
+
self.0.read_timeout()
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
/// Returns the write timeout of this socket.
|
| 382 |
+
///
|
| 383 |
+
/// If the timeout is [`None`], then [`write`] calls will block indefinitely.
|
| 384 |
+
///
|
| 385 |
+
/// [`write`]: io::Write::write
|
| 386 |
+
///
|
| 387 |
+
/// # Examples
|
| 388 |
+
///
|
| 389 |
+
/// ```no_run
|
| 390 |
+
/// use std::net::UdpSocket;
|
| 391 |
+
///
|
| 392 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 393 |
+
/// socket.set_write_timeout(None).expect("set_write_timeout call failed");
|
| 394 |
+
/// assert_eq!(socket.write_timeout().unwrap(), None);
|
| 395 |
+
/// ```
|
| 396 |
+
#[stable(feature = "socket_timeout", since = "1.4.0")]
|
| 397 |
+
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
|
| 398 |
+
self.0.write_timeout()
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
/// Sets the value of the `SO_BROADCAST` option for this socket.
|
| 402 |
+
///
|
| 403 |
+
/// When enabled, this socket is allowed to send packets to a broadcast
|
| 404 |
+
/// address.
|
| 405 |
+
///
|
| 406 |
+
/// # Examples
|
| 407 |
+
///
|
| 408 |
+
/// ```no_run
|
| 409 |
+
/// use std::net::UdpSocket;
|
| 410 |
+
///
|
| 411 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 412 |
+
/// socket.set_broadcast(false).expect("set_broadcast call failed");
|
| 413 |
+
/// ```
|
| 414 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 415 |
+
pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
|
| 416 |
+
self.0.set_broadcast(broadcast)
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
/// Gets the value of the `SO_BROADCAST` option for this socket.
|
| 420 |
+
///
|
| 421 |
+
/// For more information about this option, see [`UdpSocket::set_broadcast`].
|
| 422 |
+
///
|
| 423 |
+
/// # Examples
|
| 424 |
+
///
|
| 425 |
+
/// ```no_run
|
| 426 |
+
/// use std::net::UdpSocket;
|
| 427 |
+
///
|
| 428 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 429 |
+
/// socket.set_broadcast(false).expect("set_broadcast call failed");
|
| 430 |
+
/// assert_eq!(socket.broadcast().unwrap(), false);
|
| 431 |
+
/// ```
|
| 432 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 433 |
+
pub fn broadcast(&self) -> io::Result<bool> {
|
| 434 |
+
self.0.broadcast()
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
/// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
|
| 438 |
+
///
|
| 439 |
+
/// If enabled, multicast packets will be looped back to the local socket.
|
| 440 |
+
/// Note that this might not have any effect on IPv6 sockets.
|
| 441 |
+
///
|
| 442 |
+
/// # Examples
|
| 443 |
+
///
|
| 444 |
+
/// ```no_run
|
| 445 |
+
/// use std::net::UdpSocket;
|
| 446 |
+
///
|
| 447 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 448 |
+
/// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
|
| 449 |
+
/// ```
|
| 450 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 451 |
+
pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
|
| 452 |
+
self.0.set_multicast_loop_v4(multicast_loop_v4)
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
/// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
|
| 456 |
+
///
|
| 457 |
+
/// For more information about this option, see [`UdpSocket::set_multicast_loop_v4`].
|
| 458 |
+
///
|
| 459 |
+
/// # Examples
|
| 460 |
+
///
|
| 461 |
+
/// ```no_run
|
| 462 |
+
/// use std::net::UdpSocket;
|
| 463 |
+
///
|
| 464 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 465 |
+
/// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
|
| 466 |
+
/// assert_eq!(socket.multicast_loop_v4().unwrap(), false);
|
| 467 |
+
/// ```
|
| 468 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 469 |
+
pub fn multicast_loop_v4(&self) -> io::Result<bool> {
|
| 470 |
+
self.0.multicast_loop_v4()
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
/// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
|
| 474 |
+
///
|
| 475 |
+
/// Indicates the time-to-live value of outgoing multicast packets for
|
| 476 |
+
/// this socket. The default value is 1 which means that multicast packets
|
| 477 |
+
/// don't leave the local network unless explicitly requested.
|
| 478 |
+
///
|
| 479 |
+
/// Note that this might not have any effect on IPv6 sockets.
|
| 480 |
+
///
|
| 481 |
+
/// # Examples
|
| 482 |
+
///
|
| 483 |
+
/// ```no_run
|
| 484 |
+
/// use std::net::UdpSocket;
|
| 485 |
+
///
|
| 486 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 487 |
+
/// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
|
| 488 |
+
/// ```
|
| 489 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 490 |
+
pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
|
| 491 |
+
self.0.set_multicast_ttl_v4(multicast_ttl_v4)
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
/// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
|
| 495 |
+
///
|
| 496 |
+
/// For more information about this option, see [`UdpSocket::set_multicast_ttl_v4`].
|
| 497 |
+
///
|
| 498 |
+
/// # Examples
|
| 499 |
+
///
|
| 500 |
+
/// ```no_run
|
| 501 |
+
/// use std::net::UdpSocket;
|
| 502 |
+
///
|
| 503 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 504 |
+
/// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
|
| 505 |
+
/// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
|
| 506 |
+
/// ```
|
| 507 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 508 |
+
pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
|
| 509 |
+
self.0.multicast_ttl_v4()
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
/// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
|
| 513 |
+
///
|
| 514 |
+
/// Controls whether this socket sees the multicast packets it sends itself.
|
| 515 |
+
/// Note that this might not have any affect on IPv4 sockets.
|
| 516 |
+
///
|
| 517 |
+
/// # Examples
|
| 518 |
+
///
|
| 519 |
+
/// ```no_run
|
| 520 |
+
/// use std::net::UdpSocket;
|
| 521 |
+
///
|
| 522 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 523 |
+
/// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
|
| 524 |
+
/// ```
|
| 525 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 526 |
+
pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
|
| 527 |
+
self.0.set_multicast_loop_v6(multicast_loop_v6)
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
/// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
|
| 531 |
+
///
|
| 532 |
+
/// For more information about this option, see [`UdpSocket::set_multicast_loop_v6`].
|
| 533 |
+
///
|
| 534 |
+
/// # Examples
|
| 535 |
+
///
|
| 536 |
+
/// ```no_run
|
| 537 |
+
/// use std::net::UdpSocket;
|
| 538 |
+
///
|
| 539 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 540 |
+
/// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
|
| 541 |
+
/// assert_eq!(socket.multicast_loop_v6().unwrap(), false);
|
| 542 |
+
/// ```
|
| 543 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 544 |
+
pub fn multicast_loop_v6(&self) -> io::Result<bool> {
|
| 545 |
+
self.0.multicast_loop_v6()
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
/// Sets the value for the `IP_TTL` option on this socket.
|
| 549 |
+
///
|
| 550 |
+
/// This value sets the time-to-live field that is used in every packet sent
|
| 551 |
+
/// from this socket.
|
| 552 |
+
///
|
| 553 |
+
/// # Examples
|
| 554 |
+
///
|
| 555 |
+
/// ```no_run
|
| 556 |
+
/// use std::net::UdpSocket;
|
| 557 |
+
///
|
| 558 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 559 |
+
/// socket.set_ttl(42).expect("set_ttl call failed");
|
| 560 |
+
/// ```
|
| 561 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 562 |
+
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
|
| 563 |
+
self.0.set_ttl(ttl)
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
/// Gets the value of the `IP_TTL` option for this socket.
|
| 567 |
+
///
|
| 568 |
+
/// For more information about this option, see [`UdpSocket::set_ttl`].
|
| 569 |
+
///
|
| 570 |
+
/// # Examples
|
| 571 |
+
///
|
| 572 |
+
/// ```no_run
|
| 573 |
+
/// use std::net::UdpSocket;
|
| 574 |
+
///
|
| 575 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 576 |
+
/// socket.set_ttl(42).expect("set_ttl call failed");
|
| 577 |
+
/// assert_eq!(socket.ttl().unwrap(), 42);
|
| 578 |
+
/// ```
|
| 579 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 580 |
+
pub fn ttl(&self) -> io::Result<u32> {
|
| 581 |
+
self.0.ttl()
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
/// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
|
| 585 |
+
///
|
| 586 |
+
/// This function specifies a new multicast group for this socket to join.
|
| 587 |
+
/// The address must be a valid multicast address, and `interface` is the
|
| 588 |
+
/// address of the local interface with which the system should join the
|
| 589 |
+
/// multicast group. If it's equal to [`UNSPECIFIED`](Ipv4Addr::UNSPECIFIED)
|
| 590 |
+
/// then an appropriate interface is chosen by the system.
|
| 591 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 592 |
+
pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
|
| 593 |
+
self.0.join_multicast_v4(multiaddr, interface)
|
| 594 |
+
}
|
| 595 |
+
|
| 596 |
+
/// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
|
| 597 |
+
///
|
| 598 |
+
/// This function specifies a new multicast group for this socket to join.
|
| 599 |
+
/// The address must be a valid multicast address, and `interface` is the
|
| 600 |
+
/// index of the interface to join/leave (or 0 to indicate any interface).
|
| 601 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 602 |
+
pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
|
| 603 |
+
self.0.join_multicast_v6(multiaddr, interface)
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
/// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
|
| 607 |
+
///
|
| 608 |
+
/// For more information about this option, see [`UdpSocket::join_multicast_v4`].
|
| 609 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 610 |
+
pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
|
| 611 |
+
self.0.leave_multicast_v4(multiaddr, interface)
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
/// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
|
| 615 |
+
///
|
| 616 |
+
/// For more information about this option, see [`UdpSocket::join_multicast_v6`].
|
| 617 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 618 |
+
pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
|
| 619 |
+
self.0.leave_multicast_v6(multiaddr, interface)
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
/// Gets the value of the `SO_ERROR` option on this socket.
|
| 623 |
+
///
|
| 624 |
+
/// This will retrieve the stored error in the underlying socket, clearing
|
| 625 |
+
/// the field in the process. This can be useful for checking errors between
|
| 626 |
+
/// calls.
|
| 627 |
+
///
|
| 628 |
+
/// # Examples
|
| 629 |
+
///
|
| 630 |
+
/// ```no_run
|
| 631 |
+
/// use std::net::UdpSocket;
|
| 632 |
+
///
|
| 633 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 634 |
+
/// match socket.take_error() {
|
| 635 |
+
/// Ok(Some(error)) => println!("UdpSocket error: {error:?}"),
|
| 636 |
+
/// Ok(None) => println!("No error"),
|
| 637 |
+
/// Err(error) => println!("UdpSocket.take_error failed: {error:?}"),
|
| 638 |
+
/// }
|
| 639 |
+
/// ```
|
| 640 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 641 |
+
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
|
| 642 |
+
self.0.take_error()
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
/// Connects this UDP socket to a remote address, allowing the `send` and
|
| 646 |
+
/// `recv` syscalls to be used to send data and also applies filters to only
|
| 647 |
+
/// receive data from the specified address.
|
| 648 |
+
///
|
| 649 |
+
/// If `addr` yields multiple addresses, `connect` will be attempted with
|
| 650 |
+
/// each of the addresses until the underlying OS function returns no
|
| 651 |
+
/// error. Note that usually, a successful `connect` call does not specify
|
| 652 |
+
/// that there is a remote server listening on the port, rather, such an
|
| 653 |
+
/// error would only be detected after the first send. If the OS returns an
|
| 654 |
+
/// error for each of the specified addresses, the error returned from the
|
| 655 |
+
/// last connection attempt (the last address) is returned.
|
| 656 |
+
///
|
| 657 |
+
/// # Examples
|
| 658 |
+
///
|
| 659 |
+
/// Creates a UDP socket bound to `127.0.0.1:3400` and connect the socket to
|
| 660 |
+
/// `127.0.0.1:8080`:
|
| 661 |
+
///
|
| 662 |
+
/// ```no_run
|
| 663 |
+
/// use std::net::UdpSocket;
|
| 664 |
+
///
|
| 665 |
+
/// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
|
| 666 |
+
/// socket.connect("127.0.0.1:8080").expect("connect function failed");
|
| 667 |
+
/// ```
|
| 668 |
+
///
|
| 669 |
+
/// Unlike in the TCP case, passing an array of addresses to the `connect`
|
| 670 |
+
/// function of a UDP socket is not a useful thing to do: The OS will be
|
| 671 |
+
/// unable to determine whether something is listening on the remote
|
| 672 |
+
/// address without the application sending data.
|
| 673 |
+
///
|
| 674 |
+
/// If your first `connect` is to a loopback address, subsequent
|
| 675 |
+
/// `connect`s to non-loopback addresses might fail, depending
|
| 676 |
+
/// on the platform.
|
| 677 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 678 |
+
pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
|
| 679 |
+
self.0.connect(addr)
|
| 680 |
+
}
|
| 681 |
+
|
| 682 |
+
/// Sends data on the socket to the remote address to which it is connected.
|
| 683 |
+
/// On success, returns the number of bytes written. Note that the operating
|
| 684 |
+
/// system may refuse buffers larger than 65507. However, partial writes are
|
| 685 |
+
/// not possible until buffer sizes above `i32::MAX`.
|
| 686 |
+
///
|
| 687 |
+
/// [`UdpSocket::connect`] will connect this socket to a remote address. This
|
| 688 |
+
/// method will fail if the socket is not connected.
|
| 689 |
+
///
|
| 690 |
+
/// # Examples
|
| 691 |
+
///
|
| 692 |
+
/// ```no_run
|
| 693 |
+
/// use std::net::UdpSocket;
|
| 694 |
+
///
|
| 695 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 696 |
+
/// socket.connect("127.0.0.1:8080").expect("connect function failed");
|
| 697 |
+
/// socket.send(&[0, 1, 2]).expect("couldn't send message");
|
| 698 |
+
/// ```
|
| 699 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 700 |
+
pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
|
| 701 |
+
self.0.send(buf)
|
| 702 |
+
}
|
| 703 |
+
|
| 704 |
+
/// Receives a single datagram message on the socket from the remote address to
|
| 705 |
+
/// which it is connected. On success, returns the number of bytes read.
|
| 706 |
+
///
|
| 707 |
+
/// The function must be called with valid byte array `buf` of sufficient size to
|
| 708 |
+
/// hold the message bytes. If a message is too long to fit in the supplied buffer,
|
| 709 |
+
/// excess bytes may be discarded.
|
| 710 |
+
///
|
| 711 |
+
/// [`UdpSocket::connect`] will connect this socket to a remote address. This
|
| 712 |
+
/// method will fail if the socket is not connected.
|
| 713 |
+
///
|
| 714 |
+
/// # Examples
|
| 715 |
+
///
|
| 716 |
+
/// ```no_run
|
| 717 |
+
/// use std::net::UdpSocket;
|
| 718 |
+
///
|
| 719 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 720 |
+
/// socket.connect("127.0.0.1:8080").expect("connect function failed");
|
| 721 |
+
/// let mut buf = [0; 10];
|
| 722 |
+
/// match socket.recv(&mut buf) {
|
| 723 |
+
/// Ok(received) => println!("received {received} bytes {:?}", &buf[..received]),
|
| 724 |
+
/// Err(e) => println!("recv function failed: {e:?}"),
|
| 725 |
+
/// }
|
| 726 |
+
/// ```
|
| 727 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 728 |
+
pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
|
| 729 |
+
self.0.recv(buf)
|
| 730 |
+
}
|
| 731 |
+
|
| 732 |
+
/// Receives single datagram on the socket from the remote address to which it is
|
| 733 |
+
/// connected, without removing the message from input queue. On success, returns
|
| 734 |
+
/// the number of bytes peeked.
|
| 735 |
+
///
|
| 736 |
+
/// The function must be called with valid byte array `buf` of sufficient size to
|
| 737 |
+
/// hold the message bytes. If a message is too long to fit in the supplied buffer,
|
| 738 |
+
/// excess bytes may be discarded.
|
| 739 |
+
///
|
| 740 |
+
/// Successive calls return the same data. This is accomplished by passing
|
| 741 |
+
/// `MSG_PEEK` as a flag to the underlying `recv` system call.
|
| 742 |
+
///
|
| 743 |
+
/// Do not use this function to implement busy waiting, instead use `libc::poll` to
|
| 744 |
+
/// synchronize IO events on one or more sockets.
|
| 745 |
+
///
|
| 746 |
+
/// [`UdpSocket::connect`] will connect this socket to a remote address. This
|
| 747 |
+
/// method will fail if the socket is not connected.
|
| 748 |
+
///
|
| 749 |
+
/// # Errors
|
| 750 |
+
///
|
| 751 |
+
/// This method will fail if the socket is not connected. The `connect` method
|
| 752 |
+
/// will connect this socket to a remote address.
|
| 753 |
+
///
|
| 754 |
+
/// # Examples
|
| 755 |
+
///
|
| 756 |
+
/// ```no_run
|
| 757 |
+
/// use std::net::UdpSocket;
|
| 758 |
+
///
|
| 759 |
+
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
|
| 760 |
+
/// socket.connect("127.0.0.1:8080").expect("connect function failed");
|
| 761 |
+
/// let mut buf = [0; 10];
|
| 762 |
+
/// match socket.peek(&mut buf) {
|
| 763 |
+
/// Ok(received) => println!("received {received} bytes"),
|
| 764 |
+
/// Err(e) => println!("peek function failed: {e:?}"),
|
| 765 |
+
/// }
|
| 766 |
+
/// ```
|
| 767 |
+
#[stable(feature = "peek", since = "1.18.0")]
|
| 768 |
+
pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
|
| 769 |
+
self.0.peek(buf)
|
| 770 |
+
}
|
| 771 |
+
|
| 772 |
+
/// Moves this UDP socket into or out of nonblocking mode.
|
| 773 |
+
///
|
| 774 |
+
/// This will result in `recv`, `recv_from`, `send`, and `send_to` system
|
| 775 |
+
/// operations becoming nonblocking, i.e., immediately returning from their
|
| 776 |
+
/// calls. If the IO operation is successful, `Ok` is returned and no
|
| 777 |
+
/// further action is required. If the IO operation could not be completed
|
| 778 |
+
/// and needs to be retried, an error with kind
|
| 779 |
+
/// [`io::ErrorKind::WouldBlock`] is returned.
|
| 780 |
+
///
|
| 781 |
+
/// On Unix platforms, calling this method corresponds to calling `fcntl`
|
| 782 |
+
/// `FIONBIO`. On Windows calling this method corresponds to calling
|
| 783 |
+
/// `ioctlsocket` `FIONBIO`.
|
| 784 |
+
///
|
| 785 |
+
/// # Examples
|
| 786 |
+
///
|
| 787 |
+
/// Creates a UDP socket bound to `127.0.0.1:7878` and read bytes in
|
| 788 |
+
/// nonblocking mode:
|
| 789 |
+
///
|
| 790 |
+
/// ```no_run
|
| 791 |
+
/// use std::io;
|
| 792 |
+
/// use std::net::UdpSocket;
|
| 793 |
+
///
|
| 794 |
+
/// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
|
| 795 |
+
/// socket.set_nonblocking(true).unwrap();
|
| 796 |
+
///
|
| 797 |
+
/// # fn wait_for_fd() { unimplemented!() }
|
| 798 |
+
/// let mut buf = [0; 10];
|
| 799 |
+
/// let (num_bytes_read, _) = loop {
|
| 800 |
+
/// match socket.recv_from(&mut buf) {
|
| 801 |
+
/// Ok(n) => break n,
|
| 802 |
+
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
|
| 803 |
+
/// // wait until network socket is ready, typically implemented
|
| 804 |
+
/// // via platform-specific APIs such as epoll or IOCP
|
| 805 |
+
/// wait_for_fd();
|
| 806 |
+
/// }
|
| 807 |
+
/// Err(e) => panic!("encountered IO error: {e}"),
|
| 808 |
+
/// }
|
| 809 |
+
/// };
|
| 810 |
+
/// println!("bytes: {:?}", &buf[..num_bytes_read]);
|
| 811 |
+
/// ```
|
| 812 |
+
#[stable(feature = "net2_mutators", since = "1.9.0")]
|
| 813 |
+
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
|
| 814 |
+
self.0.set_nonblocking(nonblocking)
|
| 815 |
+
}
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
// In addition to the `impl`s here, `UdpSocket` also has `impl`s for
|
| 819 |
+
// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
|
| 820 |
+
// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
|
| 821 |
+
// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
|
| 822 |
+
// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
|
| 823 |
+
|
| 824 |
+
impl AsInner<net_imp::UdpSocket> for UdpSocket {
|
| 825 |
+
#[inline]
|
| 826 |
+
fn as_inner(&self) -> &net_imp::UdpSocket {
|
| 827 |
+
&self.0
|
| 828 |
+
}
|
| 829 |
+
}
|
| 830 |
+
|
| 831 |
+
impl FromInner<net_imp::UdpSocket> for UdpSocket {
|
| 832 |
+
fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket {
|
| 833 |
+
UdpSocket(inner)
|
| 834 |
+
}
|
| 835 |
+
}
|
| 836 |
+
|
| 837 |
+
impl IntoInner<net_imp::UdpSocket> for UdpSocket {
|
| 838 |
+
fn into_inner(self) -> net_imp::UdpSocket {
|
| 839 |
+
self.0
|
| 840 |
+
}
|
| 841 |
+
}
|
| 842 |
+
|
| 843 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 844 |
+
impl fmt::Debug for UdpSocket {
|
| 845 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 846 |
+
self.0.fmt(f)
|
| 847 |
+
}
|
| 848 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/num/f128.rs
ADDED
|
@@ -0,0 +1,1086 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Constants for the `f128` quadruple-precision floating point type.
|
| 2 |
+
//!
|
| 3 |
+
//! *[See also the `f128` primitive type](primitive@f128).*
|
| 4 |
+
//!
|
| 5 |
+
//! Mathematically significant numbers are provided in the `consts` sub-module.
|
| 6 |
+
|
| 7 |
+
#![unstable(feature = "f128", issue = "116909")]
|
| 8 |
+
#![doc(test(attr(feature(cfg_target_has_reliable_f16_f128), expect(internal_features))))]
|
| 9 |
+
|
| 10 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 11 |
+
pub use core::f128::consts;
|
| 12 |
+
|
| 13 |
+
#[cfg(not(test))]
|
| 14 |
+
use crate::intrinsics;
|
| 15 |
+
#[cfg(not(test))]
|
| 16 |
+
use crate::sys::cmath;
|
| 17 |
+
|
| 18 |
+
#[cfg(not(test))]
|
| 19 |
+
#[doc(test(attr(allow(unused_features))))]
|
| 20 |
+
impl f128 {
|
| 21 |
+
/// Raises a number to a floating point power.
|
| 22 |
+
///
|
| 23 |
+
/// Note that this function is special in that it can return non-NaN results for NaN inputs. For
|
| 24 |
+
/// example, `f128::powf(f128::NAN, 0.0)` returns `1.0`. However, if an input is a *signaling*
|
| 25 |
+
/// NaN, then the result is non-deterministically either a NaN or the result that the
|
| 26 |
+
/// corresponding quiet NaN would produce.
|
| 27 |
+
///
|
| 28 |
+
/// # Unspecified precision
|
| 29 |
+
///
|
| 30 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 31 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 32 |
+
///
|
| 33 |
+
/// # Examples
|
| 34 |
+
///
|
| 35 |
+
/// ```
|
| 36 |
+
/// #![feature(f128)]
|
| 37 |
+
/// # #[cfg(not(miri))]
|
| 38 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 39 |
+
///
|
| 40 |
+
/// let x = 2.0_f128;
|
| 41 |
+
/// let abs_difference = (x.powf(2.0) - (x * x)).abs();
|
| 42 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 43 |
+
///
|
| 44 |
+
/// assert_eq!(f128::powf(1.0, f128::NAN), 1.0);
|
| 45 |
+
/// assert_eq!(f128::powf(f128::NAN, 0.0), 1.0);
|
| 46 |
+
/// assert_eq!(f128::powf(0.0, 0.0), 1.0);
|
| 47 |
+
/// # }
|
| 48 |
+
/// ```
|
| 49 |
+
#[inline]
|
| 50 |
+
#[rustc_allow_incoherent_impl]
|
| 51 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 52 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 53 |
+
pub fn powf(self, n: f128) -> f128 {
|
| 54 |
+
intrinsics::powf128(self, n)
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/// Returns `e^(self)`, (the exponential function).
|
| 58 |
+
///
|
| 59 |
+
/// # Unspecified precision
|
| 60 |
+
///
|
| 61 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 62 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 63 |
+
///
|
| 64 |
+
/// # Examples
|
| 65 |
+
///
|
| 66 |
+
/// ```
|
| 67 |
+
/// #![feature(f128)]
|
| 68 |
+
/// # #[cfg(not(miri))]
|
| 69 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 70 |
+
///
|
| 71 |
+
/// let one = 1.0f128;
|
| 72 |
+
/// // e^1
|
| 73 |
+
/// let e = one.exp();
|
| 74 |
+
///
|
| 75 |
+
/// // ln(e) - 1 == 0
|
| 76 |
+
/// let abs_difference = (e.ln() - 1.0).abs();
|
| 77 |
+
///
|
| 78 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 79 |
+
/// # }
|
| 80 |
+
/// ```
|
| 81 |
+
#[inline]
|
| 82 |
+
#[rustc_allow_incoherent_impl]
|
| 83 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 84 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 85 |
+
pub fn exp(self) -> f128 {
|
| 86 |
+
intrinsics::expf128(self)
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
/// Returns `2^(self)`.
|
| 90 |
+
///
|
| 91 |
+
/// # Unspecified precision
|
| 92 |
+
///
|
| 93 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 94 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 95 |
+
///
|
| 96 |
+
/// # Examples
|
| 97 |
+
///
|
| 98 |
+
/// ```
|
| 99 |
+
/// #![feature(f128)]
|
| 100 |
+
/// # #[cfg(not(miri))]
|
| 101 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 102 |
+
///
|
| 103 |
+
/// let f = 2.0f128;
|
| 104 |
+
///
|
| 105 |
+
/// // 2^2 - 4 == 0
|
| 106 |
+
/// let abs_difference = (f.exp2() - 4.0).abs();
|
| 107 |
+
///
|
| 108 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 109 |
+
/// # }
|
| 110 |
+
/// ```
|
| 111 |
+
#[inline]
|
| 112 |
+
#[rustc_allow_incoherent_impl]
|
| 113 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 114 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 115 |
+
pub fn exp2(self) -> f128 {
|
| 116 |
+
intrinsics::exp2f128(self)
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
/// Returns the natural logarithm of the number.
|
| 120 |
+
///
|
| 121 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 122 |
+
///
|
| 123 |
+
/// # Unspecified precision
|
| 124 |
+
///
|
| 125 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 126 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 127 |
+
///
|
| 128 |
+
/// # Examples
|
| 129 |
+
///
|
| 130 |
+
/// ```
|
| 131 |
+
/// #![feature(f128)]
|
| 132 |
+
/// # #[cfg(not(miri))]
|
| 133 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 134 |
+
///
|
| 135 |
+
/// let one = 1.0f128;
|
| 136 |
+
/// // e^1
|
| 137 |
+
/// let e = one.exp();
|
| 138 |
+
///
|
| 139 |
+
/// // ln(e) - 1 == 0
|
| 140 |
+
/// let abs_difference = (e.ln() - 1.0).abs();
|
| 141 |
+
///
|
| 142 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 143 |
+
/// # }
|
| 144 |
+
/// ```
|
| 145 |
+
///
|
| 146 |
+
/// Non-positive values:
|
| 147 |
+
/// ```
|
| 148 |
+
/// #![feature(f128)]
|
| 149 |
+
/// # #[cfg(not(miri))]
|
| 150 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 151 |
+
///
|
| 152 |
+
/// assert_eq!(0_f128.ln(), f128::NEG_INFINITY);
|
| 153 |
+
/// assert!((-42_f128).ln().is_nan());
|
| 154 |
+
/// # }
|
| 155 |
+
/// ```
|
| 156 |
+
#[inline]
|
| 157 |
+
#[rustc_allow_incoherent_impl]
|
| 158 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 159 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 160 |
+
pub fn ln(self) -> f128 {
|
| 161 |
+
intrinsics::logf128(self)
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
/// Returns the logarithm of the number with respect to an arbitrary base.
|
| 165 |
+
///
|
| 166 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 167 |
+
///
|
| 168 |
+
/// The result might not be correctly rounded owing to implementation details;
|
| 169 |
+
/// `self.log2()` can produce more accurate results for base 2, and
|
| 170 |
+
/// `self.log10()` can produce more accurate results for base 10.
|
| 171 |
+
///
|
| 172 |
+
/// # Unspecified precision
|
| 173 |
+
///
|
| 174 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 175 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 176 |
+
///
|
| 177 |
+
/// # Examples
|
| 178 |
+
///
|
| 179 |
+
/// ```
|
| 180 |
+
/// #![feature(f128)]
|
| 181 |
+
/// # #[cfg(not(miri))]
|
| 182 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 183 |
+
///
|
| 184 |
+
/// let five = 5.0f128;
|
| 185 |
+
///
|
| 186 |
+
/// // log5(5) - 1 == 0
|
| 187 |
+
/// let abs_difference = (five.log(5.0) - 1.0).abs();
|
| 188 |
+
///
|
| 189 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 190 |
+
/// # }
|
| 191 |
+
/// ```
|
| 192 |
+
///
|
| 193 |
+
/// Non-positive values:
|
| 194 |
+
/// ```
|
| 195 |
+
/// #![feature(f128)]
|
| 196 |
+
/// # #[cfg(not(miri))]
|
| 197 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 198 |
+
///
|
| 199 |
+
/// assert_eq!(0_f128.log(10.0), f128::NEG_INFINITY);
|
| 200 |
+
/// assert!((-42_f128).log(10.0).is_nan());
|
| 201 |
+
/// # }
|
| 202 |
+
/// ```
|
| 203 |
+
#[inline]
|
| 204 |
+
#[rustc_allow_incoherent_impl]
|
| 205 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 206 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 207 |
+
pub fn log(self, base: f128) -> f128 {
|
| 208 |
+
self.ln() / base.ln()
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
/// Returns the base 2 logarithm of the number.
|
| 212 |
+
///
|
| 213 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 214 |
+
///
|
| 215 |
+
/// # Unspecified precision
|
| 216 |
+
///
|
| 217 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 218 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 219 |
+
///
|
| 220 |
+
/// # Examples
|
| 221 |
+
///
|
| 222 |
+
/// ```
|
| 223 |
+
/// #![feature(f128)]
|
| 224 |
+
/// # #[cfg(not(miri))]
|
| 225 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 226 |
+
///
|
| 227 |
+
/// let two = 2.0f128;
|
| 228 |
+
///
|
| 229 |
+
/// // log2(2) - 1 == 0
|
| 230 |
+
/// let abs_difference = (two.log2() - 1.0).abs();
|
| 231 |
+
///
|
| 232 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 233 |
+
/// # }
|
| 234 |
+
/// ```
|
| 235 |
+
///
|
| 236 |
+
/// Non-positive values:
|
| 237 |
+
/// ```
|
| 238 |
+
/// #![feature(f128)]
|
| 239 |
+
/// # #[cfg(not(miri))]
|
| 240 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 241 |
+
///
|
| 242 |
+
/// assert_eq!(0_f128.log2(), f128::NEG_INFINITY);
|
| 243 |
+
/// assert!((-42_f128).log2().is_nan());
|
| 244 |
+
/// # }
|
| 245 |
+
/// ```
|
| 246 |
+
#[inline]
|
| 247 |
+
#[rustc_allow_incoherent_impl]
|
| 248 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 249 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 250 |
+
pub fn log2(self) -> f128 {
|
| 251 |
+
intrinsics::log2f128(self)
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
/// Returns the base 10 logarithm of the number.
|
| 255 |
+
///
|
| 256 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 257 |
+
///
|
| 258 |
+
/// # Unspecified precision
|
| 259 |
+
///
|
| 260 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 261 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 262 |
+
///
|
| 263 |
+
/// # Examples
|
| 264 |
+
///
|
| 265 |
+
/// ```
|
| 266 |
+
/// #![feature(f128)]
|
| 267 |
+
/// # #[cfg(not(miri))]
|
| 268 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 269 |
+
///
|
| 270 |
+
/// let ten = 10.0f128;
|
| 271 |
+
///
|
| 272 |
+
/// // log10(10) - 1 == 0
|
| 273 |
+
/// let abs_difference = (ten.log10() - 1.0).abs();
|
| 274 |
+
///
|
| 275 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 276 |
+
/// # }
|
| 277 |
+
/// ```
|
| 278 |
+
///
|
| 279 |
+
/// Non-positive values:
|
| 280 |
+
/// ```
|
| 281 |
+
/// #![feature(f128)]
|
| 282 |
+
/// # #[cfg(not(miri))]
|
| 283 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 284 |
+
///
|
| 285 |
+
/// assert_eq!(0_f128.log10(), f128::NEG_INFINITY);
|
| 286 |
+
/// assert!((-42_f128).log10().is_nan());
|
| 287 |
+
/// # }
|
| 288 |
+
/// ```
|
| 289 |
+
#[inline]
|
| 290 |
+
#[rustc_allow_incoherent_impl]
|
| 291 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 292 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 293 |
+
pub fn log10(self) -> f128 {
|
| 294 |
+
intrinsics::log10f128(self)
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
/// Returns the cube root of a number.
|
| 298 |
+
///
|
| 299 |
+
/// # Unspecified precision
|
| 300 |
+
///
|
| 301 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 302 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 303 |
+
///
|
| 304 |
+
///
|
| 305 |
+
/// This function currently corresponds to the `cbrtf128` from libc on Unix
|
| 306 |
+
/// and Windows. Note that this might change in the future.
|
| 307 |
+
///
|
| 308 |
+
/// # Examples
|
| 309 |
+
///
|
| 310 |
+
/// ```
|
| 311 |
+
/// #![feature(f128)]
|
| 312 |
+
/// # #[cfg(not(miri))]
|
| 313 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 314 |
+
///
|
| 315 |
+
/// let x = 8.0f128;
|
| 316 |
+
///
|
| 317 |
+
/// // x^(1/3) - 2 == 0
|
| 318 |
+
/// let abs_difference = (x.cbrt() - 2.0).abs();
|
| 319 |
+
///
|
| 320 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 321 |
+
/// # }
|
| 322 |
+
/// ```
|
| 323 |
+
#[inline]
|
| 324 |
+
#[rustc_allow_incoherent_impl]
|
| 325 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 326 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 327 |
+
pub fn cbrt(self) -> f128 {
|
| 328 |
+
cmath::cbrtf128(self)
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
/// Compute the distance between the origin and a point (`x`, `y`) on the
|
| 332 |
+
/// Euclidean plane. Equivalently, compute the length of the hypotenuse of a
|
| 333 |
+
/// right-angle triangle with other sides having length `x.abs()` and
|
| 334 |
+
/// `y.abs()`.
|
| 335 |
+
///
|
| 336 |
+
/// # Unspecified precision
|
| 337 |
+
///
|
| 338 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 339 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 340 |
+
///
|
| 341 |
+
///
|
| 342 |
+
/// This function currently corresponds to the `hypotf128` from libc on Unix
|
| 343 |
+
/// and Windows. Note that this might change in the future.
|
| 344 |
+
///
|
| 345 |
+
/// # Examples
|
| 346 |
+
///
|
| 347 |
+
/// ```
|
| 348 |
+
/// #![feature(f128)]
|
| 349 |
+
/// # #[cfg(not(miri))]
|
| 350 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 351 |
+
///
|
| 352 |
+
/// let x = 2.0f128;
|
| 353 |
+
/// let y = 3.0f128;
|
| 354 |
+
///
|
| 355 |
+
/// // sqrt(x^2 + y^2)
|
| 356 |
+
/// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
|
| 357 |
+
///
|
| 358 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 359 |
+
/// # }
|
| 360 |
+
/// ```
|
| 361 |
+
#[inline]
|
| 362 |
+
#[rustc_allow_incoherent_impl]
|
| 363 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 364 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 365 |
+
pub fn hypot(self, other: f128) -> f128 {
|
| 366 |
+
cmath::hypotf128(self, other)
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
/// Computes the sine of a number (in radians).
|
| 370 |
+
///
|
| 371 |
+
/// # Unspecified precision
|
| 372 |
+
///
|
| 373 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 374 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 375 |
+
///
|
| 376 |
+
/// # Examples
|
| 377 |
+
///
|
| 378 |
+
/// ```
|
| 379 |
+
/// #![feature(f128)]
|
| 380 |
+
/// # #[cfg(not(miri))]
|
| 381 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 382 |
+
///
|
| 383 |
+
/// let x = std::f128::consts::FRAC_PI_2;
|
| 384 |
+
///
|
| 385 |
+
/// let abs_difference = (x.sin() - 1.0).abs();
|
| 386 |
+
///
|
| 387 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 388 |
+
/// # }
|
| 389 |
+
/// ```
|
| 390 |
+
#[inline]
|
| 391 |
+
#[rustc_allow_incoherent_impl]
|
| 392 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 393 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 394 |
+
pub fn sin(self) -> f128 {
|
| 395 |
+
intrinsics::sinf128(self)
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
/// Computes the cosine of a number (in radians).
|
| 399 |
+
///
|
| 400 |
+
/// # Unspecified precision
|
| 401 |
+
///
|
| 402 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 403 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 404 |
+
///
|
| 405 |
+
/// # Examples
|
| 406 |
+
///
|
| 407 |
+
/// ```
|
| 408 |
+
/// #![feature(f128)]
|
| 409 |
+
/// # #[cfg(not(miri))]
|
| 410 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 411 |
+
///
|
| 412 |
+
/// let x = 2.0 * std::f128::consts::PI;
|
| 413 |
+
///
|
| 414 |
+
/// let abs_difference = (x.cos() - 1.0).abs();
|
| 415 |
+
///
|
| 416 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 417 |
+
/// # }
|
| 418 |
+
/// ```
|
| 419 |
+
#[inline]
|
| 420 |
+
#[rustc_allow_incoherent_impl]
|
| 421 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 422 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 423 |
+
pub fn cos(self) -> f128 {
|
| 424 |
+
intrinsics::cosf128(self)
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
/// Computes the tangent of a number (in radians).
|
| 428 |
+
///
|
| 429 |
+
/// # Unspecified precision
|
| 430 |
+
///
|
| 431 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 432 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 433 |
+
///
|
| 434 |
+
/// This function currently corresponds to the `tanf128` from libc on Unix and
|
| 435 |
+
/// Windows. Note that this might change in the future.
|
| 436 |
+
///
|
| 437 |
+
/// # Examples
|
| 438 |
+
///
|
| 439 |
+
/// ```
|
| 440 |
+
/// #![feature(f128)]
|
| 441 |
+
/// # #[cfg(not(miri))]
|
| 442 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 443 |
+
///
|
| 444 |
+
/// let x = std::f128::consts::FRAC_PI_4;
|
| 445 |
+
/// let abs_difference = (x.tan() - 1.0).abs();
|
| 446 |
+
///
|
| 447 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 448 |
+
/// # }
|
| 449 |
+
/// ```
|
| 450 |
+
#[inline]
|
| 451 |
+
#[rustc_allow_incoherent_impl]
|
| 452 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 453 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 454 |
+
pub fn tan(self) -> f128 {
|
| 455 |
+
cmath::tanf128(self)
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
/// Computes the arcsine of a number. Return value is in radians in
|
| 459 |
+
/// the range [-pi/2, pi/2] or NaN if the number is outside the range
|
| 460 |
+
/// [-1, 1].
|
| 461 |
+
///
|
| 462 |
+
/// # Unspecified precision
|
| 463 |
+
///
|
| 464 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 465 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 466 |
+
///
|
| 467 |
+
/// This function currently corresponds to the `asinf128` from libc on Unix
|
| 468 |
+
/// and Windows. Note that this might change in the future.
|
| 469 |
+
///
|
| 470 |
+
/// # Examples
|
| 471 |
+
///
|
| 472 |
+
/// ```
|
| 473 |
+
/// #![feature(f128)]
|
| 474 |
+
/// # #[cfg(not(miri))]
|
| 475 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 476 |
+
///
|
| 477 |
+
/// let f = std::f128::consts::FRAC_PI_4;
|
| 478 |
+
///
|
| 479 |
+
/// // asin(sin(pi/2))
|
| 480 |
+
/// let abs_difference = (f.sin().asin() - f).abs();
|
| 481 |
+
///
|
| 482 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 483 |
+
/// # }
|
| 484 |
+
/// ```
|
| 485 |
+
#[inline]
|
| 486 |
+
#[doc(alias = "arcsin")]
|
| 487 |
+
#[rustc_allow_incoherent_impl]
|
| 488 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 489 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 490 |
+
pub fn asin(self) -> f128 {
|
| 491 |
+
cmath::asinf128(self)
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
/// Computes the arccosine of a number. Return value is in radians in
|
| 495 |
+
/// the range [0, pi] or NaN if the number is outside the range
|
| 496 |
+
/// [-1, 1].
|
| 497 |
+
///
|
| 498 |
+
/// # Unspecified precision
|
| 499 |
+
///
|
| 500 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 501 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 502 |
+
///
|
| 503 |
+
/// This function currently corresponds to the `acosf128` from libc on Unix
|
| 504 |
+
/// and Windows. Note that this might change in the future.
|
| 505 |
+
///
|
| 506 |
+
/// # Examples
|
| 507 |
+
///
|
| 508 |
+
/// ```
|
| 509 |
+
/// #![feature(f128)]
|
| 510 |
+
/// # #[cfg(not(miri))]
|
| 511 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 512 |
+
///
|
| 513 |
+
/// let f = std::f128::consts::FRAC_PI_4;
|
| 514 |
+
///
|
| 515 |
+
/// // acos(cos(pi/4))
|
| 516 |
+
/// let abs_difference = (f.cos().acos() - std::f128::consts::FRAC_PI_4).abs();
|
| 517 |
+
///
|
| 518 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 519 |
+
/// # }
|
| 520 |
+
/// ```
|
| 521 |
+
#[inline]
|
| 522 |
+
#[doc(alias = "arccos")]
|
| 523 |
+
#[rustc_allow_incoherent_impl]
|
| 524 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 525 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 526 |
+
pub fn acos(self) -> f128 {
|
| 527 |
+
cmath::acosf128(self)
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
/// Computes the arctangent of a number. Return value is in radians in the
|
| 531 |
+
/// range [-pi/2, pi/2];
|
| 532 |
+
///
|
| 533 |
+
/// # Unspecified precision
|
| 534 |
+
///
|
| 535 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 536 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 537 |
+
///
|
| 538 |
+
/// This function currently corresponds to the `atanf128` from libc on Unix
|
| 539 |
+
/// and Windows. Note that this might change in the future.
|
| 540 |
+
///
|
| 541 |
+
/// # Examples
|
| 542 |
+
///
|
| 543 |
+
/// ```
|
| 544 |
+
/// #![feature(f128)]
|
| 545 |
+
/// # #[cfg(not(miri))]
|
| 546 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 547 |
+
///
|
| 548 |
+
/// let f = 1.0f128;
|
| 549 |
+
///
|
| 550 |
+
/// // atan(tan(1))
|
| 551 |
+
/// let abs_difference = (f.tan().atan() - 1.0).abs();
|
| 552 |
+
///
|
| 553 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 554 |
+
/// # }
|
| 555 |
+
/// ```
|
| 556 |
+
#[inline]
|
| 557 |
+
#[doc(alias = "arctan")]
|
| 558 |
+
#[rustc_allow_incoherent_impl]
|
| 559 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 560 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 561 |
+
pub fn atan(self) -> f128 {
|
| 562 |
+
cmath::atanf128(self)
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
/// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) in radians.
|
| 566 |
+
///
|
| 567 |
+
/// | `x` | `y` | Piecewise Definition | Range |
|
| 568 |
+
/// |---------|---------|----------------------|---------------|
|
| 569 |
+
/// | `>= +0` | `>= +0` | `arctan(y/x)` | `[+0, +pi/2]` |
|
| 570 |
+
/// | `>= +0` | `<= -0` | `arctan(y/x)` | `[-pi/2, -0]` |
|
| 571 |
+
/// | `<= -0` | `>= +0` | `arctan(y/x) + pi` | `[+pi/2, +pi]`|
|
| 572 |
+
/// | `<= -0` | `<= -0` | `arctan(y/x) - pi` | `[-pi, -pi/2]`|
|
| 573 |
+
///
|
| 574 |
+
/// # Unspecified precision
|
| 575 |
+
///
|
| 576 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 577 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 578 |
+
///
|
| 579 |
+
/// This function currently corresponds to the `atan2f128` from libc on Unix
|
| 580 |
+
/// and Windows. Note that this might change in the future.
|
| 581 |
+
///
|
| 582 |
+
/// # Examples
|
| 583 |
+
///
|
| 584 |
+
/// ```
|
| 585 |
+
/// #![feature(f128)]
|
| 586 |
+
/// # #[cfg(not(miri))]
|
| 587 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 588 |
+
///
|
| 589 |
+
/// // Positive angles measured counter-clockwise
|
| 590 |
+
/// // from positive x axis
|
| 591 |
+
/// // -pi/4 radians (45 deg clockwise)
|
| 592 |
+
/// let x1 = 3.0f128;
|
| 593 |
+
/// let y1 = -3.0f128;
|
| 594 |
+
///
|
| 595 |
+
/// // 3pi/4 radians (135 deg counter-clockwise)
|
| 596 |
+
/// let x2 = -3.0f128;
|
| 597 |
+
/// let y2 = 3.0f128;
|
| 598 |
+
///
|
| 599 |
+
/// let abs_difference_1 = (y1.atan2(x1) - (-std::f128::consts::FRAC_PI_4)).abs();
|
| 600 |
+
/// let abs_difference_2 = (y2.atan2(x2) - (3.0 * std::f128::consts::FRAC_PI_4)).abs();
|
| 601 |
+
///
|
| 602 |
+
/// assert!(abs_difference_1 <= f128::EPSILON);
|
| 603 |
+
/// assert!(abs_difference_2 <= f128::EPSILON);
|
| 604 |
+
/// # }
|
| 605 |
+
/// ```
|
| 606 |
+
#[inline]
|
| 607 |
+
#[rustc_allow_incoherent_impl]
|
| 608 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 609 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 610 |
+
pub fn atan2(self, other: f128) -> f128 {
|
| 611 |
+
cmath::atan2f128(self, other)
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
/// Simultaneously computes the sine and cosine of the number, `x`. Returns
|
| 615 |
+
/// `(sin(x), cos(x))`.
|
| 616 |
+
///
|
| 617 |
+
/// # Unspecified precision
|
| 618 |
+
///
|
| 619 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 620 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 621 |
+
///
|
| 622 |
+
/// This function currently corresponds to the `(f128::sin(x),
|
| 623 |
+
/// f128::cos(x))`. Note that this might change in the future.
|
| 624 |
+
///
|
| 625 |
+
/// # Examples
|
| 626 |
+
///
|
| 627 |
+
/// ```
|
| 628 |
+
/// #![feature(f128)]
|
| 629 |
+
/// # #[cfg(not(miri))]
|
| 630 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 631 |
+
///
|
| 632 |
+
/// let x = std::f128::consts::FRAC_PI_4;
|
| 633 |
+
/// let f = x.sin_cos();
|
| 634 |
+
///
|
| 635 |
+
/// let abs_difference_0 = (f.0 - x.sin()).abs();
|
| 636 |
+
/// let abs_difference_1 = (f.1 - x.cos()).abs();
|
| 637 |
+
///
|
| 638 |
+
/// assert!(abs_difference_0 <= f128::EPSILON);
|
| 639 |
+
/// assert!(abs_difference_1 <= f128::EPSILON);
|
| 640 |
+
/// # }
|
| 641 |
+
/// ```
|
| 642 |
+
#[inline]
|
| 643 |
+
#[doc(alias = "sincos")]
|
| 644 |
+
#[rustc_allow_incoherent_impl]
|
| 645 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 646 |
+
pub fn sin_cos(self) -> (f128, f128) {
|
| 647 |
+
(self.sin(), self.cos())
|
| 648 |
+
}
|
| 649 |
+
|
| 650 |
+
/// Returns `e^(self) - 1` in a way that is accurate even if the
|
| 651 |
+
/// number is close to zero.
|
| 652 |
+
///
|
| 653 |
+
/// # Unspecified precision
|
| 654 |
+
///
|
| 655 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 656 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 657 |
+
///
|
| 658 |
+
/// This function currently corresponds to the `expm1f128` from libc on Unix
|
| 659 |
+
/// and Windows. Note that this might change in the future.
|
| 660 |
+
///
|
| 661 |
+
/// # Examples
|
| 662 |
+
///
|
| 663 |
+
/// ```
|
| 664 |
+
/// #![feature(f128)]
|
| 665 |
+
/// # #[cfg(not(miri))]
|
| 666 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 667 |
+
///
|
| 668 |
+
/// let x = 1e-8_f128;
|
| 669 |
+
///
|
| 670 |
+
/// // for very small x, e^x is approximately 1 + x + x^2 / 2
|
| 671 |
+
/// let approx = x + x * x / 2.0;
|
| 672 |
+
/// let abs_difference = (x.exp_m1() - approx).abs();
|
| 673 |
+
///
|
| 674 |
+
/// assert!(abs_difference < 1e-10);
|
| 675 |
+
/// # }
|
| 676 |
+
/// ```
|
| 677 |
+
#[inline]
|
| 678 |
+
#[rustc_allow_incoherent_impl]
|
| 679 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 680 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 681 |
+
pub fn exp_m1(self) -> f128 {
|
| 682 |
+
cmath::expm1f128(self)
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
/// Returns `ln(1+n)` (natural logarithm) more accurately than if
|
| 686 |
+
/// the operations were performed separately.
|
| 687 |
+
///
|
| 688 |
+
/// This returns NaN when `n < -1.0`, and negative infinity when `n == -1.0`.
|
| 689 |
+
///
|
| 690 |
+
/// # Unspecified precision
|
| 691 |
+
///
|
| 692 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 693 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 694 |
+
///
|
| 695 |
+
/// This function currently corresponds to the `log1pf128` from libc on Unix
|
| 696 |
+
/// and Windows. Note that this might change in the future.
|
| 697 |
+
///
|
| 698 |
+
/// # Examples
|
| 699 |
+
///
|
| 700 |
+
/// ```
|
| 701 |
+
/// #![feature(f128)]
|
| 702 |
+
/// # #[cfg(not(miri))]
|
| 703 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 704 |
+
///
|
| 705 |
+
/// let x = 1e-8_f128;
|
| 706 |
+
///
|
| 707 |
+
/// // for very small x, ln(1 + x) is approximately x - x^2 / 2
|
| 708 |
+
/// let approx = x - x * x / 2.0;
|
| 709 |
+
/// let abs_difference = (x.ln_1p() - approx).abs();
|
| 710 |
+
///
|
| 711 |
+
/// assert!(abs_difference < 1e-10);
|
| 712 |
+
/// # }
|
| 713 |
+
/// ```
|
| 714 |
+
///
|
| 715 |
+
/// Out-of-range values:
|
| 716 |
+
/// ```
|
| 717 |
+
/// #![feature(f128)]
|
| 718 |
+
/// # #[cfg(not(miri))]
|
| 719 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 720 |
+
///
|
| 721 |
+
/// assert_eq!((-1.0_f128).ln_1p(), f128::NEG_INFINITY);
|
| 722 |
+
/// assert!((-2.0_f128).ln_1p().is_nan());
|
| 723 |
+
/// # }
|
| 724 |
+
/// ```
|
| 725 |
+
#[inline]
|
| 726 |
+
#[doc(alias = "log1p")]
|
| 727 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 728 |
+
#[rustc_allow_incoherent_impl]
|
| 729 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 730 |
+
pub fn ln_1p(self) -> f128 {
|
| 731 |
+
cmath::log1pf128(self)
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
/// Hyperbolic sine function.
|
| 735 |
+
///
|
| 736 |
+
/// # Unspecified precision
|
| 737 |
+
///
|
| 738 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 739 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 740 |
+
///
|
| 741 |
+
/// This function currently corresponds to the `sinhf128` from libc on Unix
|
| 742 |
+
/// and Windows. Note that this might change in the future.
|
| 743 |
+
///
|
| 744 |
+
/// # Examples
|
| 745 |
+
///
|
| 746 |
+
/// ```
|
| 747 |
+
/// #![feature(f128)]
|
| 748 |
+
/// # #[cfg(not(miri))]
|
| 749 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 750 |
+
///
|
| 751 |
+
/// let e = std::f128::consts::E;
|
| 752 |
+
/// let x = 1.0f128;
|
| 753 |
+
///
|
| 754 |
+
/// let f = x.sinh();
|
| 755 |
+
/// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
|
| 756 |
+
/// let g = ((e * e) - 1.0) / (2.0 * e);
|
| 757 |
+
/// let abs_difference = (f - g).abs();
|
| 758 |
+
///
|
| 759 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 760 |
+
/// # }
|
| 761 |
+
/// ```
|
| 762 |
+
#[inline]
|
| 763 |
+
#[rustc_allow_incoherent_impl]
|
| 764 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 765 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 766 |
+
pub fn sinh(self) -> f128 {
|
| 767 |
+
cmath::sinhf128(self)
|
| 768 |
+
}
|
| 769 |
+
|
| 770 |
+
/// Hyperbolic cosine function.
|
| 771 |
+
///
|
| 772 |
+
/// # Unspecified precision
|
| 773 |
+
///
|
| 774 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 775 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 776 |
+
///
|
| 777 |
+
/// This function currently corresponds to the `coshf128` from libc on Unix
|
| 778 |
+
/// and Windows. Note that this might change in the future.
|
| 779 |
+
///
|
| 780 |
+
/// # Examples
|
| 781 |
+
///
|
| 782 |
+
/// ```
|
| 783 |
+
/// #![feature(f128)]
|
| 784 |
+
/// # #[cfg(not(miri))]
|
| 785 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 786 |
+
///
|
| 787 |
+
/// let e = std::f128::consts::E;
|
| 788 |
+
/// let x = 1.0f128;
|
| 789 |
+
/// let f = x.cosh();
|
| 790 |
+
/// // Solving cosh() at 1 gives this result
|
| 791 |
+
/// let g = ((e * e) + 1.0) / (2.0 * e);
|
| 792 |
+
/// let abs_difference = (f - g).abs();
|
| 793 |
+
///
|
| 794 |
+
/// // Same result
|
| 795 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 796 |
+
/// # }
|
| 797 |
+
/// ```
|
| 798 |
+
#[inline]
|
| 799 |
+
#[rustc_allow_incoherent_impl]
|
| 800 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 801 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 802 |
+
pub fn cosh(self) -> f128 {
|
| 803 |
+
cmath::coshf128(self)
|
| 804 |
+
}
|
| 805 |
+
|
| 806 |
+
/// Hyperbolic tangent function.
|
| 807 |
+
///
|
| 808 |
+
/// # Unspecified precision
|
| 809 |
+
///
|
| 810 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 811 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 812 |
+
///
|
| 813 |
+
/// This function currently corresponds to the `tanhf128` from libc on Unix
|
| 814 |
+
/// and Windows. Note that this might change in the future.
|
| 815 |
+
///
|
| 816 |
+
/// # Examples
|
| 817 |
+
///
|
| 818 |
+
/// ```
|
| 819 |
+
/// #![feature(f128)]
|
| 820 |
+
/// # #[cfg(not(miri))]
|
| 821 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 822 |
+
///
|
| 823 |
+
/// let e = std::f128::consts::E;
|
| 824 |
+
/// let x = 1.0f128;
|
| 825 |
+
///
|
| 826 |
+
/// let f = x.tanh();
|
| 827 |
+
/// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
|
| 828 |
+
/// let g = (1.0 - e.powi(-2)) / (1.0 + e.powi(-2));
|
| 829 |
+
/// let abs_difference = (f - g).abs();
|
| 830 |
+
///
|
| 831 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 832 |
+
/// # }
|
| 833 |
+
/// ```
|
| 834 |
+
#[inline]
|
| 835 |
+
#[rustc_allow_incoherent_impl]
|
| 836 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 837 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 838 |
+
pub fn tanh(self) -> f128 {
|
| 839 |
+
cmath::tanhf128(self)
|
| 840 |
+
}
|
| 841 |
+
|
| 842 |
+
/// Inverse hyperbolic sine function.
|
| 843 |
+
///
|
| 844 |
+
/// # Unspecified precision
|
| 845 |
+
///
|
| 846 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 847 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 848 |
+
///
|
| 849 |
+
/// # Examples
|
| 850 |
+
///
|
| 851 |
+
/// ```
|
| 852 |
+
/// #![feature(f128)]
|
| 853 |
+
/// # #[cfg(not(miri))]
|
| 854 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 855 |
+
///
|
| 856 |
+
/// let x = 1.0f128;
|
| 857 |
+
/// let f = x.sinh().asinh();
|
| 858 |
+
///
|
| 859 |
+
/// let abs_difference = (f - x).abs();
|
| 860 |
+
///
|
| 861 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 862 |
+
/// # }
|
| 863 |
+
/// ```
|
| 864 |
+
#[inline]
|
| 865 |
+
#[doc(alias = "arcsinh")]
|
| 866 |
+
#[rustc_allow_incoherent_impl]
|
| 867 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 868 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 869 |
+
pub fn asinh(self) -> f128 {
|
| 870 |
+
let ax = self.abs();
|
| 871 |
+
let ix = 1.0 / ax;
|
| 872 |
+
(ax + (ax / (Self::hypot(1.0, ix) + ix))).ln_1p().copysign(self)
|
| 873 |
+
}
|
| 874 |
+
|
| 875 |
+
/// Inverse hyperbolic cosine function.
|
| 876 |
+
///
|
| 877 |
+
/// # Unspecified precision
|
| 878 |
+
///
|
| 879 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 880 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 881 |
+
///
|
| 882 |
+
/// # Examples
|
| 883 |
+
///
|
| 884 |
+
/// ```
|
| 885 |
+
/// #![feature(f128)]
|
| 886 |
+
/// # #[cfg(not(miri))]
|
| 887 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 888 |
+
///
|
| 889 |
+
/// let x = 1.0f128;
|
| 890 |
+
/// let f = x.cosh().acosh();
|
| 891 |
+
///
|
| 892 |
+
/// let abs_difference = (f - x).abs();
|
| 893 |
+
///
|
| 894 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 895 |
+
/// # }
|
| 896 |
+
/// ```
|
| 897 |
+
#[inline]
|
| 898 |
+
#[doc(alias = "arccosh")]
|
| 899 |
+
#[rustc_allow_incoherent_impl]
|
| 900 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 901 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 902 |
+
pub fn acosh(self) -> f128 {
|
| 903 |
+
if self < 1.0 {
|
| 904 |
+
Self::NAN
|
| 905 |
+
} else {
|
| 906 |
+
(self + ((self - 1.0).sqrt() * (self + 1.0).sqrt())).ln()
|
| 907 |
+
}
|
| 908 |
+
}
|
| 909 |
+
|
| 910 |
+
/// Inverse hyperbolic tangent function.
|
| 911 |
+
///
|
| 912 |
+
/// # Unspecified precision
|
| 913 |
+
///
|
| 914 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 915 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 916 |
+
///
|
| 917 |
+
/// # Examples
|
| 918 |
+
///
|
| 919 |
+
/// ```
|
| 920 |
+
/// #![feature(f128)]
|
| 921 |
+
/// # #[cfg(not(miri))]
|
| 922 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 923 |
+
///
|
| 924 |
+
/// let x = std::f128::consts::FRAC_PI_6;
|
| 925 |
+
/// let f = x.tanh().atanh();
|
| 926 |
+
///
|
| 927 |
+
/// let abs_difference = (f - x).abs();
|
| 928 |
+
///
|
| 929 |
+
/// assert!(abs_difference <= 1e-5);
|
| 930 |
+
/// # }
|
| 931 |
+
/// ```
|
| 932 |
+
#[inline]
|
| 933 |
+
#[doc(alias = "arctanh")]
|
| 934 |
+
#[rustc_allow_incoherent_impl]
|
| 935 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 936 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 937 |
+
pub fn atanh(self) -> f128 {
|
| 938 |
+
0.5 * ((2.0 * self) / (1.0 - self)).ln_1p()
|
| 939 |
+
}
|
| 940 |
+
|
| 941 |
+
/// Gamma function.
|
| 942 |
+
///
|
| 943 |
+
/// # Unspecified precision
|
| 944 |
+
///
|
| 945 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 946 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 947 |
+
///
|
| 948 |
+
/// This function currently corresponds to the `tgammaf128` from libc on Unix
|
| 949 |
+
/// and Windows. Note that this might change in the future.
|
| 950 |
+
///
|
| 951 |
+
/// # Examples
|
| 952 |
+
///
|
| 953 |
+
/// ```
|
| 954 |
+
/// #![feature(f128)]
|
| 955 |
+
/// #![feature(float_gamma)]
|
| 956 |
+
/// # #[cfg(not(miri))]
|
| 957 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 958 |
+
///
|
| 959 |
+
/// let x = 5.0f128;
|
| 960 |
+
///
|
| 961 |
+
/// let abs_difference = (x.gamma() - 24.0).abs();
|
| 962 |
+
///
|
| 963 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 964 |
+
/// # }
|
| 965 |
+
/// ```
|
| 966 |
+
#[inline]
|
| 967 |
+
#[rustc_allow_incoherent_impl]
|
| 968 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 969 |
+
// #[unstable(feature = "float_gamma", issue = "99842")]
|
| 970 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 971 |
+
pub fn gamma(self) -> f128 {
|
| 972 |
+
cmath::tgammaf128(self)
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
/// Natural logarithm of the absolute value of the gamma function
|
| 976 |
+
///
|
| 977 |
+
/// The integer part of the tuple indicates the sign of the gamma function.
|
| 978 |
+
///
|
| 979 |
+
/// # Unspecified precision
|
| 980 |
+
///
|
| 981 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 982 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 983 |
+
///
|
| 984 |
+
/// This function currently corresponds to the `lgammaf128_r` from libc on Unix
|
| 985 |
+
/// and Windows. Note that this might change in the future.
|
| 986 |
+
///
|
| 987 |
+
/// # Examples
|
| 988 |
+
///
|
| 989 |
+
/// ```
|
| 990 |
+
/// #![feature(f128)]
|
| 991 |
+
/// #![feature(float_gamma)]
|
| 992 |
+
/// # #[cfg(not(miri))]
|
| 993 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 994 |
+
///
|
| 995 |
+
/// let x = 2.0f128;
|
| 996 |
+
///
|
| 997 |
+
/// let abs_difference = (x.ln_gamma().0 - 0.0).abs();
|
| 998 |
+
///
|
| 999 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 1000 |
+
/// # }
|
| 1001 |
+
/// ```
|
| 1002 |
+
#[inline]
|
| 1003 |
+
#[rustc_allow_incoherent_impl]
|
| 1004 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 1005 |
+
// #[unstable(feature = "float_gamma", issue = "99842")]
|
| 1006 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1007 |
+
pub fn ln_gamma(self) -> (f128, i32) {
|
| 1008 |
+
let mut signgamp: i32 = 0;
|
| 1009 |
+
let x = cmath::lgammaf128_r(self, &mut signgamp);
|
| 1010 |
+
(x, signgamp)
|
| 1011 |
+
}
|
| 1012 |
+
|
| 1013 |
+
/// Error function.
|
| 1014 |
+
///
|
| 1015 |
+
/// # Unspecified precision
|
| 1016 |
+
///
|
| 1017 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 1018 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 1019 |
+
///
|
| 1020 |
+
/// This function currently corresponds to the `erff128` from libc on Unix
|
| 1021 |
+
/// and Windows. Note that this might change in the future.
|
| 1022 |
+
///
|
| 1023 |
+
/// # Examples
|
| 1024 |
+
///
|
| 1025 |
+
/// ```
|
| 1026 |
+
/// #![feature(f128)]
|
| 1027 |
+
/// #![feature(float_erf)]
|
| 1028 |
+
/// # #[cfg(not(miri))]
|
| 1029 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 1030 |
+
/// /// The error function relates what percent of a normal distribution lies
|
| 1031 |
+
/// /// within `x` standard deviations (scaled by `1/sqrt(2)`).
|
| 1032 |
+
/// fn within_standard_deviations(x: f128) -> f128 {
|
| 1033 |
+
/// (x * std::f128::consts::FRAC_1_SQRT_2).erf() * 100.0
|
| 1034 |
+
/// }
|
| 1035 |
+
///
|
| 1036 |
+
/// // 68% of a normal distribution is within one standard deviation
|
| 1037 |
+
/// assert!((within_standard_deviations(1.0) - 68.269).abs() < 0.01);
|
| 1038 |
+
/// // 95% of a normal distribution is within two standard deviations
|
| 1039 |
+
/// assert!((within_standard_deviations(2.0) - 95.450).abs() < 0.01);
|
| 1040 |
+
/// // 99.7% of a normal distribution is within three standard deviations
|
| 1041 |
+
/// assert!((within_standard_deviations(3.0) - 99.730).abs() < 0.01);
|
| 1042 |
+
/// # }
|
| 1043 |
+
/// ```
|
| 1044 |
+
#[rustc_allow_incoherent_impl]
|
| 1045 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1046 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 1047 |
+
// #[unstable(feature = "float_erf", issue = "136321")]
|
| 1048 |
+
#[inline]
|
| 1049 |
+
pub fn erf(self) -> f128 {
|
| 1050 |
+
cmath::erff128(self)
|
| 1051 |
+
}
|
| 1052 |
+
|
| 1053 |
+
/// Complementary error function.
|
| 1054 |
+
///
|
| 1055 |
+
/// # Unspecified precision
|
| 1056 |
+
///
|
| 1057 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 1058 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 1059 |
+
///
|
| 1060 |
+
/// This function currently corresponds to the `erfcf128` from libc on Unix
|
| 1061 |
+
/// and Windows. Note that this might change in the future.
|
| 1062 |
+
///
|
| 1063 |
+
/// # Examples
|
| 1064 |
+
///
|
| 1065 |
+
/// ```
|
| 1066 |
+
/// #![feature(f128)]
|
| 1067 |
+
/// #![feature(float_erf)]
|
| 1068 |
+
/// # #[cfg(not(miri))]
|
| 1069 |
+
/// # #[cfg(target_has_reliable_f128_math)] {
|
| 1070 |
+
/// let x: f128 = 0.123;
|
| 1071 |
+
///
|
| 1072 |
+
/// let one = x.erf() + x.erfc();
|
| 1073 |
+
/// let abs_difference = (one - 1.0).abs();
|
| 1074 |
+
///
|
| 1075 |
+
/// assert!(abs_difference <= f128::EPSILON);
|
| 1076 |
+
/// # }
|
| 1077 |
+
/// ```
|
| 1078 |
+
#[rustc_allow_incoherent_impl]
|
| 1079 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1080 |
+
#[unstable(feature = "f128", issue = "116909")]
|
| 1081 |
+
// #[unstable(feature = "float_erf", issue = "136321")]
|
| 1082 |
+
#[inline]
|
| 1083 |
+
pub fn erfc(self) -> f128 {
|
| 1084 |
+
cmath::erfcf128(self)
|
| 1085 |
+
}
|
| 1086 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/num/f16.rs
ADDED
|
@@ -0,0 +1,1046 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
//! Constants for the `f16` half-precision floating point type.
|
| 2 |
+
//!
|
| 3 |
+
//! *[See also the `f16` primitive type](primitive@f16).*
|
| 4 |
+
//!
|
| 5 |
+
//! Mathematically significant numbers are provided in the `consts` sub-module.
|
| 6 |
+
|
| 7 |
+
#![unstable(feature = "f16", issue = "116909")]
|
| 8 |
+
#![doc(test(attr(feature(cfg_target_has_reliable_f16_f128), expect(internal_features))))]
|
| 9 |
+
|
| 10 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 11 |
+
pub use core::f16::consts;
|
| 12 |
+
|
| 13 |
+
#[cfg(not(test))]
|
| 14 |
+
use crate::intrinsics;
|
| 15 |
+
#[cfg(not(test))]
|
| 16 |
+
use crate::sys::cmath;
|
| 17 |
+
|
| 18 |
+
#[cfg(not(test))]
|
| 19 |
+
impl f16 {
|
| 20 |
+
/// Raises a number to a floating point power.
|
| 21 |
+
///
|
| 22 |
+
/// Note that this function is special in that it can return non-NaN results for NaN inputs. For
|
| 23 |
+
/// example, `f16::powf(f16::NAN, 0.0)` returns `1.0`. However, if an input is a *signaling*
|
| 24 |
+
/// NaN, then the result is non-deterministically either a NaN or the result that the
|
| 25 |
+
/// corresponding quiet NaN would produce.
|
| 26 |
+
///
|
| 27 |
+
/// # Unspecified precision
|
| 28 |
+
///
|
| 29 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 30 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 31 |
+
///
|
| 32 |
+
/// # Examples
|
| 33 |
+
///
|
| 34 |
+
/// ```
|
| 35 |
+
/// #![feature(f16)]
|
| 36 |
+
/// # #[cfg(not(miri))]
|
| 37 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 38 |
+
///
|
| 39 |
+
/// let x = 2.0_f16;
|
| 40 |
+
/// let abs_difference = (x.powf(2.0) - (x * x)).abs();
|
| 41 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 42 |
+
///
|
| 43 |
+
/// assert_eq!(f16::powf(1.0, f16::NAN), 1.0);
|
| 44 |
+
/// assert_eq!(f16::powf(f16::NAN, 0.0), 1.0);
|
| 45 |
+
/// assert_eq!(f16::powf(0.0, 0.0), 1.0);
|
| 46 |
+
/// # }
|
| 47 |
+
/// ```
|
| 48 |
+
#[inline]
|
| 49 |
+
#[rustc_allow_incoherent_impl]
|
| 50 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 51 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 52 |
+
pub fn powf(self, n: f16) -> f16 {
|
| 53 |
+
intrinsics::powf16(self, n)
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
/// Returns `e^(self)`, (the exponential function).
|
| 57 |
+
///
|
| 58 |
+
/// # Unspecified precision
|
| 59 |
+
///
|
| 60 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 61 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 62 |
+
///
|
| 63 |
+
/// # Examples
|
| 64 |
+
///
|
| 65 |
+
/// ```
|
| 66 |
+
/// #![feature(f16)]
|
| 67 |
+
/// # #[cfg(not(miri))]
|
| 68 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 69 |
+
///
|
| 70 |
+
/// let one = 1.0f16;
|
| 71 |
+
/// // e^1
|
| 72 |
+
/// let e = one.exp();
|
| 73 |
+
///
|
| 74 |
+
/// // ln(e) - 1 == 0
|
| 75 |
+
/// let abs_difference = (e.ln() - 1.0).abs();
|
| 76 |
+
///
|
| 77 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 78 |
+
/// # }
|
| 79 |
+
/// ```
|
| 80 |
+
#[inline]
|
| 81 |
+
#[rustc_allow_incoherent_impl]
|
| 82 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 83 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 84 |
+
pub fn exp(self) -> f16 {
|
| 85 |
+
intrinsics::expf16(self)
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
/// Returns `2^(self)`.
|
| 89 |
+
///
|
| 90 |
+
/// # Unspecified precision
|
| 91 |
+
///
|
| 92 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 93 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 94 |
+
///
|
| 95 |
+
/// # Examples
|
| 96 |
+
///
|
| 97 |
+
/// ```
|
| 98 |
+
/// #![feature(f16)]
|
| 99 |
+
/// # #[cfg(not(miri))]
|
| 100 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 101 |
+
///
|
| 102 |
+
/// let f = 2.0f16;
|
| 103 |
+
///
|
| 104 |
+
/// // 2^2 - 4 == 0
|
| 105 |
+
/// let abs_difference = (f.exp2() - 4.0).abs();
|
| 106 |
+
///
|
| 107 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 108 |
+
/// # }
|
| 109 |
+
/// ```
|
| 110 |
+
#[inline]
|
| 111 |
+
#[rustc_allow_incoherent_impl]
|
| 112 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 113 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 114 |
+
pub fn exp2(self) -> f16 {
|
| 115 |
+
intrinsics::exp2f16(self)
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
/// Returns the natural logarithm of the number.
|
| 119 |
+
///
|
| 120 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 121 |
+
///
|
| 122 |
+
/// # Unspecified precision
|
| 123 |
+
///
|
| 124 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 125 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 126 |
+
///
|
| 127 |
+
/// # Examples
|
| 128 |
+
///
|
| 129 |
+
/// ```
|
| 130 |
+
/// #![feature(f16)]
|
| 131 |
+
/// # #[cfg(not(miri))]
|
| 132 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 133 |
+
///
|
| 134 |
+
/// let one = 1.0f16;
|
| 135 |
+
/// // e^1
|
| 136 |
+
/// let e = one.exp();
|
| 137 |
+
///
|
| 138 |
+
/// // ln(e) - 1 == 0
|
| 139 |
+
/// let abs_difference = (e.ln() - 1.0).abs();
|
| 140 |
+
///
|
| 141 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 142 |
+
/// # }
|
| 143 |
+
/// ```
|
| 144 |
+
///
|
| 145 |
+
/// Non-positive values:
|
| 146 |
+
/// ```
|
| 147 |
+
/// #![feature(f16)]
|
| 148 |
+
/// # #[cfg(not(miri))]
|
| 149 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 150 |
+
///
|
| 151 |
+
/// assert_eq!(0_f16.ln(), f16::NEG_INFINITY);
|
| 152 |
+
/// assert!((-42_f16).ln().is_nan());
|
| 153 |
+
/// # }
|
| 154 |
+
/// ```
|
| 155 |
+
#[inline]
|
| 156 |
+
#[rustc_allow_incoherent_impl]
|
| 157 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 158 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 159 |
+
pub fn ln(self) -> f16 {
|
| 160 |
+
intrinsics::logf16(self)
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
/// Returns the logarithm of the number with respect to an arbitrary base.
|
| 164 |
+
///
|
| 165 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 166 |
+
///
|
| 167 |
+
/// The result might not be correctly rounded owing to implementation details;
|
| 168 |
+
/// `self.log2()` can produce more accurate results for base 2, and
|
| 169 |
+
/// `self.log10()` can produce more accurate results for base 10.
|
| 170 |
+
///
|
| 171 |
+
/// # Unspecified precision
|
| 172 |
+
///
|
| 173 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 174 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 175 |
+
///
|
| 176 |
+
/// # Examples
|
| 177 |
+
///
|
| 178 |
+
/// ```
|
| 179 |
+
/// #![feature(f16)]
|
| 180 |
+
/// # #[cfg(not(miri))]
|
| 181 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 182 |
+
///
|
| 183 |
+
/// let five = 5.0f16;
|
| 184 |
+
///
|
| 185 |
+
/// // log5(5) - 1 == 0
|
| 186 |
+
/// let abs_difference = (five.log(5.0) - 1.0).abs();
|
| 187 |
+
///
|
| 188 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 189 |
+
/// # }
|
| 190 |
+
/// ```
|
| 191 |
+
///
|
| 192 |
+
/// Non-positive values:
|
| 193 |
+
/// ```
|
| 194 |
+
/// #![feature(f16)]
|
| 195 |
+
/// # #[cfg(not(miri))]
|
| 196 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 197 |
+
///
|
| 198 |
+
/// assert_eq!(0_f16.log(10.0), f16::NEG_INFINITY);
|
| 199 |
+
/// assert!((-42_f16).log(10.0).is_nan());
|
| 200 |
+
/// # }
|
| 201 |
+
/// ```
|
| 202 |
+
#[inline]
|
| 203 |
+
#[rustc_allow_incoherent_impl]
|
| 204 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 205 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 206 |
+
pub fn log(self, base: f16) -> f16 {
|
| 207 |
+
self.ln() / base.ln()
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
/// Returns the base 2 logarithm of the number.
|
| 211 |
+
///
|
| 212 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 213 |
+
///
|
| 214 |
+
/// # Unspecified precision
|
| 215 |
+
///
|
| 216 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 217 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 218 |
+
///
|
| 219 |
+
/// # Examples
|
| 220 |
+
///
|
| 221 |
+
/// ```
|
| 222 |
+
/// #![feature(f16)]
|
| 223 |
+
/// # #[cfg(not(miri))]
|
| 224 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 225 |
+
///
|
| 226 |
+
/// let two = 2.0f16;
|
| 227 |
+
///
|
| 228 |
+
/// // log2(2) - 1 == 0
|
| 229 |
+
/// let abs_difference = (two.log2() - 1.0).abs();
|
| 230 |
+
///
|
| 231 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 232 |
+
/// # }
|
| 233 |
+
/// ```
|
| 234 |
+
///
|
| 235 |
+
/// Non-positive values:
|
| 236 |
+
/// ```
|
| 237 |
+
/// #![feature(f16)]
|
| 238 |
+
/// # #[cfg(not(miri))]
|
| 239 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 240 |
+
///
|
| 241 |
+
/// assert_eq!(0_f16.log2(), f16::NEG_INFINITY);
|
| 242 |
+
/// assert!((-42_f16).log2().is_nan());
|
| 243 |
+
/// # }
|
| 244 |
+
/// ```
|
| 245 |
+
#[inline]
|
| 246 |
+
#[rustc_allow_incoherent_impl]
|
| 247 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 248 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 249 |
+
pub fn log2(self) -> f16 {
|
| 250 |
+
intrinsics::log2f16(self)
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
/// Returns the base 10 logarithm of the number.
|
| 254 |
+
///
|
| 255 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 256 |
+
///
|
| 257 |
+
/// # Unspecified precision
|
| 258 |
+
///
|
| 259 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 260 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 261 |
+
///
|
| 262 |
+
/// # Examples
|
| 263 |
+
///
|
| 264 |
+
/// ```
|
| 265 |
+
/// #![feature(f16)]
|
| 266 |
+
/// # #[cfg(not(miri))]
|
| 267 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 268 |
+
///
|
| 269 |
+
/// let ten = 10.0f16;
|
| 270 |
+
///
|
| 271 |
+
/// // log10(10) - 1 == 0
|
| 272 |
+
/// let abs_difference = (ten.log10() - 1.0).abs();
|
| 273 |
+
///
|
| 274 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 275 |
+
/// # }
|
| 276 |
+
/// ```
|
| 277 |
+
///
|
| 278 |
+
/// Non-positive values:
|
| 279 |
+
/// ```
|
| 280 |
+
/// #![feature(f16)]
|
| 281 |
+
/// # #[cfg(not(miri))]
|
| 282 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 283 |
+
///
|
| 284 |
+
/// assert_eq!(0_f16.log10(), f16::NEG_INFINITY);
|
| 285 |
+
/// assert!((-42_f16).log10().is_nan());
|
| 286 |
+
/// # }
|
| 287 |
+
/// ```
|
| 288 |
+
#[inline]
|
| 289 |
+
#[rustc_allow_incoherent_impl]
|
| 290 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 291 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 292 |
+
pub fn log10(self) -> f16 {
|
| 293 |
+
intrinsics::log10f16(self)
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
/// Compute the distance between the origin and a point (`x`, `y`) on the
|
| 297 |
+
/// Euclidean plane. Equivalently, compute the length of the hypotenuse of a
|
| 298 |
+
/// right-angle triangle with other sides having length `x.abs()` and
|
| 299 |
+
/// `y.abs()`.
|
| 300 |
+
///
|
| 301 |
+
/// # Unspecified precision
|
| 302 |
+
///
|
| 303 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 304 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 305 |
+
///
|
| 306 |
+
/// This function currently corresponds to the `hypotf` from libc on Unix
|
| 307 |
+
/// and Windows. Note that this might change in the future.
|
| 308 |
+
///
|
| 309 |
+
/// # Examples
|
| 310 |
+
///
|
| 311 |
+
/// ```
|
| 312 |
+
/// #![feature(f16)]
|
| 313 |
+
/// # #[cfg(not(miri))]
|
| 314 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 315 |
+
///
|
| 316 |
+
/// let x = 2.0f16;
|
| 317 |
+
/// let y = 3.0f16;
|
| 318 |
+
///
|
| 319 |
+
/// // sqrt(x^2 + y^2)
|
| 320 |
+
/// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
|
| 321 |
+
///
|
| 322 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 323 |
+
/// # }
|
| 324 |
+
/// ```
|
| 325 |
+
#[inline]
|
| 326 |
+
#[rustc_allow_incoherent_impl]
|
| 327 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 328 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 329 |
+
pub fn hypot(self, other: f16) -> f16 {
|
| 330 |
+
cmath::hypotf(self as f32, other as f32) as f16
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
/// Computes the sine of a number (in radians).
|
| 334 |
+
///
|
| 335 |
+
/// # Unspecified precision
|
| 336 |
+
///
|
| 337 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 338 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 339 |
+
///
|
| 340 |
+
/// # Examples
|
| 341 |
+
///
|
| 342 |
+
/// ```
|
| 343 |
+
/// #![feature(f16)]
|
| 344 |
+
/// # #[cfg(not(miri))]
|
| 345 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 346 |
+
///
|
| 347 |
+
/// let x = std::f16::consts::FRAC_PI_2;
|
| 348 |
+
///
|
| 349 |
+
/// let abs_difference = (x.sin() - 1.0).abs();
|
| 350 |
+
///
|
| 351 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 352 |
+
/// # }
|
| 353 |
+
/// ```
|
| 354 |
+
#[inline]
|
| 355 |
+
#[rustc_allow_incoherent_impl]
|
| 356 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 357 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 358 |
+
pub fn sin(self) -> f16 {
|
| 359 |
+
intrinsics::sinf16(self)
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
/// Computes the cosine of a number (in radians).
|
| 363 |
+
///
|
| 364 |
+
/// # Unspecified precision
|
| 365 |
+
///
|
| 366 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 367 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 368 |
+
///
|
| 369 |
+
/// # Examples
|
| 370 |
+
///
|
| 371 |
+
/// ```
|
| 372 |
+
/// #![feature(f16)]
|
| 373 |
+
/// # #[cfg(not(miri))]
|
| 374 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 375 |
+
///
|
| 376 |
+
/// let x = 2.0 * std::f16::consts::PI;
|
| 377 |
+
///
|
| 378 |
+
/// let abs_difference = (x.cos() - 1.0).abs();
|
| 379 |
+
///
|
| 380 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 381 |
+
/// # }
|
| 382 |
+
/// ```
|
| 383 |
+
#[inline]
|
| 384 |
+
#[rustc_allow_incoherent_impl]
|
| 385 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 386 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 387 |
+
pub fn cos(self) -> f16 {
|
| 388 |
+
intrinsics::cosf16(self)
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
/// Computes the tangent of a number (in radians).
|
| 392 |
+
///
|
| 393 |
+
/// # Unspecified precision
|
| 394 |
+
///
|
| 395 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 396 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 397 |
+
///
|
| 398 |
+
/// This function currently corresponds to the `tanf` from libc on Unix and
|
| 399 |
+
/// Windows. Note that this might change in the future.
|
| 400 |
+
///
|
| 401 |
+
/// # Examples
|
| 402 |
+
///
|
| 403 |
+
/// ```
|
| 404 |
+
/// #![feature(f16)]
|
| 405 |
+
/// # #[cfg(not(miri))]
|
| 406 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 407 |
+
///
|
| 408 |
+
/// let x = std::f16::consts::FRAC_PI_4;
|
| 409 |
+
/// let abs_difference = (x.tan() - 1.0).abs();
|
| 410 |
+
///
|
| 411 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 412 |
+
/// # }
|
| 413 |
+
/// ```
|
| 414 |
+
#[inline]
|
| 415 |
+
#[rustc_allow_incoherent_impl]
|
| 416 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 417 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 418 |
+
pub fn tan(self) -> f16 {
|
| 419 |
+
cmath::tanf(self as f32) as f16
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
/// Computes the arcsine of a number. Return value is in radians in
|
| 423 |
+
/// the range [-pi/2, pi/2] or NaN if the number is outside the range
|
| 424 |
+
/// [-1, 1].
|
| 425 |
+
///
|
| 426 |
+
/// # Unspecified precision
|
| 427 |
+
///
|
| 428 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 429 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 430 |
+
///
|
| 431 |
+
/// This function currently corresponds to the `asinf` from libc on Unix
|
| 432 |
+
/// and Windows. Note that this might change in the future.
|
| 433 |
+
///
|
| 434 |
+
/// # Examples
|
| 435 |
+
///
|
| 436 |
+
/// ```
|
| 437 |
+
/// #![feature(f16)]
|
| 438 |
+
/// # #[cfg(not(miri))]
|
| 439 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 440 |
+
///
|
| 441 |
+
/// let f = std::f16::consts::FRAC_PI_4;
|
| 442 |
+
///
|
| 443 |
+
/// // asin(sin(pi/2))
|
| 444 |
+
/// let abs_difference = (f.sin().asin() - f).abs();
|
| 445 |
+
///
|
| 446 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 447 |
+
/// # }
|
| 448 |
+
/// ```
|
| 449 |
+
#[inline]
|
| 450 |
+
#[doc(alias = "arcsin")]
|
| 451 |
+
#[rustc_allow_incoherent_impl]
|
| 452 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 453 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 454 |
+
pub fn asin(self) -> f16 {
|
| 455 |
+
cmath::asinf(self as f32) as f16
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
/// Computes the arccosine of a number. Return value is in radians in
|
| 459 |
+
/// the range [0, pi] or NaN if the number is outside the range
|
| 460 |
+
/// [-1, 1].
|
| 461 |
+
///
|
| 462 |
+
/// # Unspecified precision
|
| 463 |
+
///
|
| 464 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 465 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 466 |
+
///
|
| 467 |
+
/// This function currently corresponds to the `acosf` from libc on Unix
|
| 468 |
+
/// and Windows. Note that this might change in the future.
|
| 469 |
+
///
|
| 470 |
+
/// # Examples
|
| 471 |
+
///
|
| 472 |
+
/// ```
|
| 473 |
+
/// #![feature(f16)]
|
| 474 |
+
/// # #[cfg(not(miri))]
|
| 475 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 476 |
+
///
|
| 477 |
+
/// let f = std::f16::consts::FRAC_PI_4;
|
| 478 |
+
///
|
| 479 |
+
/// // acos(cos(pi/4))
|
| 480 |
+
/// let abs_difference = (f.cos().acos() - std::f16::consts::FRAC_PI_4).abs();
|
| 481 |
+
///
|
| 482 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 483 |
+
/// # }
|
| 484 |
+
/// ```
|
| 485 |
+
#[inline]
|
| 486 |
+
#[doc(alias = "arccos")]
|
| 487 |
+
#[rustc_allow_incoherent_impl]
|
| 488 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 489 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 490 |
+
pub fn acos(self) -> f16 {
|
| 491 |
+
cmath::acosf(self as f32) as f16
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
/// Computes the arctangent of a number. Return value is in radians in the
|
| 495 |
+
/// range [-pi/2, pi/2];
|
| 496 |
+
///
|
| 497 |
+
/// # Unspecified precision
|
| 498 |
+
///
|
| 499 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 500 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 501 |
+
///
|
| 502 |
+
/// This function currently corresponds to the `atanf` from libc on Unix
|
| 503 |
+
/// and Windows. Note that this might change in the future.
|
| 504 |
+
///
|
| 505 |
+
/// # Examples
|
| 506 |
+
///
|
| 507 |
+
/// ```
|
| 508 |
+
/// #![feature(f16)]
|
| 509 |
+
/// # #[cfg(not(miri))]
|
| 510 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 511 |
+
///
|
| 512 |
+
/// let f = 1.0f16;
|
| 513 |
+
///
|
| 514 |
+
/// // atan(tan(1))
|
| 515 |
+
/// let abs_difference = (f.tan().atan() - 1.0).abs();
|
| 516 |
+
///
|
| 517 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 518 |
+
/// # }
|
| 519 |
+
/// ```
|
| 520 |
+
#[inline]
|
| 521 |
+
#[doc(alias = "arctan")]
|
| 522 |
+
#[rustc_allow_incoherent_impl]
|
| 523 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 524 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 525 |
+
pub fn atan(self) -> f16 {
|
| 526 |
+
cmath::atanf(self as f32) as f16
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
/// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) in radians.
|
| 530 |
+
///
|
| 531 |
+
/// | `x` | `y` | Piecewise Definition | Range |
|
| 532 |
+
/// |---------|---------|----------------------|---------------|
|
| 533 |
+
/// | `>= +0` | `>= +0` | `arctan(y/x)` | `[+0, +pi/2]` |
|
| 534 |
+
/// | `>= +0` | `<= -0` | `arctan(y/x)` | `[-pi/2, -0]` |
|
| 535 |
+
/// | `<= -0` | `>= +0` | `arctan(y/x) + pi` | `[+pi/2, +pi]`|
|
| 536 |
+
/// | `<= -0` | `<= -0` | `arctan(y/x) - pi` | `[-pi, -pi/2]`|
|
| 537 |
+
///
|
| 538 |
+
/// # Unspecified precision
|
| 539 |
+
///
|
| 540 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 541 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 542 |
+
///
|
| 543 |
+
/// This function currently corresponds to the `atan2f` from libc on Unix
|
| 544 |
+
/// and Windows. Note that this might change in the future.
|
| 545 |
+
///
|
| 546 |
+
/// # Examples
|
| 547 |
+
///
|
| 548 |
+
/// ```
|
| 549 |
+
/// #![feature(f16)]
|
| 550 |
+
/// # #[cfg(not(miri))]
|
| 551 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 552 |
+
///
|
| 553 |
+
/// // Positive angles measured counter-clockwise
|
| 554 |
+
/// // from positive x axis
|
| 555 |
+
/// // -pi/4 radians (45 deg clockwise)
|
| 556 |
+
/// let x1 = 3.0f16;
|
| 557 |
+
/// let y1 = -3.0f16;
|
| 558 |
+
///
|
| 559 |
+
/// // 3pi/4 radians (135 deg counter-clockwise)
|
| 560 |
+
/// let x2 = -3.0f16;
|
| 561 |
+
/// let y2 = 3.0f16;
|
| 562 |
+
///
|
| 563 |
+
/// let abs_difference_1 = (y1.atan2(x1) - (-std::f16::consts::FRAC_PI_4)).abs();
|
| 564 |
+
/// let abs_difference_2 = (y2.atan2(x2) - (3.0 * std::f16::consts::FRAC_PI_4)).abs();
|
| 565 |
+
///
|
| 566 |
+
/// assert!(abs_difference_1 <= f16::EPSILON);
|
| 567 |
+
/// assert!(abs_difference_2 <= f16::EPSILON);
|
| 568 |
+
/// # }
|
| 569 |
+
/// ```
|
| 570 |
+
#[inline]
|
| 571 |
+
#[rustc_allow_incoherent_impl]
|
| 572 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 573 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 574 |
+
pub fn atan2(self, other: f16) -> f16 {
|
| 575 |
+
cmath::atan2f(self as f32, other as f32) as f16
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
/// Simultaneously computes the sine and cosine of the number, `x`. Returns
|
| 579 |
+
/// `(sin(x), cos(x))`.
|
| 580 |
+
///
|
| 581 |
+
/// # Unspecified precision
|
| 582 |
+
///
|
| 583 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 584 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 585 |
+
///
|
| 586 |
+
/// This function currently corresponds to the `(f16::sin(x),
|
| 587 |
+
/// f16::cos(x))`. Note that this might change in the future.
|
| 588 |
+
///
|
| 589 |
+
/// # Examples
|
| 590 |
+
///
|
| 591 |
+
/// ```
|
| 592 |
+
/// #![feature(f16)]
|
| 593 |
+
/// # #[cfg(not(miri))]
|
| 594 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 595 |
+
///
|
| 596 |
+
/// let x = std::f16::consts::FRAC_PI_4;
|
| 597 |
+
/// let f = x.sin_cos();
|
| 598 |
+
///
|
| 599 |
+
/// let abs_difference_0 = (f.0 - x.sin()).abs();
|
| 600 |
+
/// let abs_difference_1 = (f.1 - x.cos()).abs();
|
| 601 |
+
///
|
| 602 |
+
/// assert!(abs_difference_0 <= f16::EPSILON);
|
| 603 |
+
/// assert!(abs_difference_1 <= f16::EPSILON);
|
| 604 |
+
/// # }
|
| 605 |
+
/// ```
|
| 606 |
+
#[inline]
|
| 607 |
+
#[doc(alias = "sincos")]
|
| 608 |
+
#[rustc_allow_incoherent_impl]
|
| 609 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 610 |
+
pub fn sin_cos(self) -> (f16, f16) {
|
| 611 |
+
(self.sin(), self.cos())
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
/// Returns `e^(self) - 1` in a way that is accurate even if the
|
| 615 |
+
/// number is close to zero.
|
| 616 |
+
///
|
| 617 |
+
/// # Unspecified precision
|
| 618 |
+
///
|
| 619 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 620 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 621 |
+
///
|
| 622 |
+
/// This function currently corresponds to the `expm1f` from libc on Unix
|
| 623 |
+
/// and Windows. Note that this might change in the future.
|
| 624 |
+
///
|
| 625 |
+
/// # Examples
|
| 626 |
+
///
|
| 627 |
+
/// ```
|
| 628 |
+
/// #![feature(f16)]
|
| 629 |
+
/// # #[cfg(not(miri))]
|
| 630 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 631 |
+
///
|
| 632 |
+
/// let x = 1e-4_f16;
|
| 633 |
+
///
|
| 634 |
+
/// // for very small x, e^x is approximately 1 + x + x^2 / 2
|
| 635 |
+
/// let approx = x + x * x / 2.0;
|
| 636 |
+
/// let abs_difference = (x.exp_m1() - approx).abs();
|
| 637 |
+
///
|
| 638 |
+
/// assert!(abs_difference < 1e-4);
|
| 639 |
+
/// # }
|
| 640 |
+
/// ```
|
| 641 |
+
#[inline]
|
| 642 |
+
#[rustc_allow_incoherent_impl]
|
| 643 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 644 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 645 |
+
pub fn exp_m1(self) -> f16 {
|
| 646 |
+
cmath::expm1f(self as f32) as f16
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
/// Returns `ln(1+n)` (natural logarithm) more accurately than if
|
| 650 |
+
/// the operations were performed separately.
|
| 651 |
+
///
|
| 652 |
+
/// This returns NaN when `n < -1.0`, and negative infinity when `n == -1.0`.
|
| 653 |
+
///
|
| 654 |
+
/// # Unspecified precision
|
| 655 |
+
///
|
| 656 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 657 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 658 |
+
///
|
| 659 |
+
/// This function currently corresponds to the `log1pf` from libc on Unix
|
| 660 |
+
/// and Windows. Note that this might change in the future.
|
| 661 |
+
///
|
| 662 |
+
/// # Examples
|
| 663 |
+
///
|
| 664 |
+
/// ```
|
| 665 |
+
/// #![feature(f16)]
|
| 666 |
+
/// # #[cfg(not(miri))]
|
| 667 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 668 |
+
///
|
| 669 |
+
/// let x = 1e-4_f16;
|
| 670 |
+
///
|
| 671 |
+
/// // for very small x, ln(1 + x) is approximately x - x^2 / 2
|
| 672 |
+
/// let approx = x - x * x / 2.0;
|
| 673 |
+
/// let abs_difference = (x.ln_1p() - approx).abs();
|
| 674 |
+
///
|
| 675 |
+
/// assert!(abs_difference < 1e-4);
|
| 676 |
+
/// # }
|
| 677 |
+
/// ```
|
| 678 |
+
///
|
| 679 |
+
/// Out-of-range values:
|
| 680 |
+
/// ```
|
| 681 |
+
/// #![feature(f16)]
|
| 682 |
+
/// # #[cfg(not(miri))]
|
| 683 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 684 |
+
///
|
| 685 |
+
/// assert_eq!((-1.0_f16).ln_1p(), f16::NEG_INFINITY);
|
| 686 |
+
/// assert!((-2.0_f16).ln_1p().is_nan());
|
| 687 |
+
/// # }
|
| 688 |
+
/// ```
|
| 689 |
+
#[inline]
|
| 690 |
+
#[doc(alias = "log1p")]
|
| 691 |
+
#[rustc_allow_incoherent_impl]
|
| 692 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 693 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 694 |
+
pub fn ln_1p(self) -> f16 {
|
| 695 |
+
cmath::log1pf(self as f32) as f16
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
/// Hyperbolic sine function.
|
| 699 |
+
///
|
| 700 |
+
/// # Unspecified precision
|
| 701 |
+
///
|
| 702 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 703 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 704 |
+
///
|
| 705 |
+
/// This function currently corresponds to the `sinhf` from libc on Unix
|
| 706 |
+
/// and Windows. Note that this might change in the future.
|
| 707 |
+
///
|
| 708 |
+
/// # Examples
|
| 709 |
+
///
|
| 710 |
+
/// ```
|
| 711 |
+
/// #![feature(f16)]
|
| 712 |
+
/// # #[cfg(not(miri))]
|
| 713 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 714 |
+
///
|
| 715 |
+
/// let e = std::f16::consts::E;
|
| 716 |
+
/// let x = 1.0f16;
|
| 717 |
+
///
|
| 718 |
+
/// let f = x.sinh();
|
| 719 |
+
/// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
|
| 720 |
+
/// let g = ((e * e) - 1.0) / (2.0 * e);
|
| 721 |
+
/// let abs_difference = (f - g).abs();
|
| 722 |
+
///
|
| 723 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 724 |
+
/// # }
|
| 725 |
+
/// ```
|
| 726 |
+
#[inline]
|
| 727 |
+
#[rustc_allow_incoherent_impl]
|
| 728 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 729 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 730 |
+
pub fn sinh(self) -> f16 {
|
| 731 |
+
cmath::sinhf(self as f32) as f16
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
/// Hyperbolic cosine function.
|
| 735 |
+
///
|
| 736 |
+
/// # Unspecified precision
|
| 737 |
+
///
|
| 738 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 739 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 740 |
+
///
|
| 741 |
+
/// This function currently corresponds to the `coshf` from libc on Unix
|
| 742 |
+
/// and Windows. Note that this might change in the future.
|
| 743 |
+
///
|
| 744 |
+
/// # Examples
|
| 745 |
+
///
|
| 746 |
+
/// ```
|
| 747 |
+
/// #![feature(f16)]
|
| 748 |
+
/// # #[cfg(not(miri))]
|
| 749 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 750 |
+
///
|
| 751 |
+
/// let e = std::f16::consts::E;
|
| 752 |
+
/// let x = 1.0f16;
|
| 753 |
+
/// let f = x.cosh();
|
| 754 |
+
/// // Solving cosh() at 1 gives this result
|
| 755 |
+
/// let g = ((e * e) + 1.0) / (2.0 * e);
|
| 756 |
+
/// let abs_difference = (f - g).abs();
|
| 757 |
+
///
|
| 758 |
+
/// // Same result
|
| 759 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 760 |
+
/// # }
|
| 761 |
+
/// ```
|
| 762 |
+
#[inline]
|
| 763 |
+
#[rustc_allow_incoherent_impl]
|
| 764 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 765 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 766 |
+
pub fn cosh(self) -> f16 {
|
| 767 |
+
cmath::coshf(self as f32) as f16
|
| 768 |
+
}
|
| 769 |
+
|
| 770 |
+
/// Hyperbolic tangent function.
|
| 771 |
+
///
|
| 772 |
+
/// # Unspecified precision
|
| 773 |
+
///
|
| 774 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 775 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 776 |
+
///
|
| 777 |
+
/// This function currently corresponds to the `tanhf` from libc on Unix
|
| 778 |
+
/// and Windows. Note that this might change in the future.
|
| 779 |
+
///
|
| 780 |
+
/// # Examples
|
| 781 |
+
///
|
| 782 |
+
/// ```
|
| 783 |
+
/// #![feature(f16)]
|
| 784 |
+
/// # #[cfg(not(miri))]
|
| 785 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 786 |
+
///
|
| 787 |
+
/// let e = std::f16::consts::E;
|
| 788 |
+
/// let x = 1.0f16;
|
| 789 |
+
///
|
| 790 |
+
/// let f = x.tanh();
|
| 791 |
+
/// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
|
| 792 |
+
/// let g = (1.0 - e.powi(-2)) / (1.0 + e.powi(-2));
|
| 793 |
+
/// let abs_difference = (f - g).abs();
|
| 794 |
+
///
|
| 795 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 796 |
+
/// # }
|
| 797 |
+
/// ```
|
| 798 |
+
#[inline]
|
| 799 |
+
#[rustc_allow_incoherent_impl]
|
| 800 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 801 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 802 |
+
pub fn tanh(self) -> f16 {
|
| 803 |
+
cmath::tanhf(self as f32) as f16
|
| 804 |
+
}
|
| 805 |
+
|
| 806 |
+
/// Inverse hyperbolic sine function.
|
| 807 |
+
///
|
| 808 |
+
/// # Unspecified precision
|
| 809 |
+
///
|
| 810 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 811 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 812 |
+
///
|
| 813 |
+
/// # Examples
|
| 814 |
+
///
|
| 815 |
+
/// ```
|
| 816 |
+
/// #![feature(f16)]
|
| 817 |
+
/// # #[cfg(not(miri))]
|
| 818 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 819 |
+
///
|
| 820 |
+
/// let x = 1.0f16;
|
| 821 |
+
/// let f = x.sinh().asinh();
|
| 822 |
+
///
|
| 823 |
+
/// let abs_difference = (f - x).abs();
|
| 824 |
+
///
|
| 825 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 826 |
+
/// # }
|
| 827 |
+
/// ```
|
| 828 |
+
#[inline]
|
| 829 |
+
#[doc(alias = "arcsinh")]
|
| 830 |
+
#[rustc_allow_incoherent_impl]
|
| 831 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 832 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 833 |
+
pub fn asinh(self) -> f16 {
|
| 834 |
+
let ax = self.abs();
|
| 835 |
+
let ix = 1.0 / ax;
|
| 836 |
+
(ax + (ax / (Self::hypot(1.0, ix) + ix))).ln_1p().copysign(self)
|
| 837 |
+
}
|
| 838 |
+
|
| 839 |
+
/// Inverse hyperbolic cosine function.
|
| 840 |
+
///
|
| 841 |
+
/// # Unspecified precision
|
| 842 |
+
///
|
| 843 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 844 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 845 |
+
///
|
| 846 |
+
/// # Examples
|
| 847 |
+
///
|
| 848 |
+
/// ```
|
| 849 |
+
/// #![feature(f16)]
|
| 850 |
+
/// # #[cfg(not(miri))]
|
| 851 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 852 |
+
///
|
| 853 |
+
/// let x = 1.0f16;
|
| 854 |
+
/// let f = x.cosh().acosh();
|
| 855 |
+
///
|
| 856 |
+
/// let abs_difference = (f - x).abs();
|
| 857 |
+
///
|
| 858 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 859 |
+
/// # }
|
| 860 |
+
/// ```
|
| 861 |
+
#[inline]
|
| 862 |
+
#[doc(alias = "arccosh")]
|
| 863 |
+
#[rustc_allow_incoherent_impl]
|
| 864 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 865 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 866 |
+
pub fn acosh(self) -> f16 {
|
| 867 |
+
if self < 1.0 {
|
| 868 |
+
Self::NAN
|
| 869 |
+
} else {
|
| 870 |
+
(self + ((self - 1.0).sqrt() * (self + 1.0).sqrt())).ln()
|
| 871 |
+
}
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
/// Inverse hyperbolic tangent function.
|
| 875 |
+
///
|
| 876 |
+
/// # Unspecified precision
|
| 877 |
+
///
|
| 878 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 879 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 880 |
+
///
|
| 881 |
+
/// # Examples
|
| 882 |
+
///
|
| 883 |
+
/// ```
|
| 884 |
+
/// #![feature(f16)]
|
| 885 |
+
/// # #[cfg(not(miri))]
|
| 886 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 887 |
+
///
|
| 888 |
+
/// let x = std::f16::consts::FRAC_PI_6;
|
| 889 |
+
/// let f = x.tanh().atanh();
|
| 890 |
+
///
|
| 891 |
+
/// let abs_difference = (f - x).abs();
|
| 892 |
+
///
|
| 893 |
+
/// assert!(abs_difference <= 0.01);
|
| 894 |
+
/// # }
|
| 895 |
+
/// ```
|
| 896 |
+
#[inline]
|
| 897 |
+
#[doc(alias = "arctanh")]
|
| 898 |
+
#[rustc_allow_incoherent_impl]
|
| 899 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 900 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 901 |
+
pub fn atanh(self) -> f16 {
|
| 902 |
+
0.5 * ((2.0 * self) / (1.0 - self)).ln_1p()
|
| 903 |
+
}
|
| 904 |
+
|
| 905 |
+
/// Gamma function.
|
| 906 |
+
///
|
| 907 |
+
/// # Unspecified precision
|
| 908 |
+
///
|
| 909 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 910 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 911 |
+
///
|
| 912 |
+
/// This function currently corresponds to the `tgammaf` from libc on Unix
|
| 913 |
+
/// and Windows. Note that this might change in the future.
|
| 914 |
+
///
|
| 915 |
+
/// # Examples
|
| 916 |
+
///
|
| 917 |
+
/// ```
|
| 918 |
+
/// #![feature(f16)]
|
| 919 |
+
/// # #[cfg(not(miri))]
|
| 920 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 921 |
+
///
|
| 922 |
+
/// let x = 5.0f16;
|
| 923 |
+
///
|
| 924 |
+
/// let abs_difference = (x.gamma() - 24.0).abs();
|
| 925 |
+
///
|
| 926 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 927 |
+
/// # }
|
| 928 |
+
/// ```
|
| 929 |
+
#[inline]
|
| 930 |
+
#[rustc_allow_incoherent_impl]
|
| 931 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 932 |
+
// #[unstable(feature = "float_gamma", issue = "99842")]
|
| 933 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 934 |
+
pub fn gamma(self) -> f16 {
|
| 935 |
+
cmath::tgammaf(self as f32) as f16
|
| 936 |
+
}
|
| 937 |
+
|
| 938 |
+
/// Natural logarithm of the absolute value of the gamma function
|
| 939 |
+
///
|
| 940 |
+
/// The integer part of the tuple indicates the sign of the gamma function.
|
| 941 |
+
///
|
| 942 |
+
/// # Unspecified precision
|
| 943 |
+
///
|
| 944 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 945 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 946 |
+
///
|
| 947 |
+
/// This function currently corresponds to the `lgamma_r` from libc on Unix
|
| 948 |
+
/// and Windows. Note that this might change in the future.
|
| 949 |
+
///
|
| 950 |
+
/// # Examples
|
| 951 |
+
///
|
| 952 |
+
/// ```
|
| 953 |
+
/// #![feature(f16)]
|
| 954 |
+
/// # #[cfg(not(miri))]
|
| 955 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 956 |
+
///
|
| 957 |
+
/// let x = 2.0f16;
|
| 958 |
+
///
|
| 959 |
+
/// let abs_difference = (x.ln_gamma().0 - 0.0).abs();
|
| 960 |
+
///
|
| 961 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 962 |
+
/// # }
|
| 963 |
+
/// ```
|
| 964 |
+
#[inline]
|
| 965 |
+
#[rustc_allow_incoherent_impl]
|
| 966 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 967 |
+
// #[unstable(feature = "float_gamma", issue = "99842")]
|
| 968 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 969 |
+
pub fn ln_gamma(self) -> (f16, i32) {
|
| 970 |
+
let mut signgamp: i32 = 0;
|
| 971 |
+
let x = cmath::lgammaf_r(self as f32, &mut signgamp) as f16;
|
| 972 |
+
(x, signgamp)
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
/// Error function.
|
| 976 |
+
///
|
| 977 |
+
/// # Unspecified precision
|
| 978 |
+
///
|
| 979 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 980 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 981 |
+
///
|
| 982 |
+
/// This function currently corresponds to the `erff` from libc on Unix
|
| 983 |
+
/// and Windows. Note that this might change in the future.
|
| 984 |
+
///
|
| 985 |
+
/// # Examples
|
| 986 |
+
///
|
| 987 |
+
/// ```
|
| 988 |
+
/// #![feature(f16)]
|
| 989 |
+
/// # #[cfg(not(miri))]
|
| 990 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 991 |
+
/// /// The error function relates what percent of a normal distribution lies
|
| 992 |
+
/// /// within `x` standard deviations (scaled by `1/sqrt(2)`).
|
| 993 |
+
/// fn within_standard_deviations(x: f16) -> f16 {
|
| 994 |
+
/// (x * std::f16::consts::FRAC_1_SQRT_2).erf() * 100.0
|
| 995 |
+
/// }
|
| 996 |
+
///
|
| 997 |
+
/// // 68% of a normal distribution is within one standard deviation
|
| 998 |
+
/// assert!((within_standard_deviations(1.0) - 68.269).abs() < 0.1);
|
| 999 |
+
/// // 95% of a normal distribution is within two standard deviations
|
| 1000 |
+
/// assert!((within_standard_deviations(2.0) - 95.450).abs() < 0.1);
|
| 1001 |
+
/// // 99.7% of a normal distribution is within three standard deviations
|
| 1002 |
+
/// assert!((within_standard_deviations(3.0) - 99.730).abs() < 0.1);
|
| 1003 |
+
/// # }
|
| 1004 |
+
/// ```
|
| 1005 |
+
#[rustc_allow_incoherent_impl]
|
| 1006 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1007 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 1008 |
+
// #[unstable(feature = "float_erf", issue = "136321")]
|
| 1009 |
+
#[inline]
|
| 1010 |
+
pub fn erf(self) -> f16 {
|
| 1011 |
+
cmath::erff(self as f32) as f16
|
| 1012 |
+
}
|
| 1013 |
+
|
| 1014 |
+
/// Complementary error function.
|
| 1015 |
+
///
|
| 1016 |
+
/// # Unspecified precision
|
| 1017 |
+
///
|
| 1018 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 1019 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 1020 |
+
///
|
| 1021 |
+
/// This function currently corresponds to the `erfcf` from libc on Unix
|
| 1022 |
+
/// and Windows. Note that this might change in the future.
|
| 1023 |
+
///
|
| 1024 |
+
/// # Examples
|
| 1025 |
+
///
|
| 1026 |
+
/// ```
|
| 1027 |
+
/// #![feature(f16)]
|
| 1028 |
+
/// # #[cfg(not(miri))]
|
| 1029 |
+
/// # #[cfg(target_has_reliable_f16_math)] {
|
| 1030 |
+
/// let x: f16 = 0.123;
|
| 1031 |
+
///
|
| 1032 |
+
/// let one = x.erf() + x.erfc();
|
| 1033 |
+
/// let abs_difference = (one - 1.0).abs();
|
| 1034 |
+
///
|
| 1035 |
+
/// assert!(abs_difference <= f16::EPSILON);
|
| 1036 |
+
/// # }
|
| 1037 |
+
/// ```
|
| 1038 |
+
#[rustc_allow_incoherent_impl]
|
| 1039 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1040 |
+
#[unstable(feature = "f16", issue = "116909")]
|
| 1041 |
+
// #[unstable(feature = "float_erf", issue = "136321")]
|
| 1042 |
+
#[inline]
|
| 1043 |
+
pub fn erfc(self) -> f16 {
|
| 1044 |
+
cmath::erfcf(self as f32) as f16
|
| 1045 |
+
}
|
| 1046 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/num/f32.rs
ADDED
|
@@ -0,0 +1,1276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Constants for the `f32` single-precision floating point type.
|
| 2 |
+
//!
|
| 3 |
+
//! *[See also the `f32` primitive type](primitive@f32).*
|
| 4 |
+
//!
|
| 5 |
+
//! Mathematically significant numbers are provided in the `consts` sub-module.
|
| 6 |
+
//!
|
| 7 |
+
//! For the constants defined directly in this module
|
| 8 |
+
//! (as distinct from those defined in the `consts` sub-module),
|
| 9 |
+
//! new code should instead use the associated constants
|
| 10 |
+
//! defined directly on the `f32` type.
|
| 11 |
+
|
| 12 |
+
#![stable(feature = "rust1", since = "1.0.0")]
|
| 13 |
+
#![allow(missing_docs)]
|
| 14 |
+
|
| 15 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 16 |
+
#[allow(deprecated, deprecated_in_future)]
|
| 17 |
+
pub use core::f32::{
|
| 18 |
+
DIGITS, EPSILON, INFINITY, MANTISSA_DIGITS, MAX, MAX_10_EXP, MAX_EXP, MIN, MIN_10_EXP, MIN_EXP,
|
| 19 |
+
MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, consts,
|
| 20 |
+
};
|
| 21 |
+
|
| 22 |
+
#[cfg(not(test))]
|
| 23 |
+
use crate::intrinsics;
|
| 24 |
+
#[cfg(not(test))]
|
| 25 |
+
use crate::sys::cmath;
|
| 26 |
+
|
| 27 |
+
#[cfg(not(test))]
|
| 28 |
+
impl f32 {
|
| 29 |
+
/// Returns the largest integer less than or equal to `self`.
|
| 30 |
+
///
|
| 31 |
+
/// This function always returns the precise result.
|
| 32 |
+
///
|
| 33 |
+
/// # Examples
|
| 34 |
+
///
|
| 35 |
+
/// ```
|
| 36 |
+
/// let f = 3.7_f32;
|
| 37 |
+
/// let g = 3.0_f32;
|
| 38 |
+
/// let h = -3.7_f32;
|
| 39 |
+
///
|
| 40 |
+
/// assert_eq!(f.floor(), 3.0);
|
| 41 |
+
/// assert_eq!(g.floor(), 3.0);
|
| 42 |
+
/// assert_eq!(h.floor(), -4.0);
|
| 43 |
+
/// ```
|
| 44 |
+
#[rustc_allow_incoherent_impl]
|
| 45 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 46 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 47 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 48 |
+
#[inline]
|
| 49 |
+
pub const fn floor(self) -> f32 {
|
| 50 |
+
core::f32::math::floor(self)
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
/// Returns the smallest integer greater than or equal to `self`.
|
| 54 |
+
///
|
| 55 |
+
/// This function always returns the precise result.
|
| 56 |
+
///
|
| 57 |
+
/// # Examples
|
| 58 |
+
///
|
| 59 |
+
/// ```
|
| 60 |
+
/// let f = 3.01_f32;
|
| 61 |
+
/// let g = 4.0_f32;
|
| 62 |
+
///
|
| 63 |
+
/// assert_eq!(f.ceil(), 4.0);
|
| 64 |
+
/// assert_eq!(g.ceil(), 4.0);
|
| 65 |
+
/// ```
|
| 66 |
+
#[doc(alias = "ceiling")]
|
| 67 |
+
#[rustc_allow_incoherent_impl]
|
| 68 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 69 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 70 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 71 |
+
#[inline]
|
| 72 |
+
pub const fn ceil(self) -> f32 {
|
| 73 |
+
core::f32::math::ceil(self)
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/// Returns the nearest integer to `self`. If a value is half-way between two
|
| 77 |
+
/// integers, round away from `0.0`.
|
| 78 |
+
///
|
| 79 |
+
/// This function always returns the precise result.
|
| 80 |
+
///
|
| 81 |
+
/// # Examples
|
| 82 |
+
///
|
| 83 |
+
/// ```
|
| 84 |
+
/// let f = 3.3_f32;
|
| 85 |
+
/// let g = -3.3_f32;
|
| 86 |
+
/// let h = -3.7_f32;
|
| 87 |
+
/// let i = 3.5_f32;
|
| 88 |
+
/// let j = 4.5_f32;
|
| 89 |
+
///
|
| 90 |
+
/// assert_eq!(f.round(), 3.0);
|
| 91 |
+
/// assert_eq!(g.round(), -3.0);
|
| 92 |
+
/// assert_eq!(h.round(), -4.0);
|
| 93 |
+
/// assert_eq!(i.round(), 4.0);
|
| 94 |
+
/// assert_eq!(j.round(), 5.0);
|
| 95 |
+
/// ```
|
| 96 |
+
#[rustc_allow_incoherent_impl]
|
| 97 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 98 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 99 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 100 |
+
#[inline]
|
| 101 |
+
pub const fn round(self) -> f32 {
|
| 102 |
+
core::f32::math::round(self)
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
/// Returns the nearest integer to a number. Rounds half-way cases to the number
|
| 106 |
+
/// with an even least significant digit.
|
| 107 |
+
///
|
| 108 |
+
/// This function always returns the precise result.
|
| 109 |
+
///
|
| 110 |
+
/// # Examples
|
| 111 |
+
///
|
| 112 |
+
/// ```
|
| 113 |
+
/// let f = 3.3_f32;
|
| 114 |
+
/// let g = -3.3_f32;
|
| 115 |
+
/// let h = 3.5_f32;
|
| 116 |
+
/// let i = 4.5_f32;
|
| 117 |
+
///
|
| 118 |
+
/// assert_eq!(f.round_ties_even(), 3.0);
|
| 119 |
+
/// assert_eq!(g.round_ties_even(), -3.0);
|
| 120 |
+
/// assert_eq!(h.round_ties_even(), 4.0);
|
| 121 |
+
/// assert_eq!(i.round_ties_even(), 4.0);
|
| 122 |
+
/// ```
|
| 123 |
+
#[rustc_allow_incoherent_impl]
|
| 124 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 125 |
+
#[stable(feature = "round_ties_even", since = "1.77.0")]
|
| 126 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 127 |
+
#[inline]
|
| 128 |
+
pub const fn round_ties_even(self) -> f32 {
|
| 129 |
+
core::f32::math::round_ties_even(self)
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
/// Returns the integer part of `self`.
|
| 133 |
+
/// This means that non-integer numbers are always truncated towards zero.
|
| 134 |
+
///
|
| 135 |
+
/// This function always returns the precise result.
|
| 136 |
+
///
|
| 137 |
+
/// # Examples
|
| 138 |
+
///
|
| 139 |
+
/// ```
|
| 140 |
+
/// let f = 3.7_f32;
|
| 141 |
+
/// let g = 3.0_f32;
|
| 142 |
+
/// let h = -3.7_f32;
|
| 143 |
+
///
|
| 144 |
+
/// assert_eq!(f.trunc(), 3.0);
|
| 145 |
+
/// assert_eq!(g.trunc(), 3.0);
|
| 146 |
+
/// assert_eq!(h.trunc(), -3.0);
|
| 147 |
+
/// ```
|
| 148 |
+
#[doc(alias = "truncate")]
|
| 149 |
+
#[rustc_allow_incoherent_impl]
|
| 150 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 151 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 152 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 153 |
+
#[inline]
|
| 154 |
+
pub const fn trunc(self) -> f32 {
|
| 155 |
+
core::f32::math::trunc(self)
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
/// Returns the fractional part of `self`.
|
| 159 |
+
///
|
| 160 |
+
/// This function always returns the precise result.
|
| 161 |
+
///
|
| 162 |
+
/// # Examples
|
| 163 |
+
///
|
| 164 |
+
/// ```
|
| 165 |
+
/// let x = 3.6_f32;
|
| 166 |
+
/// let y = -3.6_f32;
|
| 167 |
+
/// let abs_difference_x = (x.fract() - 0.6).abs();
|
| 168 |
+
/// let abs_difference_y = (y.fract() - (-0.6)).abs();
|
| 169 |
+
///
|
| 170 |
+
/// assert!(abs_difference_x <= f32::EPSILON);
|
| 171 |
+
/// assert!(abs_difference_y <= f32::EPSILON);
|
| 172 |
+
/// ```
|
| 173 |
+
#[rustc_allow_incoherent_impl]
|
| 174 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 175 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 176 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 177 |
+
#[inline]
|
| 178 |
+
pub const fn fract(self) -> f32 {
|
| 179 |
+
core::f32::math::fract(self)
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
|
| 183 |
+
/// error, yielding a more accurate result than an unfused multiply-add.
|
| 184 |
+
///
|
| 185 |
+
/// Using `mul_add` *may* be more performant than an unfused multiply-add if
|
| 186 |
+
/// the target architecture has a dedicated `fma` CPU instruction. However,
|
| 187 |
+
/// this is not always true, and will be heavily dependant on designing
|
| 188 |
+
/// algorithms with specific target hardware in mind.
|
| 189 |
+
///
|
| 190 |
+
/// # Precision
|
| 191 |
+
///
|
| 192 |
+
/// The result of this operation is guaranteed to be the rounded
|
| 193 |
+
/// infinite-precision result. It is specified by IEEE 754 as
|
| 194 |
+
/// `fusedMultiplyAdd` and guaranteed not to change.
|
| 195 |
+
///
|
| 196 |
+
/// # Examples
|
| 197 |
+
///
|
| 198 |
+
/// ```
|
| 199 |
+
/// let m = 10.0_f32;
|
| 200 |
+
/// let x = 4.0_f32;
|
| 201 |
+
/// let b = 60.0_f32;
|
| 202 |
+
///
|
| 203 |
+
/// assert_eq!(m.mul_add(x, b), 100.0);
|
| 204 |
+
/// assert_eq!(m * x + b, 100.0);
|
| 205 |
+
///
|
| 206 |
+
/// let one_plus_eps = 1.0_f32 + f32::EPSILON;
|
| 207 |
+
/// let one_minus_eps = 1.0_f32 - f32::EPSILON;
|
| 208 |
+
/// let minus_one = -1.0_f32;
|
| 209 |
+
///
|
| 210 |
+
/// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
|
| 211 |
+
/// assert_eq!(one_plus_eps.mul_add(one_minus_eps, minus_one), -f32::EPSILON * f32::EPSILON);
|
| 212 |
+
/// // Different rounding with the non-fused multiply and add.
|
| 213 |
+
/// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
|
| 214 |
+
/// ```
|
| 215 |
+
#[rustc_allow_incoherent_impl]
|
| 216 |
+
#[doc(alias = "fmaf", alias = "fusedMultiplyAdd")]
|
| 217 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 218 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 219 |
+
#[inline]
|
| 220 |
+
#[rustc_const_stable(feature = "const_mul_add", since = "1.94.0")]
|
| 221 |
+
pub const fn mul_add(self, a: f32, b: f32) -> f32 {
|
| 222 |
+
core::f32::math::mul_add(self, a, b)
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
/// Calculates Euclidean division, the matching method for `rem_euclid`.
|
| 226 |
+
///
|
| 227 |
+
/// This computes the integer `n` such that
|
| 228 |
+
/// `self = n * rhs + self.rem_euclid(rhs)`.
|
| 229 |
+
/// In other words, the result is `self / rhs` rounded to the integer `n`
|
| 230 |
+
/// such that `self >= n * rhs`.
|
| 231 |
+
///
|
| 232 |
+
/// # Precision
|
| 233 |
+
///
|
| 234 |
+
/// The result of this operation is guaranteed to be the rounded
|
| 235 |
+
/// infinite-precision result.
|
| 236 |
+
///
|
| 237 |
+
/// # Examples
|
| 238 |
+
///
|
| 239 |
+
/// ```
|
| 240 |
+
/// let a: f32 = 7.0;
|
| 241 |
+
/// let b = 4.0;
|
| 242 |
+
/// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
|
| 243 |
+
/// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
|
| 244 |
+
/// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
|
| 245 |
+
/// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
|
| 246 |
+
/// ```
|
| 247 |
+
#[rustc_allow_incoherent_impl]
|
| 248 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 249 |
+
#[inline]
|
| 250 |
+
#[stable(feature = "euclidean_division", since = "1.38.0")]
|
| 251 |
+
pub fn div_euclid(self, rhs: f32) -> f32 {
|
| 252 |
+
core::f32::math::div_euclid(self, rhs)
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
/// Calculates the least nonnegative remainder of `self` when divided by
|
| 256 |
+
/// `rhs`.
|
| 257 |
+
///
|
| 258 |
+
/// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
|
| 259 |
+
/// most cases. However, due to a floating point round-off error it can
|
| 260 |
+
/// result in `r == rhs.abs()`, violating the mathematical definition, if
|
| 261 |
+
/// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
|
| 262 |
+
/// This result is not an element of the function's codomain, but it is the
|
| 263 |
+
/// closest floating point number in the real numbers and thus fulfills the
|
| 264 |
+
/// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
|
| 265 |
+
/// approximately.
|
| 266 |
+
///
|
| 267 |
+
/// # Precision
|
| 268 |
+
///
|
| 269 |
+
/// The result of this operation is guaranteed to be the rounded
|
| 270 |
+
/// infinite-precision result.
|
| 271 |
+
///
|
| 272 |
+
/// # Examples
|
| 273 |
+
///
|
| 274 |
+
/// ```
|
| 275 |
+
/// let a: f32 = 7.0;
|
| 276 |
+
/// let b = 4.0;
|
| 277 |
+
/// assert_eq!(a.rem_euclid(b), 3.0);
|
| 278 |
+
/// assert_eq!((-a).rem_euclid(b), 1.0);
|
| 279 |
+
/// assert_eq!(a.rem_euclid(-b), 3.0);
|
| 280 |
+
/// assert_eq!((-a).rem_euclid(-b), 1.0);
|
| 281 |
+
/// // limitation due to round-off error
|
| 282 |
+
/// assert!((-f32::EPSILON).rem_euclid(3.0) != 0.0);
|
| 283 |
+
/// ```
|
| 284 |
+
#[doc(alias = "modulo", alias = "mod")]
|
| 285 |
+
#[rustc_allow_incoherent_impl]
|
| 286 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 287 |
+
#[inline]
|
| 288 |
+
#[stable(feature = "euclidean_division", since = "1.38.0")]
|
| 289 |
+
pub fn rem_euclid(self, rhs: f32) -> f32 {
|
| 290 |
+
core::f32::math::rem_euclid(self, rhs)
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
/// Raises a number to an integer power.
|
| 294 |
+
///
|
| 295 |
+
/// Using this function is generally faster than using `powf`.
|
| 296 |
+
/// It might have a different sequence of rounding operations than `powf`,
|
| 297 |
+
/// so the results are not guaranteed to agree.
|
| 298 |
+
///
|
| 299 |
+
/// Note that this function is special in that it can return non-NaN results for NaN inputs. For
|
| 300 |
+
/// example, `f32::powi(f32::NAN, 0)` returns `1.0`. However, if an input is a *signaling*
|
| 301 |
+
/// NaN, then the result is non-deterministically either a NaN or the result that the
|
| 302 |
+
/// corresponding quiet NaN would produce.
|
| 303 |
+
///
|
| 304 |
+
/// # Unspecified precision
|
| 305 |
+
///
|
| 306 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 307 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 308 |
+
///
|
| 309 |
+
/// # Examples
|
| 310 |
+
///
|
| 311 |
+
/// ```
|
| 312 |
+
/// let x = 2.0_f32;
|
| 313 |
+
/// let abs_difference = (x.powi(2) - (x * x)).abs();
|
| 314 |
+
/// assert!(abs_difference <= 1e-5);
|
| 315 |
+
///
|
| 316 |
+
/// assert_eq!(f32::powi(f32::NAN, 0), 1.0);
|
| 317 |
+
/// assert_eq!(f32::powi(0.0, 0), 1.0);
|
| 318 |
+
/// ```
|
| 319 |
+
#[rustc_allow_incoherent_impl]
|
| 320 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 321 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 322 |
+
#[inline]
|
| 323 |
+
pub fn powi(self, n: i32) -> f32 {
|
| 324 |
+
core::f32::math::powi(self, n)
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
/// Raises a number to a floating point power.
|
| 328 |
+
///
|
| 329 |
+
/// Note that this function is special in that it can return non-NaN results for NaN inputs. For
|
| 330 |
+
/// example, `f32::powf(f32::NAN, 0.0)` returns `1.0`. However, if an input is a *signaling*
|
| 331 |
+
/// NaN, then the result is non-deterministically either a NaN or the result that the
|
| 332 |
+
/// corresponding quiet NaN would produce.
|
| 333 |
+
///
|
| 334 |
+
/// # Unspecified precision
|
| 335 |
+
///
|
| 336 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 337 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 338 |
+
///
|
| 339 |
+
/// # Examples
|
| 340 |
+
///
|
| 341 |
+
/// ```
|
| 342 |
+
/// let x = 2.0_f32;
|
| 343 |
+
/// let abs_difference = (x.powf(2.0) - (x * x)).abs();
|
| 344 |
+
/// assert!(abs_difference <= 1e-5);
|
| 345 |
+
///
|
| 346 |
+
/// assert_eq!(f32::powf(1.0, f32::NAN), 1.0);
|
| 347 |
+
/// assert_eq!(f32::powf(f32::NAN, 0.0), 1.0);
|
| 348 |
+
/// assert_eq!(f32::powf(0.0, 0.0), 1.0);
|
| 349 |
+
/// ```
|
| 350 |
+
#[rustc_allow_incoherent_impl]
|
| 351 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 352 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 353 |
+
#[inline]
|
| 354 |
+
pub fn powf(self, n: f32) -> f32 {
|
| 355 |
+
intrinsics::powf32(self, n)
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
/// Returns the square root of a number.
|
| 359 |
+
///
|
| 360 |
+
/// Returns NaN if `self` is a negative number other than `-0.0`.
|
| 361 |
+
///
|
| 362 |
+
/// # Precision
|
| 363 |
+
///
|
| 364 |
+
/// The result of this operation is guaranteed to be the rounded
|
| 365 |
+
/// infinite-precision result. It is specified by IEEE 754 as `squareRoot`
|
| 366 |
+
/// and guaranteed not to change.
|
| 367 |
+
///
|
| 368 |
+
/// # Examples
|
| 369 |
+
///
|
| 370 |
+
/// ```
|
| 371 |
+
/// let positive = 4.0_f32;
|
| 372 |
+
/// let negative = -4.0_f32;
|
| 373 |
+
/// let negative_zero = -0.0_f32;
|
| 374 |
+
///
|
| 375 |
+
/// assert_eq!(positive.sqrt(), 2.0);
|
| 376 |
+
/// assert!(negative.sqrt().is_nan());
|
| 377 |
+
/// assert!(negative_zero.sqrt() == negative_zero);
|
| 378 |
+
/// ```
|
| 379 |
+
#[doc(alias = "squareRoot")]
|
| 380 |
+
#[rustc_allow_incoherent_impl]
|
| 381 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 382 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 383 |
+
#[inline]
|
| 384 |
+
pub fn sqrt(self) -> f32 {
|
| 385 |
+
core::f32::math::sqrt(self)
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
/// Returns `e^(self)`, (the exponential function).
|
| 389 |
+
///
|
| 390 |
+
/// # Unspecified precision
|
| 391 |
+
///
|
| 392 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 393 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 394 |
+
///
|
| 395 |
+
/// # Examples
|
| 396 |
+
///
|
| 397 |
+
/// ```
|
| 398 |
+
/// let one = 1.0f32;
|
| 399 |
+
/// // e^1
|
| 400 |
+
/// let e = one.exp();
|
| 401 |
+
///
|
| 402 |
+
/// // ln(e) - 1 == 0
|
| 403 |
+
/// let abs_difference = (e.ln() - 1.0).abs();
|
| 404 |
+
///
|
| 405 |
+
/// assert!(abs_difference <= 1e-6);
|
| 406 |
+
/// ```
|
| 407 |
+
#[rustc_allow_incoherent_impl]
|
| 408 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 409 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 410 |
+
#[inline]
|
| 411 |
+
pub fn exp(self) -> f32 {
|
| 412 |
+
intrinsics::expf32(self)
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
/// Returns `2^(self)`.
|
| 416 |
+
///
|
| 417 |
+
/// # Unspecified precision
|
| 418 |
+
///
|
| 419 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 420 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 421 |
+
///
|
| 422 |
+
/// # Examples
|
| 423 |
+
///
|
| 424 |
+
/// ```
|
| 425 |
+
/// let f = 2.0f32;
|
| 426 |
+
///
|
| 427 |
+
/// // 2^2 - 4 == 0
|
| 428 |
+
/// let abs_difference = (f.exp2() - 4.0).abs();
|
| 429 |
+
///
|
| 430 |
+
/// assert!(abs_difference <= 1e-5);
|
| 431 |
+
/// ```
|
| 432 |
+
#[rustc_allow_incoherent_impl]
|
| 433 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 434 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 435 |
+
#[inline]
|
| 436 |
+
pub fn exp2(self) -> f32 {
|
| 437 |
+
intrinsics::exp2f32(self)
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
/// Returns the natural logarithm of the number.
|
| 441 |
+
///
|
| 442 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 443 |
+
///
|
| 444 |
+
/// # Unspecified precision
|
| 445 |
+
///
|
| 446 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 447 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 448 |
+
///
|
| 449 |
+
/// # Examples
|
| 450 |
+
///
|
| 451 |
+
/// ```
|
| 452 |
+
/// let one = 1.0f32;
|
| 453 |
+
/// // e^1
|
| 454 |
+
/// let e = one.exp();
|
| 455 |
+
///
|
| 456 |
+
/// // ln(e) - 1 == 0
|
| 457 |
+
/// let abs_difference = (e.ln() - 1.0).abs();
|
| 458 |
+
///
|
| 459 |
+
/// assert!(abs_difference <= 1e-6);
|
| 460 |
+
/// ```
|
| 461 |
+
///
|
| 462 |
+
/// Non-positive values:
|
| 463 |
+
/// ```
|
| 464 |
+
/// assert_eq!(0_f32.ln(), f32::NEG_INFINITY);
|
| 465 |
+
/// assert!((-42_f32).ln().is_nan());
|
| 466 |
+
/// ```
|
| 467 |
+
#[rustc_allow_incoherent_impl]
|
| 468 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 469 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 470 |
+
#[inline]
|
| 471 |
+
pub fn ln(self) -> f32 {
|
| 472 |
+
intrinsics::logf32(self)
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
/// Returns the logarithm of the number with respect to an arbitrary base.
|
| 476 |
+
///
|
| 477 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 478 |
+
///
|
| 479 |
+
/// The result might not be correctly rounded owing to implementation details;
|
| 480 |
+
/// `self.log2()` can produce more accurate results for base 2, and
|
| 481 |
+
/// `self.log10()` can produce more accurate results for base 10.
|
| 482 |
+
///
|
| 483 |
+
/// # Unspecified precision
|
| 484 |
+
///
|
| 485 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 486 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 487 |
+
///
|
| 488 |
+
/// # Examples
|
| 489 |
+
///
|
| 490 |
+
/// ```
|
| 491 |
+
/// let five = 5.0f32;
|
| 492 |
+
///
|
| 493 |
+
/// // log5(5) - 1 == 0
|
| 494 |
+
/// let abs_difference = (five.log(5.0) - 1.0).abs();
|
| 495 |
+
///
|
| 496 |
+
/// assert!(abs_difference <= 1e-6);
|
| 497 |
+
/// ```
|
| 498 |
+
///
|
| 499 |
+
/// Non-positive values:
|
| 500 |
+
/// ```
|
| 501 |
+
/// assert_eq!(0_f32.log(10.0), f32::NEG_INFINITY);
|
| 502 |
+
/// assert!((-42_f32).log(10.0).is_nan());
|
| 503 |
+
/// ```
|
| 504 |
+
#[rustc_allow_incoherent_impl]
|
| 505 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 506 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 507 |
+
#[inline]
|
| 508 |
+
pub fn log(self, base: f32) -> f32 {
|
| 509 |
+
self.ln() / base.ln()
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
/// Returns the base 2 logarithm of the number.
|
| 513 |
+
///
|
| 514 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 515 |
+
///
|
| 516 |
+
/// # Unspecified precision
|
| 517 |
+
///
|
| 518 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 519 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 520 |
+
///
|
| 521 |
+
/// # Examples
|
| 522 |
+
///
|
| 523 |
+
/// ```
|
| 524 |
+
/// let two = 2.0f32;
|
| 525 |
+
///
|
| 526 |
+
/// // log2(2) - 1 == 0
|
| 527 |
+
/// let abs_difference = (two.log2() - 1.0).abs();
|
| 528 |
+
///
|
| 529 |
+
/// assert!(abs_difference <= 1e-6);
|
| 530 |
+
/// ```
|
| 531 |
+
///
|
| 532 |
+
/// Non-positive values:
|
| 533 |
+
/// ```
|
| 534 |
+
/// assert_eq!(0_f32.log2(), f32::NEG_INFINITY);
|
| 535 |
+
/// assert!((-42_f32).log2().is_nan());
|
| 536 |
+
/// ```
|
| 537 |
+
#[rustc_allow_incoherent_impl]
|
| 538 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 539 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 540 |
+
#[inline]
|
| 541 |
+
pub fn log2(self) -> f32 {
|
| 542 |
+
intrinsics::log2f32(self)
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
/// Returns the base 10 logarithm of the number.
|
| 546 |
+
///
|
| 547 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 548 |
+
///
|
| 549 |
+
/// # Unspecified precision
|
| 550 |
+
///
|
| 551 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 552 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 553 |
+
///
|
| 554 |
+
/// # Examples
|
| 555 |
+
///
|
| 556 |
+
/// ```
|
| 557 |
+
/// let ten = 10.0f32;
|
| 558 |
+
///
|
| 559 |
+
/// // log10(10) - 1 == 0
|
| 560 |
+
/// let abs_difference = (ten.log10() - 1.0).abs();
|
| 561 |
+
///
|
| 562 |
+
/// assert!(abs_difference <= 1e-6);
|
| 563 |
+
/// ```
|
| 564 |
+
///
|
| 565 |
+
/// Non-positive values:
|
| 566 |
+
/// ```
|
| 567 |
+
/// assert_eq!(0_f32.log10(), f32::NEG_INFINITY);
|
| 568 |
+
/// assert!((-42_f32).log10().is_nan());
|
| 569 |
+
/// ```
|
| 570 |
+
#[rustc_allow_incoherent_impl]
|
| 571 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 572 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 573 |
+
#[inline]
|
| 574 |
+
pub fn log10(self) -> f32 {
|
| 575 |
+
intrinsics::log10f32(self)
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
/// The positive difference of two numbers.
|
| 579 |
+
///
|
| 580 |
+
/// * If `self <= other`: `0.0`
|
| 581 |
+
/// * Else: `self - other`
|
| 582 |
+
///
|
| 583 |
+
/// # Unspecified precision
|
| 584 |
+
///
|
| 585 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 586 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 587 |
+
/// This function currently corresponds to the `fdimf` from libc on Unix
|
| 588 |
+
/// and Windows. Note that this might change in the future.
|
| 589 |
+
///
|
| 590 |
+
/// # Examples
|
| 591 |
+
///
|
| 592 |
+
/// ```
|
| 593 |
+
/// let x = 3.0f32;
|
| 594 |
+
/// let y = -3.0f32;
|
| 595 |
+
///
|
| 596 |
+
/// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
|
| 597 |
+
/// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();
|
| 598 |
+
///
|
| 599 |
+
/// assert!(abs_difference_x <= 1e-6);
|
| 600 |
+
/// assert!(abs_difference_y <= 1e-6);
|
| 601 |
+
/// ```
|
| 602 |
+
#[rustc_allow_incoherent_impl]
|
| 603 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 604 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 605 |
+
#[inline]
|
| 606 |
+
#[deprecated(
|
| 607 |
+
since = "1.10.0",
|
| 608 |
+
note = "you probably meant `(self - other).abs()`: \
|
| 609 |
+
this operation is `(self - other).max(0.0)` \
|
| 610 |
+
except that `abs_sub` also propagates NaNs (also \
|
| 611 |
+
known as `fdimf` in C). If you truly need the positive \
|
| 612 |
+
difference, consider using that expression or the C function \
|
| 613 |
+
`fdimf`, depending on how you wish to handle NaN (please consider \
|
| 614 |
+
filing an issue describing your use-case too)."
|
| 615 |
+
)]
|
| 616 |
+
pub fn abs_sub(self, other: f32) -> f32 {
|
| 617 |
+
#[allow(deprecated)]
|
| 618 |
+
core::f32::math::abs_sub(self, other)
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
/// Returns the cube root of a number.
|
| 622 |
+
///
|
| 623 |
+
/// # Unspecified precision
|
| 624 |
+
///
|
| 625 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 626 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 627 |
+
/// This function currently corresponds to the `cbrtf` from libc on Unix
|
| 628 |
+
/// and Windows. Note that this might change in the future.
|
| 629 |
+
///
|
| 630 |
+
/// # Examples
|
| 631 |
+
///
|
| 632 |
+
/// ```
|
| 633 |
+
/// let x = 8.0f32;
|
| 634 |
+
///
|
| 635 |
+
/// // x^(1/3) - 2 == 0
|
| 636 |
+
/// let abs_difference = (x.cbrt() - 2.0).abs();
|
| 637 |
+
///
|
| 638 |
+
/// assert!(abs_difference <= 1e-6);
|
| 639 |
+
/// ```
|
| 640 |
+
#[rustc_allow_incoherent_impl]
|
| 641 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 642 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 643 |
+
#[inline]
|
| 644 |
+
pub fn cbrt(self) -> f32 {
|
| 645 |
+
core::f32::math::cbrt(self)
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
/// Compute the distance between the origin and a point (`x`, `y`) on the
|
| 649 |
+
/// Euclidean plane. Equivalently, compute the length of the hypotenuse of a
|
| 650 |
+
/// right-angle triangle with other sides having length `x.abs()` and
|
| 651 |
+
/// `y.abs()`.
|
| 652 |
+
///
|
| 653 |
+
/// # Unspecified precision
|
| 654 |
+
///
|
| 655 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 656 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 657 |
+
/// This function currently corresponds to the `hypotf` from libc on Unix
|
| 658 |
+
/// and Windows. Note that this might change in the future.
|
| 659 |
+
///
|
| 660 |
+
/// # Examples
|
| 661 |
+
///
|
| 662 |
+
/// ```
|
| 663 |
+
/// let x = 2.0f32;
|
| 664 |
+
/// let y = 3.0f32;
|
| 665 |
+
///
|
| 666 |
+
/// // sqrt(x^2 + y^2)
|
| 667 |
+
/// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
|
| 668 |
+
///
|
| 669 |
+
/// assert!(abs_difference <= 1e-5);
|
| 670 |
+
/// ```
|
| 671 |
+
#[rustc_allow_incoherent_impl]
|
| 672 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 673 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 674 |
+
#[inline]
|
| 675 |
+
pub fn hypot(self, other: f32) -> f32 {
|
| 676 |
+
cmath::hypotf(self, other)
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
/// Computes the sine of a number (in radians).
|
| 680 |
+
///
|
| 681 |
+
/// # Unspecified precision
|
| 682 |
+
///
|
| 683 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 684 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 685 |
+
///
|
| 686 |
+
/// # Examples
|
| 687 |
+
///
|
| 688 |
+
/// ```
|
| 689 |
+
/// let x = std::f32::consts::FRAC_PI_2;
|
| 690 |
+
///
|
| 691 |
+
/// let abs_difference = (x.sin() - 1.0).abs();
|
| 692 |
+
///
|
| 693 |
+
/// assert!(abs_difference <= 1e-6);
|
| 694 |
+
/// ```
|
| 695 |
+
#[rustc_allow_incoherent_impl]
|
| 696 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 697 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 698 |
+
#[inline]
|
| 699 |
+
pub fn sin(self) -> f32 {
|
| 700 |
+
intrinsics::sinf32(self)
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
/// Computes the cosine of a number (in radians).
|
| 704 |
+
///
|
| 705 |
+
/// # Unspecified precision
|
| 706 |
+
///
|
| 707 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 708 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 709 |
+
///
|
| 710 |
+
/// # Examples
|
| 711 |
+
///
|
| 712 |
+
/// ```
|
| 713 |
+
/// let x = 2.0 * std::f32::consts::PI;
|
| 714 |
+
///
|
| 715 |
+
/// let abs_difference = (x.cos() - 1.0).abs();
|
| 716 |
+
///
|
| 717 |
+
/// assert!(abs_difference <= 1e-6);
|
| 718 |
+
/// ```
|
| 719 |
+
#[rustc_allow_incoherent_impl]
|
| 720 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 721 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 722 |
+
#[inline]
|
| 723 |
+
pub fn cos(self) -> f32 {
|
| 724 |
+
intrinsics::cosf32(self)
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
/// Computes the tangent of a number (in radians).
|
| 728 |
+
///
|
| 729 |
+
/// # Unspecified precision
|
| 730 |
+
///
|
| 731 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 732 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 733 |
+
/// This function currently corresponds to the `tanf` from libc on Unix and
|
| 734 |
+
/// Windows. Note that this might change in the future.
|
| 735 |
+
///
|
| 736 |
+
/// # Examples
|
| 737 |
+
///
|
| 738 |
+
/// ```
|
| 739 |
+
/// let x = std::f32::consts::FRAC_PI_4;
|
| 740 |
+
/// let abs_difference = (x.tan() - 1.0).abs();
|
| 741 |
+
///
|
| 742 |
+
/// assert!(abs_difference <= 1e-6);
|
| 743 |
+
/// ```
|
| 744 |
+
#[rustc_allow_incoherent_impl]
|
| 745 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 746 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 747 |
+
#[inline]
|
| 748 |
+
pub fn tan(self) -> f32 {
|
| 749 |
+
cmath::tanf(self)
|
| 750 |
+
}
|
| 751 |
+
|
| 752 |
+
/// Computes the arcsine of a number. Return value is in radians in
|
| 753 |
+
/// the range [-pi/2, pi/2] or NaN if the number is outside the range
|
| 754 |
+
/// [-1, 1].
|
| 755 |
+
///
|
| 756 |
+
/// # Unspecified precision
|
| 757 |
+
///
|
| 758 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 759 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 760 |
+
/// This function currently corresponds to the `asinf` from libc on Unix
|
| 761 |
+
/// and Windows. Note that this might change in the future.
|
| 762 |
+
///
|
| 763 |
+
/// # Examples
|
| 764 |
+
///
|
| 765 |
+
/// ```
|
| 766 |
+
/// let f = std::f32::consts::FRAC_PI_4;
|
| 767 |
+
///
|
| 768 |
+
/// // asin(sin(pi/2))
|
| 769 |
+
/// let abs_difference = (f.sin().asin() - f).abs();
|
| 770 |
+
///
|
| 771 |
+
/// assert!(abs_difference <= 1e-6);
|
| 772 |
+
/// ```
|
| 773 |
+
#[doc(alias = "arcsin")]
|
| 774 |
+
#[rustc_allow_incoherent_impl]
|
| 775 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 776 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 777 |
+
#[inline]
|
| 778 |
+
pub fn asin(self) -> f32 {
|
| 779 |
+
cmath::asinf(self)
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
/// Computes the arccosine of a number. Return value is in radians in
|
| 783 |
+
/// the range [0, pi] or NaN if the number is outside the range
|
| 784 |
+
/// [-1, 1].
|
| 785 |
+
///
|
| 786 |
+
/// # Unspecified precision
|
| 787 |
+
///
|
| 788 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 789 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 790 |
+
/// This function currently corresponds to the `acosf` from libc on Unix
|
| 791 |
+
/// and Windows. Note that this might change in the future.
|
| 792 |
+
///
|
| 793 |
+
/// # Examples
|
| 794 |
+
///
|
| 795 |
+
/// ```
|
| 796 |
+
/// let f = std::f32::consts::FRAC_PI_4;
|
| 797 |
+
///
|
| 798 |
+
/// // acos(cos(pi/4))
|
| 799 |
+
/// let abs_difference = (f.cos().acos() - std::f32::consts::FRAC_PI_4).abs();
|
| 800 |
+
///
|
| 801 |
+
/// assert!(abs_difference <= 1e-6);
|
| 802 |
+
/// ```
|
| 803 |
+
#[doc(alias = "arccos")]
|
| 804 |
+
#[rustc_allow_incoherent_impl]
|
| 805 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 806 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 807 |
+
#[inline]
|
| 808 |
+
pub fn acos(self) -> f32 {
|
| 809 |
+
cmath::acosf(self)
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
/// Computes the arctangent of a number. Return value is in radians in the
|
| 813 |
+
/// range [-pi/2, pi/2];
|
| 814 |
+
///
|
| 815 |
+
/// # Unspecified precision
|
| 816 |
+
///
|
| 817 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 818 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 819 |
+
/// This function currently corresponds to the `atanf` from libc on Unix
|
| 820 |
+
/// and Windows. Note that this might change in the future.
|
| 821 |
+
///
|
| 822 |
+
/// # Examples
|
| 823 |
+
///
|
| 824 |
+
/// ```
|
| 825 |
+
/// let f = 1.0f32;
|
| 826 |
+
///
|
| 827 |
+
/// // atan(tan(1))
|
| 828 |
+
/// let abs_difference = (f.tan().atan() - 1.0).abs();
|
| 829 |
+
///
|
| 830 |
+
/// assert!(abs_difference <= 1e-6);
|
| 831 |
+
/// ```
|
| 832 |
+
#[doc(alias = "arctan")]
|
| 833 |
+
#[rustc_allow_incoherent_impl]
|
| 834 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 835 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 836 |
+
#[inline]
|
| 837 |
+
pub fn atan(self) -> f32 {
|
| 838 |
+
cmath::atanf(self)
|
| 839 |
+
}
|
| 840 |
+
|
| 841 |
+
/// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) in radians.
|
| 842 |
+
///
|
| 843 |
+
/// | `x` | `y` | Piecewise Definition | Range |
|
| 844 |
+
/// |---------|---------|----------------------|---------------|
|
| 845 |
+
/// | `>= +0` | `>= +0` | `arctan(y/x)` | `[+0, +pi/2]` |
|
| 846 |
+
/// | `>= +0` | `<= -0` | `arctan(y/x)` | `[-pi/2, -0]` |
|
| 847 |
+
/// | `<= -0` | `>= +0` | `arctan(y/x) + pi` | `[+pi/2, +pi]`|
|
| 848 |
+
/// | `<= -0` | `<= -0` | `arctan(y/x) - pi` | `[-pi, -pi/2]`|
|
| 849 |
+
///
|
| 850 |
+
/// # Unspecified precision
|
| 851 |
+
///
|
| 852 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 853 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 854 |
+
/// This function currently corresponds to the `atan2f` from libc on Unix
|
| 855 |
+
/// and Windows. Note that this might change in the future.
|
| 856 |
+
///
|
| 857 |
+
/// # Examples
|
| 858 |
+
///
|
| 859 |
+
/// ```
|
| 860 |
+
/// // Positive angles measured counter-clockwise
|
| 861 |
+
/// // from positive x axis
|
| 862 |
+
/// // -pi/4 radians (45 deg clockwise)
|
| 863 |
+
/// let x1 = 3.0f32;
|
| 864 |
+
/// let y1 = -3.0f32;
|
| 865 |
+
///
|
| 866 |
+
/// // 3pi/4 radians (135 deg counter-clockwise)
|
| 867 |
+
/// let x2 = -3.0f32;
|
| 868 |
+
/// let y2 = 3.0f32;
|
| 869 |
+
///
|
| 870 |
+
/// let abs_difference_1 = (y1.atan2(x1) - (-std::f32::consts::FRAC_PI_4)).abs();
|
| 871 |
+
/// let abs_difference_2 = (y2.atan2(x2) - (3.0 * std::f32::consts::FRAC_PI_4)).abs();
|
| 872 |
+
///
|
| 873 |
+
/// assert!(abs_difference_1 <= 1e-5);
|
| 874 |
+
/// assert!(abs_difference_2 <= 1e-5);
|
| 875 |
+
/// ```
|
| 876 |
+
#[rustc_allow_incoherent_impl]
|
| 877 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 878 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 879 |
+
#[inline]
|
| 880 |
+
pub fn atan2(self, other: f32) -> f32 {
|
| 881 |
+
cmath::atan2f(self, other)
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
+
/// Simultaneously computes the sine and cosine of the number, `x`. Returns
|
| 885 |
+
/// `(sin(x), cos(x))`.
|
| 886 |
+
///
|
| 887 |
+
/// # Unspecified precision
|
| 888 |
+
///
|
| 889 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 890 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 891 |
+
/// This function currently corresponds to the `(f32::sin(x),
|
| 892 |
+
/// f32::cos(x))`. Note that this might change in the future.
|
| 893 |
+
///
|
| 894 |
+
/// # Examples
|
| 895 |
+
///
|
| 896 |
+
/// ```
|
| 897 |
+
/// let x = std::f32::consts::FRAC_PI_4;
|
| 898 |
+
/// let f = x.sin_cos();
|
| 899 |
+
///
|
| 900 |
+
/// let abs_difference_0 = (f.0 - x.sin()).abs();
|
| 901 |
+
/// let abs_difference_1 = (f.1 - x.cos()).abs();
|
| 902 |
+
///
|
| 903 |
+
/// assert!(abs_difference_0 <= 1e-4);
|
| 904 |
+
/// assert!(abs_difference_1 <= 1e-4);
|
| 905 |
+
/// ```
|
| 906 |
+
#[doc(alias = "sincos")]
|
| 907 |
+
#[rustc_allow_incoherent_impl]
|
| 908 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 909 |
+
#[inline]
|
| 910 |
+
pub fn sin_cos(self) -> (f32, f32) {
|
| 911 |
+
(self.sin(), self.cos())
|
| 912 |
+
}
|
| 913 |
+
|
| 914 |
+
/// Returns `e^(self) - 1` in a way that is accurate even if the
|
| 915 |
+
/// number is close to zero.
|
| 916 |
+
///
|
| 917 |
+
/// # Unspecified precision
|
| 918 |
+
///
|
| 919 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 920 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 921 |
+
/// This function currently corresponds to the `expm1f` from libc on Unix
|
| 922 |
+
/// and Windows. Note that this might change in the future.
|
| 923 |
+
///
|
| 924 |
+
/// # Examples
|
| 925 |
+
///
|
| 926 |
+
/// ```
|
| 927 |
+
/// let x = 1e-8_f32;
|
| 928 |
+
///
|
| 929 |
+
/// // for very small x, e^x is approximately 1 + x + x^2 / 2
|
| 930 |
+
/// let approx = x + x * x / 2.0;
|
| 931 |
+
/// let abs_difference = (x.exp_m1() - approx).abs();
|
| 932 |
+
///
|
| 933 |
+
/// assert!(abs_difference < 1e-10);
|
| 934 |
+
/// ```
|
| 935 |
+
#[rustc_allow_incoherent_impl]
|
| 936 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 937 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 938 |
+
#[inline]
|
| 939 |
+
pub fn exp_m1(self) -> f32 {
|
| 940 |
+
cmath::expm1f(self)
|
| 941 |
+
}
|
| 942 |
+
|
| 943 |
+
/// Returns `ln(1+n)` (natural logarithm) more accurately than if
|
| 944 |
+
/// the operations were performed separately.
|
| 945 |
+
///
|
| 946 |
+
/// This returns NaN when `n < -1.0`, and negative infinity when `n == -1.0`.
|
| 947 |
+
///
|
| 948 |
+
/// # Unspecified precision
|
| 949 |
+
///
|
| 950 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 951 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 952 |
+
/// This function currently corresponds to the `log1pf` from libc on Unix
|
| 953 |
+
/// and Windows. Note that this might change in the future.
|
| 954 |
+
///
|
| 955 |
+
/// # Examples
|
| 956 |
+
///
|
| 957 |
+
/// ```
|
| 958 |
+
/// let x = 1e-8_f32;
|
| 959 |
+
///
|
| 960 |
+
/// // for very small x, ln(1 + x) is approximately x - x^2 / 2
|
| 961 |
+
/// let approx = x - x * x / 2.0;
|
| 962 |
+
/// let abs_difference = (x.ln_1p() - approx).abs();
|
| 963 |
+
///
|
| 964 |
+
/// assert!(abs_difference < 1e-10);
|
| 965 |
+
/// ```
|
| 966 |
+
///
|
| 967 |
+
/// Out-of-range values:
|
| 968 |
+
/// ```
|
| 969 |
+
/// assert_eq!((-1.0_f32).ln_1p(), f32::NEG_INFINITY);
|
| 970 |
+
/// assert!((-2.0_f32).ln_1p().is_nan());
|
| 971 |
+
/// ```
|
| 972 |
+
#[doc(alias = "log1p")]
|
| 973 |
+
#[rustc_allow_incoherent_impl]
|
| 974 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 975 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 976 |
+
#[inline]
|
| 977 |
+
pub fn ln_1p(self) -> f32 {
|
| 978 |
+
cmath::log1pf(self)
|
| 979 |
+
}
|
| 980 |
+
|
| 981 |
+
/// Hyperbolic sine function.
|
| 982 |
+
///
|
| 983 |
+
/// # Unspecified precision
|
| 984 |
+
///
|
| 985 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 986 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 987 |
+
/// This function currently corresponds to the `sinhf` from libc on Unix
|
| 988 |
+
/// and Windows. Note that this might change in the future.
|
| 989 |
+
///
|
| 990 |
+
/// # Examples
|
| 991 |
+
///
|
| 992 |
+
/// ```
|
| 993 |
+
/// let e = std::f32::consts::E;
|
| 994 |
+
/// let x = 1.0f32;
|
| 995 |
+
///
|
| 996 |
+
/// let f = x.sinh();
|
| 997 |
+
/// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
|
| 998 |
+
/// let g = ((e * e) - 1.0) / (2.0 * e);
|
| 999 |
+
/// let abs_difference = (f - g).abs();
|
| 1000 |
+
///
|
| 1001 |
+
/// assert!(abs_difference <= 1e-6);
|
| 1002 |
+
/// ```
|
| 1003 |
+
#[rustc_allow_incoherent_impl]
|
| 1004 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1005 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1006 |
+
#[inline]
|
| 1007 |
+
pub fn sinh(self) -> f32 {
|
| 1008 |
+
cmath::sinhf(self)
|
| 1009 |
+
}
|
| 1010 |
+
|
| 1011 |
+
/// Hyperbolic cosine function.
|
| 1012 |
+
///
|
| 1013 |
+
/// # Unspecified precision
|
| 1014 |
+
///
|
| 1015 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1016 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1017 |
+
/// This function currently corresponds to the `coshf` from libc on Unix
|
| 1018 |
+
/// and Windows. Note that this might change in the future.
|
| 1019 |
+
///
|
| 1020 |
+
/// # Examples
|
| 1021 |
+
///
|
| 1022 |
+
/// ```
|
| 1023 |
+
/// let e = std::f32::consts::E;
|
| 1024 |
+
/// let x = 1.0f32;
|
| 1025 |
+
/// let f = x.cosh();
|
| 1026 |
+
/// // Solving cosh() at 1 gives this result
|
| 1027 |
+
/// let g = ((e * e) + 1.0) / (2.0 * e);
|
| 1028 |
+
/// let abs_difference = (f - g).abs();
|
| 1029 |
+
///
|
| 1030 |
+
/// // Same result
|
| 1031 |
+
/// assert!(abs_difference <= 1e-6);
|
| 1032 |
+
/// ```
|
| 1033 |
+
#[rustc_allow_incoherent_impl]
|
| 1034 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1035 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1036 |
+
#[inline]
|
| 1037 |
+
pub fn cosh(self) -> f32 {
|
| 1038 |
+
cmath::coshf(self)
|
| 1039 |
+
}
|
| 1040 |
+
|
| 1041 |
+
/// Hyperbolic tangent function.
|
| 1042 |
+
///
|
| 1043 |
+
/// # Unspecified precision
|
| 1044 |
+
///
|
| 1045 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1046 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1047 |
+
/// This function currently corresponds to the `tanhf` from libc on Unix
|
| 1048 |
+
/// and Windows. Note that this might change in the future.
|
| 1049 |
+
///
|
| 1050 |
+
/// # Examples
|
| 1051 |
+
///
|
| 1052 |
+
/// ```
|
| 1053 |
+
/// let e = std::f32::consts::E;
|
| 1054 |
+
/// let x = 1.0f32;
|
| 1055 |
+
///
|
| 1056 |
+
/// let f = x.tanh();
|
| 1057 |
+
/// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
|
| 1058 |
+
/// let g = (1.0 - e.powi(-2)) / (1.0 + e.powi(-2));
|
| 1059 |
+
/// let abs_difference = (f - g).abs();
|
| 1060 |
+
///
|
| 1061 |
+
/// assert!(abs_difference <= 1e-6);
|
| 1062 |
+
/// ```
|
| 1063 |
+
#[rustc_allow_incoherent_impl]
|
| 1064 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1065 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1066 |
+
#[inline]
|
| 1067 |
+
pub fn tanh(self) -> f32 {
|
| 1068 |
+
cmath::tanhf(self)
|
| 1069 |
+
}
|
| 1070 |
+
|
| 1071 |
+
/// Inverse hyperbolic sine function.
|
| 1072 |
+
///
|
| 1073 |
+
/// # Unspecified precision
|
| 1074 |
+
///
|
| 1075 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1076 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1077 |
+
///
|
| 1078 |
+
/// # Examples
|
| 1079 |
+
///
|
| 1080 |
+
/// ```
|
| 1081 |
+
/// let x = 1.0f32;
|
| 1082 |
+
/// let f = x.sinh().asinh();
|
| 1083 |
+
///
|
| 1084 |
+
/// let abs_difference = (f - x).abs();
|
| 1085 |
+
///
|
| 1086 |
+
/// assert!(abs_difference <= 1e-6);
|
| 1087 |
+
/// ```
|
| 1088 |
+
#[doc(alias = "arcsinh")]
|
| 1089 |
+
#[rustc_allow_incoherent_impl]
|
| 1090 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1091 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1092 |
+
#[inline]
|
| 1093 |
+
pub fn asinh(self) -> f32 {
|
| 1094 |
+
let ax = self.abs();
|
| 1095 |
+
let ix = 1.0 / ax;
|
| 1096 |
+
(ax + (ax / (Self::hypot(1.0, ix) + ix))).ln_1p().copysign(self)
|
| 1097 |
+
}
|
| 1098 |
+
|
| 1099 |
+
/// Inverse hyperbolic cosine function.
|
| 1100 |
+
///
|
| 1101 |
+
/// # Unspecified precision
|
| 1102 |
+
///
|
| 1103 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1104 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1105 |
+
///
|
| 1106 |
+
/// # Examples
|
| 1107 |
+
///
|
| 1108 |
+
/// ```
|
| 1109 |
+
/// let x = 1.0f32;
|
| 1110 |
+
/// let f = x.cosh().acosh();
|
| 1111 |
+
///
|
| 1112 |
+
/// let abs_difference = (f - x).abs();
|
| 1113 |
+
///
|
| 1114 |
+
/// assert!(abs_difference <= 1e-6);
|
| 1115 |
+
/// ```
|
| 1116 |
+
#[doc(alias = "arccosh")]
|
| 1117 |
+
#[rustc_allow_incoherent_impl]
|
| 1118 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1119 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1120 |
+
#[inline]
|
| 1121 |
+
pub fn acosh(self) -> f32 {
|
| 1122 |
+
if self < 1.0 {
|
| 1123 |
+
Self::NAN
|
| 1124 |
+
} else {
|
| 1125 |
+
(self + ((self - 1.0).sqrt() * (self + 1.0).sqrt())).ln()
|
| 1126 |
+
}
|
| 1127 |
+
}
|
| 1128 |
+
|
| 1129 |
+
/// Inverse hyperbolic tangent function.
|
| 1130 |
+
///
|
| 1131 |
+
/// # Unspecified precision
|
| 1132 |
+
///
|
| 1133 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1134 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1135 |
+
///
|
| 1136 |
+
/// # Examples
|
| 1137 |
+
///
|
| 1138 |
+
/// ```
|
| 1139 |
+
/// let x = std::f32::consts::FRAC_PI_6;
|
| 1140 |
+
/// let f = x.tanh().atanh();
|
| 1141 |
+
///
|
| 1142 |
+
/// let abs_difference = (f - x).abs();
|
| 1143 |
+
///
|
| 1144 |
+
/// assert!(abs_difference <= 1e-5);
|
| 1145 |
+
/// ```
|
| 1146 |
+
#[doc(alias = "arctanh")]
|
| 1147 |
+
#[rustc_allow_incoherent_impl]
|
| 1148 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1149 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1150 |
+
#[inline]
|
| 1151 |
+
pub fn atanh(self) -> f32 {
|
| 1152 |
+
0.5 * ((2.0 * self) / (1.0 - self)).ln_1p()
|
| 1153 |
+
}
|
| 1154 |
+
|
| 1155 |
+
/// Gamma function.
|
| 1156 |
+
///
|
| 1157 |
+
/// # Unspecified precision
|
| 1158 |
+
///
|
| 1159 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1160 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1161 |
+
/// This function currently corresponds to the `tgammaf` from libc on Unix
|
| 1162 |
+
/// and Windows. Note that this might change in the future.
|
| 1163 |
+
///
|
| 1164 |
+
/// # Examples
|
| 1165 |
+
///
|
| 1166 |
+
/// ```
|
| 1167 |
+
/// #![feature(float_gamma)]
|
| 1168 |
+
/// let x = 5.0f32;
|
| 1169 |
+
///
|
| 1170 |
+
/// let abs_difference = (x.gamma() - 24.0).abs();
|
| 1171 |
+
///
|
| 1172 |
+
/// assert!(abs_difference <= 1e-5);
|
| 1173 |
+
/// ```
|
| 1174 |
+
#[rustc_allow_incoherent_impl]
|
| 1175 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1176 |
+
#[unstable(feature = "float_gamma", issue = "99842")]
|
| 1177 |
+
#[inline]
|
| 1178 |
+
pub fn gamma(self) -> f32 {
|
| 1179 |
+
cmath::tgammaf(self)
|
| 1180 |
+
}
|
| 1181 |
+
|
| 1182 |
+
/// Natural logarithm of the absolute value of the gamma function
|
| 1183 |
+
///
|
| 1184 |
+
/// The integer part of the tuple indicates the sign of the gamma function.
|
| 1185 |
+
///
|
| 1186 |
+
/// # Unspecified precision
|
| 1187 |
+
///
|
| 1188 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1189 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1190 |
+
/// This function currently corresponds to the `lgamma_r` from libc on Unix
|
| 1191 |
+
/// and Windows. Note that this might change in the future.
|
| 1192 |
+
///
|
| 1193 |
+
/// # Examples
|
| 1194 |
+
///
|
| 1195 |
+
/// ```
|
| 1196 |
+
/// #![feature(float_gamma)]
|
| 1197 |
+
/// let x = 2.0f32;
|
| 1198 |
+
///
|
| 1199 |
+
/// let abs_difference = (x.ln_gamma().0 - 0.0).abs();
|
| 1200 |
+
///
|
| 1201 |
+
/// assert!(abs_difference <= f32::EPSILON);
|
| 1202 |
+
/// ```
|
| 1203 |
+
#[rustc_allow_incoherent_impl]
|
| 1204 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1205 |
+
#[unstable(feature = "float_gamma", issue = "99842")]
|
| 1206 |
+
#[inline]
|
| 1207 |
+
pub fn ln_gamma(self) -> (f32, i32) {
|
| 1208 |
+
let mut signgamp: i32 = 0;
|
| 1209 |
+
let x = cmath::lgammaf_r(self, &mut signgamp);
|
| 1210 |
+
(x, signgamp)
|
| 1211 |
+
}
|
| 1212 |
+
|
| 1213 |
+
/// Error function.
|
| 1214 |
+
///
|
| 1215 |
+
/// # Unspecified precision
|
| 1216 |
+
///
|
| 1217 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 1218 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 1219 |
+
///
|
| 1220 |
+
/// This function currently corresponds to the `erff` from libc on Unix
|
| 1221 |
+
/// and Windows. Note that this might change in the future.
|
| 1222 |
+
///
|
| 1223 |
+
/// # Examples
|
| 1224 |
+
///
|
| 1225 |
+
/// ```
|
| 1226 |
+
/// #![feature(float_erf)]
|
| 1227 |
+
/// /// The error function relates what percent of a normal distribution lies
|
| 1228 |
+
/// /// within `x` standard deviations (scaled by `1/sqrt(2)`).
|
| 1229 |
+
/// fn within_standard_deviations(x: f32) -> f32 {
|
| 1230 |
+
/// (x * std::f32::consts::FRAC_1_SQRT_2).erf() * 100.0
|
| 1231 |
+
/// }
|
| 1232 |
+
///
|
| 1233 |
+
/// // 68% of a normal distribution is within one standard deviation
|
| 1234 |
+
/// assert!((within_standard_deviations(1.0) - 68.269).abs() < 0.01);
|
| 1235 |
+
/// // 95% of a normal distribution is within two standard deviations
|
| 1236 |
+
/// assert!((within_standard_deviations(2.0) - 95.450).abs() < 0.01);
|
| 1237 |
+
/// // 99.7% of a normal distribution is within three standard deviations
|
| 1238 |
+
/// assert!((within_standard_deviations(3.0) - 99.730).abs() < 0.01);
|
| 1239 |
+
/// ```
|
| 1240 |
+
#[rustc_allow_incoherent_impl]
|
| 1241 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1242 |
+
#[unstable(feature = "float_erf", issue = "136321")]
|
| 1243 |
+
#[inline]
|
| 1244 |
+
pub fn erf(self) -> f32 {
|
| 1245 |
+
cmath::erff(self)
|
| 1246 |
+
}
|
| 1247 |
+
|
| 1248 |
+
/// Complementary error function.
|
| 1249 |
+
///
|
| 1250 |
+
/// # Unspecified precision
|
| 1251 |
+
///
|
| 1252 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 1253 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 1254 |
+
///
|
| 1255 |
+
/// This function currently corresponds to the `erfcf` from libc on Unix
|
| 1256 |
+
/// and Windows. Note that this might change in the future.
|
| 1257 |
+
///
|
| 1258 |
+
/// # Examples
|
| 1259 |
+
///
|
| 1260 |
+
/// ```
|
| 1261 |
+
/// #![feature(float_erf)]
|
| 1262 |
+
/// let x: f32 = 0.123;
|
| 1263 |
+
///
|
| 1264 |
+
/// let one = x.erf() + x.erfc();
|
| 1265 |
+
/// let abs_difference = (one - 1.0).abs();
|
| 1266 |
+
///
|
| 1267 |
+
/// assert!(abs_difference <= 1e-6);
|
| 1268 |
+
/// ```
|
| 1269 |
+
#[rustc_allow_incoherent_impl]
|
| 1270 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1271 |
+
#[unstable(feature = "float_erf", issue = "136321")]
|
| 1272 |
+
#[inline]
|
| 1273 |
+
pub fn erfc(self) -> f32 {
|
| 1274 |
+
cmath::erfcf(self)
|
| 1275 |
+
}
|
| 1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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Constants for the `f64` double-precision floating point type.
|
| 2 |
+
//!
|
| 3 |
+
//! *[See also the `f64` primitive type](primitive@f64).*
|
| 4 |
+
//!
|
| 5 |
+
//! Mathematically significant numbers are provided in the `consts` sub-module.
|
| 6 |
+
//!
|
| 7 |
+
//! For the constants defined directly in this module
|
| 8 |
+
//! (as distinct from those defined in the `consts` sub-module),
|
| 9 |
+
//! new code should instead use the associated constants
|
| 10 |
+
//! defined directly on the `f64` type.
|
| 11 |
+
|
| 12 |
+
#![stable(feature = "rust1", since = "1.0.0")]
|
| 13 |
+
#![allow(missing_docs)]
|
| 14 |
+
|
| 15 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 16 |
+
#[allow(deprecated, deprecated_in_future)]
|
| 17 |
+
pub use core::f64::{
|
| 18 |
+
DIGITS, EPSILON, INFINITY, MANTISSA_DIGITS, MAX, MAX_10_EXP, MAX_EXP, MIN, MIN_10_EXP, MIN_EXP,
|
| 19 |
+
MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, consts,
|
| 20 |
+
};
|
| 21 |
+
|
| 22 |
+
#[cfg(not(test))]
|
| 23 |
+
use crate::intrinsics;
|
| 24 |
+
#[cfg(not(test))]
|
| 25 |
+
use crate::sys::cmath;
|
| 26 |
+
|
| 27 |
+
#[cfg(not(test))]
|
| 28 |
+
impl f64 {
|
| 29 |
+
/// Returns the largest integer less than or equal to `self`.
|
| 30 |
+
///
|
| 31 |
+
/// This function always returns the precise result.
|
| 32 |
+
///
|
| 33 |
+
/// # Examples
|
| 34 |
+
///
|
| 35 |
+
/// ```
|
| 36 |
+
/// let f = 3.7_f64;
|
| 37 |
+
/// let g = 3.0_f64;
|
| 38 |
+
/// let h = -3.7_f64;
|
| 39 |
+
///
|
| 40 |
+
/// assert_eq!(f.floor(), 3.0);
|
| 41 |
+
/// assert_eq!(g.floor(), 3.0);
|
| 42 |
+
/// assert_eq!(h.floor(), -4.0);
|
| 43 |
+
/// ```
|
| 44 |
+
#[rustc_allow_incoherent_impl]
|
| 45 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 46 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 47 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 48 |
+
#[inline]
|
| 49 |
+
pub const fn floor(self) -> f64 {
|
| 50 |
+
core::f64::math::floor(self)
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
/// Returns the smallest integer greater than or equal to `self`.
|
| 54 |
+
///
|
| 55 |
+
/// This function always returns the precise result.
|
| 56 |
+
///
|
| 57 |
+
/// # Examples
|
| 58 |
+
///
|
| 59 |
+
/// ```
|
| 60 |
+
/// let f = 3.01_f64;
|
| 61 |
+
/// let g = 4.0_f64;
|
| 62 |
+
///
|
| 63 |
+
/// assert_eq!(f.ceil(), 4.0);
|
| 64 |
+
/// assert_eq!(g.ceil(), 4.0);
|
| 65 |
+
/// ```
|
| 66 |
+
#[doc(alias = "ceiling")]
|
| 67 |
+
#[rustc_allow_incoherent_impl]
|
| 68 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 69 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 70 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 71 |
+
#[inline]
|
| 72 |
+
pub const fn ceil(self) -> f64 {
|
| 73 |
+
core::f64::math::ceil(self)
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/// Returns the nearest integer to `self`. If a value is half-way between two
|
| 77 |
+
/// integers, round away from `0.0`.
|
| 78 |
+
///
|
| 79 |
+
/// This function always returns the precise result.
|
| 80 |
+
///
|
| 81 |
+
/// # Examples
|
| 82 |
+
///
|
| 83 |
+
/// ```
|
| 84 |
+
/// let f = 3.3_f64;
|
| 85 |
+
/// let g = -3.3_f64;
|
| 86 |
+
/// let h = -3.7_f64;
|
| 87 |
+
/// let i = 3.5_f64;
|
| 88 |
+
/// let j = 4.5_f64;
|
| 89 |
+
///
|
| 90 |
+
/// assert_eq!(f.round(), 3.0);
|
| 91 |
+
/// assert_eq!(g.round(), -3.0);
|
| 92 |
+
/// assert_eq!(h.round(), -4.0);
|
| 93 |
+
/// assert_eq!(i.round(), 4.0);
|
| 94 |
+
/// assert_eq!(j.round(), 5.0);
|
| 95 |
+
/// ```
|
| 96 |
+
#[rustc_allow_incoherent_impl]
|
| 97 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 98 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 99 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 100 |
+
#[inline]
|
| 101 |
+
pub const fn round(self) -> f64 {
|
| 102 |
+
core::f64::math::round(self)
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
/// Returns the nearest integer to a number. Rounds half-way cases to the number
|
| 106 |
+
/// with an even least significant digit.
|
| 107 |
+
///
|
| 108 |
+
/// This function always returns the precise result.
|
| 109 |
+
///
|
| 110 |
+
/// # Examples
|
| 111 |
+
///
|
| 112 |
+
/// ```
|
| 113 |
+
/// let f = 3.3_f64;
|
| 114 |
+
/// let g = -3.3_f64;
|
| 115 |
+
/// let h = 3.5_f64;
|
| 116 |
+
/// let i = 4.5_f64;
|
| 117 |
+
///
|
| 118 |
+
/// assert_eq!(f.round_ties_even(), 3.0);
|
| 119 |
+
/// assert_eq!(g.round_ties_even(), -3.0);
|
| 120 |
+
/// assert_eq!(h.round_ties_even(), 4.0);
|
| 121 |
+
/// assert_eq!(i.round_ties_even(), 4.0);
|
| 122 |
+
/// ```
|
| 123 |
+
#[rustc_allow_incoherent_impl]
|
| 124 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 125 |
+
#[stable(feature = "round_ties_even", since = "1.77.0")]
|
| 126 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 127 |
+
#[inline]
|
| 128 |
+
pub const fn round_ties_even(self) -> f64 {
|
| 129 |
+
core::f64::math::round_ties_even(self)
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
/// Returns the integer part of `self`.
|
| 133 |
+
/// This means that non-integer numbers are always truncated towards zero.
|
| 134 |
+
///
|
| 135 |
+
/// This function always returns the precise result.
|
| 136 |
+
///
|
| 137 |
+
/// # Examples
|
| 138 |
+
///
|
| 139 |
+
/// ```
|
| 140 |
+
/// let f = 3.7_f64;
|
| 141 |
+
/// let g = 3.0_f64;
|
| 142 |
+
/// let h = -3.7_f64;
|
| 143 |
+
///
|
| 144 |
+
/// assert_eq!(f.trunc(), 3.0);
|
| 145 |
+
/// assert_eq!(g.trunc(), 3.0);
|
| 146 |
+
/// assert_eq!(h.trunc(), -3.0);
|
| 147 |
+
/// ```
|
| 148 |
+
#[doc(alias = "truncate")]
|
| 149 |
+
#[rustc_allow_incoherent_impl]
|
| 150 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 151 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 152 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 153 |
+
#[inline]
|
| 154 |
+
pub const fn trunc(self) -> f64 {
|
| 155 |
+
core::f64::math::trunc(self)
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
/// Returns the fractional part of `self`.
|
| 159 |
+
///
|
| 160 |
+
/// This function always returns the precise result.
|
| 161 |
+
///
|
| 162 |
+
/// # Examples
|
| 163 |
+
///
|
| 164 |
+
/// ```
|
| 165 |
+
/// let x = 3.6_f64;
|
| 166 |
+
/// let y = -3.6_f64;
|
| 167 |
+
/// let abs_difference_x = (x.fract() - 0.6).abs();
|
| 168 |
+
/// let abs_difference_y = (y.fract() - (-0.6)).abs();
|
| 169 |
+
///
|
| 170 |
+
/// assert!(abs_difference_x < 1e-10);
|
| 171 |
+
/// assert!(abs_difference_y < 1e-10);
|
| 172 |
+
/// ```
|
| 173 |
+
#[rustc_allow_incoherent_impl]
|
| 174 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 175 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 176 |
+
#[rustc_const_stable(feature = "const_float_round_methods", since = "1.90.0")]
|
| 177 |
+
#[inline]
|
| 178 |
+
pub const fn fract(self) -> f64 {
|
| 179 |
+
core::f64::math::fract(self)
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding
|
| 183 |
+
/// error, yielding a more accurate result than an unfused multiply-add.
|
| 184 |
+
///
|
| 185 |
+
/// Using `mul_add` *may* be more performant than an unfused multiply-add if
|
| 186 |
+
/// the target architecture has a dedicated `fma` CPU instruction. However,
|
| 187 |
+
/// this is not always true, and will be heavily dependant on designing
|
| 188 |
+
/// algorithms with specific target hardware in mind.
|
| 189 |
+
///
|
| 190 |
+
/// # Precision
|
| 191 |
+
///
|
| 192 |
+
/// The result of this operation is guaranteed to be the rounded
|
| 193 |
+
/// infinite-precision result. It is specified by IEEE 754 as
|
| 194 |
+
/// `fusedMultiplyAdd` and guaranteed not to change.
|
| 195 |
+
///
|
| 196 |
+
/// # Examples
|
| 197 |
+
///
|
| 198 |
+
/// ```
|
| 199 |
+
/// let m = 10.0_f64;
|
| 200 |
+
/// let x = 4.0_f64;
|
| 201 |
+
/// let b = 60.0_f64;
|
| 202 |
+
///
|
| 203 |
+
/// assert_eq!(m.mul_add(x, b), 100.0);
|
| 204 |
+
/// assert_eq!(m * x + b, 100.0);
|
| 205 |
+
///
|
| 206 |
+
/// let one_plus_eps = 1.0_f64 + f64::EPSILON;
|
| 207 |
+
/// let one_minus_eps = 1.0_f64 - f64::EPSILON;
|
| 208 |
+
/// let minus_one = -1.0_f64;
|
| 209 |
+
///
|
| 210 |
+
/// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
|
| 211 |
+
/// assert_eq!(one_plus_eps.mul_add(one_minus_eps, minus_one), -f64::EPSILON * f64::EPSILON);
|
| 212 |
+
/// // Different rounding with the non-fused multiply and add.
|
| 213 |
+
/// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
|
| 214 |
+
/// ```
|
| 215 |
+
#[rustc_allow_incoherent_impl]
|
| 216 |
+
#[doc(alias = "fma", alias = "fusedMultiplyAdd")]
|
| 217 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 218 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 219 |
+
#[inline]
|
| 220 |
+
#[rustc_const_stable(feature = "const_mul_add", since = "1.94.0")]
|
| 221 |
+
pub const fn mul_add(self, a: f64, b: f64) -> f64 {
|
| 222 |
+
core::f64::math::mul_add(self, a, b)
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
/// Calculates Euclidean division, the matching method for `rem_euclid`.
|
| 226 |
+
///
|
| 227 |
+
/// This computes the integer `n` such that
|
| 228 |
+
/// `self = n * rhs + self.rem_euclid(rhs)`.
|
| 229 |
+
/// In other words, the result is `self / rhs` rounded to the integer `n`
|
| 230 |
+
/// such that `self >= n * rhs`.
|
| 231 |
+
///
|
| 232 |
+
/// # Precision
|
| 233 |
+
///
|
| 234 |
+
/// The result of this operation is guaranteed to be the rounded
|
| 235 |
+
/// infinite-precision result.
|
| 236 |
+
///
|
| 237 |
+
/// # Examples
|
| 238 |
+
///
|
| 239 |
+
/// ```
|
| 240 |
+
/// let a: f64 = 7.0;
|
| 241 |
+
/// let b = 4.0;
|
| 242 |
+
/// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
|
| 243 |
+
/// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
|
| 244 |
+
/// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
|
| 245 |
+
/// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
|
| 246 |
+
/// ```
|
| 247 |
+
#[rustc_allow_incoherent_impl]
|
| 248 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 249 |
+
#[inline]
|
| 250 |
+
#[stable(feature = "euclidean_division", since = "1.38.0")]
|
| 251 |
+
pub fn div_euclid(self, rhs: f64) -> f64 {
|
| 252 |
+
core::f64::math::div_euclid(self, rhs)
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
/// Calculates the least nonnegative remainder of `self` when divided by
|
| 256 |
+
/// `rhs`.
|
| 257 |
+
///
|
| 258 |
+
/// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
|
| 259 |
+
/// most cases. However, due to a floating point round-off error it can
|
| 260 |
+
/// result in `r == rhs.abs()`, violating the mathematical definition, if
|
| 261 |
+
/// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
|
| 262 |
+
/// This result is not an element of the function's codomain, but it is the
|
| 263 |
+
/// closest floating point number in the real numbers and thus fulfills the
|
| 264 |
+
/// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
|
| 265 |
+
/// approximately.
|
| 266 |
+
///
|
| 267 |
+
/// # Precision
|
| 268 |
+
///
|
| 269 |
+
/// The result of this operation is guaranteed to be the rounded
|
| 270 |
+
/// infinite-precision result.
|
| 271 |
+
///
|
| 272 |
+
/// # Examples
|
| 273 |
+
///
|
| 274 |
+
/// ```
|
| 275 |
+
/// let a: f64 = 7.0;
|
| 276 |
+
/// let b = 4.0;
|
| 277 |
+
/// assert_eq!(a.rem_euclid(b), 3.0);
|
| 278 |
+
/// assert_eq!((-a).rem_euclid(b), 1.0);
|
| 279 |
+
/// assert_eq!(a.rem_euclid(-b), 3.0);
|
| 280 |
+
/// assert_eq!((-a).rem_euclid(-b), 1.0);
|
| 281 |
+
/// // limitation due to round-off error
|
| 282 |
+
/// assert!((-f64::EPSILON).rem_euclid(3.0) != 0.0);
|
| 283 |
+
/// ```
|
| 284 |
+
#[doc(alias = "modulo", alias = "mod")]
|
| 285 |
+
#[rustc_allow_incoherent_impl]
|
| 286 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 287 |
+
#[inline]
|
| 288 |
+
#[stable(feature = "euclidean_division", since = "1.38.0")]
|
| 289 |
+
pub fn rem_euclid(self, rhs: f64) -> f64 {
|
| 290 |
+
core::f64::math::rem_euclid(self, rhs)
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
/// Raises a number to an integer power.
|
| 294 |
+
///
|
| 295 |
+
/// Using this function is generally faster than using `powf`.
|
| 296 |
+
/// It might have a different sequence of rounding operations than `powf`,
|
| 297 |
+
/// so the results are not guaranteed to agree.
|
| 298 |
+
///
|
| 299 |
+
/// Note that this function is special in that it can return non-NaN results for NaN inputs. For
|
| 300 |
+
/// example, `f64::powi(f64::NAN, 0)` returns `1.0`. However, if an input is a *signaling*
|
| 301 |
+
/// NaN, then the result is non-deterministically either a NaN or the result that the
|
| 302 |
+
/// corresponding quiet NaN would produce.
|
| 303 |
+
///
|
| 304 |
+
/// # Unspecified precision
|
| 305 |
+
///
|
| 306 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 307 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 308 |
+
///
|
| 309 |
+
/// # Examples
|
| 310 |
+
///
|
| 311 |
+
/// ```
|
| 312 |
+
/// let x = 2.0_f64;
|
| 313 |
+
/// let abs_difference = (x.powi(2) - (x * x)).abs();
|
| 314 |
+
/// assert!(abs_difference <= 1e-14);
|
| 315 |
+
///
|
| 316 |
+
/// assert_eq!(f64::powi(f64::NAN, 0), 1.0);
|
| 317 |
+
/// assert_eq!(f64::powi(0.0, 0), 1.0);
|
| 318 |
+
/// ```
|
| 319 |
+
#[rustc_allow_incoherent_impl]
|
| 320 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 321 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 322 |
+
#[inline]
|
| 323 |
+
pub fn powi(self, n: i32) -> f64 {
|
| 324 |
+
core::f64::math::powi(self, n)
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
/// Raises a number to a floating point power.
|
| 328 |
+
///
|
| 329 |
+
/// Note that this function is special in that it can return non-NaN results for NaN inputs. For
|
| 330 |
+
/// example, `f64::powf(f64::NAN, 0.0)` returns `1.0`. However, if an input is a *signaling*
|
| 331 |
+
/// NaN, then the result is non-deterministically either a NaN or the result that the
|
| 332 |
+
/// corresponding quiet NaN would produce.
|
| 333 |
+
///
|
| 334 |
+
/// # Unspecified precision
|
| 335 |
+
///
|
| 336 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 337 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 338 |
+
///
|
| 339 |
+
/// # Examples
|
| 340 |
+
///
|
| 341 |
+
/// ```
|
| 342 |
+
/// let x = 2.0_f64;
|
| 343 |
+
/// let abs_difference = (x.powf(2.0) - (x * x)).abs();
|
| 344 |
+
/// assert!(abs_difference <= 1e-14);
|
| 345 |
+
///
|
| 346 |
+
/// assert_eq!(f64::powf(1.0, f64::NAN), 1.0);
|
| 347 |
+
/// assert_eq!(f64::powf(f64::NAN, 0.0), 1.0);
|
| 348 |
+
/// assert_eq!(f64::powf(0.0, 0.0), 1.0);
|
| 349 |
+
/// ```
|
| 350 |
+
#[rustc_allow_incoherent_impl]
|
| 351 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 352 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 353 |
+
#[inline]
|
| 354 |
+
pub fn powf(self, n: f64) -> f64 {
|
| 355 |
+
intrinsics::powf64(self, n)
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
/// Returns the square root of a number.
|
| 359 |
+
///
|
| 360 |
+
/// Returns NaN if `self` is a negative number other than `-0.0`.
|
| 361 |
+
///
|
| 362 |
+
/// # Precision
|
| 363 |
+
///
|
| 364 |
+
/// The result of this operation is guaranteed to be the rounded
|
| 365 |
+
/// infinite-precision result. It is specified by IEEE 754 as `squareRoot`
|
| 366 |
+
/// and guaranteed not to change.
|
| 367 |
+
///
|
| 368 |
+
/// # Examples
|
| 369 |
+
///
|
| 370 |
+
/// ```
|
| 371 |
+
/// let positive = 4.0_f64;
|
| 372 |
+
/// let negative = -4.0_f64;
|
| 373 |
+
/// let negative_zero = -0.0_f64;
|
| 374 |
+
///
|
| 375 |
+
/// assert_eq!(positive.sqrt(), 2.0);
|
| 376 |
+
/// assert!(negative.sqrt().is_nan());
|
| 377 |
+
/// assert!(negative_zero.sqrt() == negative_zero);
|
| 378 |
+
/// ```
|
| 379 |
+
#[doc(alias = "squareRoot")]
|
| 380 |
+
#[rustc_allow_incoherent_impl]
|
| 381 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 382 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 383 |
+
#[inline]
|
| 384 |
+
pub fn sqrt(self) -> f64 {
|
| 385 |
+
core::f64::math::sqrt(self)
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
/// Returns `e^(self)`, (the exponential function).
|
| 389 |
+
///
|
| 390 |
+
/// # Unspecified precision
|
| 391 |
+
///
|
| 392 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 393 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 394 |
+
///
|
| 395 |
+
/// # Examples
|
| 396 |
+
///
|
| 397 |
+
/// ```
|
| 398 |
+
/// let one = 1.0_f64;
|
| 399 |
+
/// // e^1
|
| 400 |
+
/// let e = one.exp();
|
| 401 |
+
///
|
| 402 |
+
/// // ln(e) - 1 == 0
|
| 403 |
+
/// let abs_difference = (e.ln() - 1.0).abs();
|
| 404 |
+
///
|
| 405 |
+
/// assert!(abs_difference < 1e-10);
|
| 406 |
+
/// ```
|
| 407 |
+
#[rustc_allow_incoherent_impl]
|
| 408 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 409 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 410 |
+
#[inline]
|
| 411 |
+
pub fn exp(self) -> f64 {
|
| 412 |
+
intrinsics::expf64(self)
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
/// Returns `2^(self)`.
|
| 416 |
+
///
|
| 417 |
+
/// # Unspecified precision
|
| 418 |
+
///
|
| 419 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 420 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 421 |
+
///
|
| 422 |
+
/// # Examples
|
| 423 |
+
///
|
| 424 |
+
/// ```
|
| 425 |
+
/// let f = 2.0_f64;
|
| 426 |
+
///
|
| 427 |
+
/// // 2^2 - 4 == 0
|
| 428 |
+
/// let abs_difference = (f.exp2() - 4.0).abs();
|
| 429 |
+
///
|
| 430 |
+
/// assert!(abs_difference < 1e-10);
|
| 431 |
+
/// ```
|
| 432 |
+
#[rustc_allow_incoherent_impl]
|
| 433 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 434 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 435 |
+
#[inline]
|
| 436 |
+
pub fn exp2(self) -> f64 {
|
| 437 |
+
intrinsics::exp2f64(self)
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
/// Returns the natural logarithm of the number.
|
| 441 |
+
///
|
| 442 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 443 |
+
///
|
| 444 |
+
/// # Unspecified precision
|
| 445 |
+
///
|
| 446 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 447 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 448 |
+
///
|
| 449 |
+
/// # Examples
|
| 450 |
+
///
|
| 451 |
+
/// ```
|
| 452 |
+
/// let one = 1.0_f64;
|
| 453 |
+
/// // e^1
|
| 454 |
+
/// let e = one.exp();
|
| 455 |
+
///
|
| 456 |
+
/// // ln(e) - 1 == 0
|
| 457 |
+
/// let abs_difference = (e.ln() - 1.0).abs();
|
| 458 |
+
///
|
| 459 |
+
/// assert!(abs_difference < 1e-10);
|
| 460 |
+
/// ```
|
| 461 |
+
///
|
| 462 |
+
/// Non-positive values:
|
| 463 |
+
/// ```
|
| 464 |
+
/// assert_eq!(0_f64.ln(), f64::NEG_INFINITY);
|
| 465 |
+
/// assert!((-42_f64).ln().is_nan());
|
| 466 |
+
/// ```
|
| 467 |
+
#[rustc_allow_incoherent_impl]
|
| 468 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 469 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 470 |
+
#[inline]
|
| 471 |
+
pub fn ln(self) -> f64 {
|
| 472 |
+
intrinsics::logf64(self)
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
/// Returns the logarithm of the number with respect to an arbitrary base.
|
| 476 |
+
///
|
| 477 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 478 |
+
///
|
| 479 |
+
/// The result might not be correctly rounded owing to implementation details;
|
| 480 |
+
/// `self.log2()` can produce more accurate results for base 2, and
|
| 481 |
+
/// `self.log10()` can produce more accurate results for base 10.
|
| 482 |
+
///
|
| 483 |
+
/// # Unspecified precision
|
| 484 |
+
///
|
| 485 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 486 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 487 |
+
///
|
| 488 |
+
/// # Examples
|
| 489 |
+
///
|
| 490 |
+
/// ```
|
| 491 |
+
/// let twenty_five = 25.0_f64;
|
| 492 |
+
///
|
| 493 |
+
/// // log5(25) - 2 == 0
|
| 494 |
+
/// let abs_difference = (twenty_five.log(5.0) - 2.0).abs();
|
| 495 |
+
///
|
| 496 |
+
/// assert!(abs_difference < 1e-10);
|
| 497 |
+
/// ```
|
| 498 |
+
///
|
| 499 |
+
/// Non-positive values:
|
| 500 |
+
/// ```
|
| 501 |
+
/// assert_eq!(0_f64.log(10.0), f64::NEG_INFINITY);
|
| 502 |
+
/// assert!((-42_f64).log(10.0).is_nan());
|
| 503 |
+
/// ```
|
| 504 |
+
#[rustc_allow_incoherent_impl]
|
| 505 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 506 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 507 |
+
#[inline]
|
| 508 |
+
pub fn log(self, base: f64) -> f64 {
|
| 509 |
+
self.ln() / base.ln()
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
/// Returns the base 2 logarithm of the number.
|
| 513 |
+
///
|
| 514 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 515 |
+
///
|
| 516 |
+
/// # Unspecified precision
|
| 517 |
+
///
|
| 518 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 519 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 520 |
+
///
|
| 521 |
+
/// # Examples
|
| 522 |
+
///
|
| 523 |
+
/// ```
|
| 524 |
+
/// let four = 4.0_f64;
|
| 525 |
+
///
|
| 526 |
+
/// // log2(4) - 2 == 0
|
| 527 |
+
/// let abs_difference = (four.log2() - 2.0).abs();
|
| 528 |
+
///
|
| 529 |
+
/// assert!(abs_difference < 1e-10);
|
| 530 |
+
/// ```
|
| 531 |
+
///
|
| 532 |
+
/// Non-positive values:
|
| 533 |
+
/// ```
|
| 534 |
+
/// assert_eq!(0_f64.log2(), f64::NEG_INFINITY);
|
| 535 |
+
/// assert!((-42_f64).log2().is_nan());
|
| 536 |
+
/// ```
|
| 537 |
+
#[rustc_allow_incoherent_impl]
|
| 538 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 539 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 540 |
+
#[inline]
|
| 541 |
+
pub fn log2(self) -> f64 {
|
| 542 |
+
intrinsics::log2f64(self)
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
/// Returns the base 10 logarithm of the number.
|
| 546 |
+
///
|
| 547 |
+
/// This returns NaN when the number is negative, and negative infinity when number is zero.
|
| 548 |
+
///
|
| 549 |
+
/// # Unspecified precision
|
| 550 |
+
///
|
| 551 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 552 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 553 |
+
///
|
| 554 |
+
/// # Examples
|
| 555 |
+
///
|
| 556 |
+
/// ```
|
| 557 |
+
/// let hundred = 100.0_f64;
|
| 558 |
+
///
|
| 559 |
+
/// // log10(100) - 2 == 0
|
| 560 |
+
/// let abs_difference = (hundred.log10() - 2.0).abs();
|
| 561 |
+
///
|
| 562 |
+
/// assert!(abs_difference < 1e-10);
|
| 563 |
+
/// ```
|
| 564 |
+
///
|
| 565 |
+
/// Non-positive values:
|
| 566 |
+
/// ```
|
| 567 |
+
/// assert_eq!(0_f64.log10(), f64::NEG_INFINITY);
|
| 568 |
+
/// assert!((-42_f64).log10().is_nan());
|
| 569 |
+
/// ```
|
| 570 |
+
#[rustc_allow_incoherent_impl]
|
| 571 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 572 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 573 |
+
#[inline]
|
| 574 |
+
pub fn log10(self) -> f64 {
|
| 575 |
+
intrinsics::log10f64(self)
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
/// The positive difference of two numbers.
|
| 579 |
+
///
|
| 580 |
+
/// * If `self <= other`: `0.0`
|
| 581 |
+
/// * Else: `self - other`
|
| 582 |
+
///
|
| 583 |
+
/// # Unspecified precision
|
| 584 |
+
///
|
| 585 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 586 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 587 |
+
/// This function currently corresponds to the `fdim` from libc on Unix and
|
| 588 |
+
/// Windows. Note that this might change in the future.
|
| 589 |
+
///
|
| 590 |
+
/// # Examples
|
| 591 |
+
///
|
| 592 |
+
/// ```
|
| 593 |
+
/// let x = 3.0_f64;
|
| 594 |
+
/// let y = -3.0_f64;
|
| 595 |
+
///
|
| 596 |
+
/// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
|
| 597 |
+
/// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();
|
| 598 |
+
///
|
| 599 |
+
/// assert!(abs_difference_x < 1e-10);
|
| 600 |
+
/// assert!(abs_difference_y < 1e-10);
|
| 601 |
+
/// ```
|
| 602 |
+
#[rustc_allow_incoherent_impl]
|
| 603 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 604 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 605 |
+
#[inline]
|
| 606 |
+
#[deprecated(
|
| 607 |
+
since = "1.10.0",
|
| 608 |
+
note = "you probably meant `(self - other).abs()`: \
|
| 609 |
+
this operation is `(self - other).max(0.0)` \
|
| 610 |
+
except that `abs_sub` also propagates NaNs (also \
|
| 611 |
+
known as `fdim` in C). If you truly need the positive \
|
| 612 |
+
difference, consider using that expression or the C function \
|
| 613 |
+
`fdim`, depending on how you wish to handle NaN (please consider \
|
| 614 |
+
filing an issue describing your use-case too)."
|
| 615 |
+
)]
|
| 616 |
+
pub fn abs_sub(self, other: f64) -> f64 {
|
| 617 |
+
#[allow(deprecated)]
|
| 618 |
+
core::f64::math::abs_sub(self, other)
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
/// Returns the cube root of a number.
|
| 622 |
+
///
|
| 623 |
+
/// # Unspecified precision
|
| 624 |
+
///
|
| 625 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 626 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 627 |
+
/// This function currently corresponds to the `cbrt` from libc on Unix and
|
| 628 |
+
/// Windows. Note that this might change in the future.
|
| 629 |
+
///
|
| 630 |
+
/// # Examples
|
| 631 |
+
///
|
| 632 |
+
/// ```
|
| 633 |
+
/// let x = 8.0_f64;
|
| 634 |
+
///
|
| 635 |
+
/// // x^(1/3) - 2 == 0
|
| 636 |
+
/// let abs_difference = (x.cbrt() - 2.0).abs();
|
| 637 |
+
///
|
| 638 |
+
/// assert!(abs_difference < 1e-10);
|
| 639 |
+
/// ```
|
| 640 |
+
#[rustc_allow_incoherent_impl]
|
| 641 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 642 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 643 |
+
#[inline]
|
| 644 |
+
pub fn cbrt(self) -> f64 {
|
| 645 |
+
core::f64::math::cbrt(self)
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
/// Compute the distance between the origin and a point (`x`, `y`) on the
|
| 649 |
+
/// Euclidean plane. Equivalently, compute the length of the hypotenuse of a
|
| 650 |
+
/// right-angle triangle with other sides having length `x.abs()` and
|
| 651 |
+
/// `y.abs()`.
|
| 652 |
+
///
|
| 653 |
+
/// # Unspecified precision
|
| 654 |
+
///
|
| 655 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 656 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 657 |
+
/// This function currently corresponds to the `hypot` from libc on Unix
|
| 658 |
+
/// and Windows. Note that this might change in the future.
|
| 659 |
+
///
|
| 660 |
+
/// # Examples
|
| 661 |
+
///
|
| 662 |
+
/// ```
|
| 663 |
+
/// let x = 2.0_f64;
|
| 664 |
+
/// let y = 3.0_f64;
|
| 665 |
+
///
|
| 666 |
+
/// // sqrt(x^2 + y^2)
|
| 667 |
+
/// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
|
| 668 |
+
///
|
| 669 |
+
/// assert!(abs_difference < 1e-10);
|
| 670 |
+
/// ```
|
| 671 |
+
#[rustc_allow_incoherent_impl]
|
| 672 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 673 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 674 |
+
#[inline]
|
| 675 |
+
pub fn hypot(self, other: f64) -> f64 {
|
| 676 |
+
cmath::hypot(self, other)
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
/// Computes the sine of a number (in radians).
|
| 680 |
+
///
|
| 681 |
+
/// # Unspecified precision
|
| 682 |
+
///
|
| 683 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 684 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 685 |
+
///
|
| 686 |
+
/// # Examples
|
| 687 |
+
///
|
| 688 |
+
/// ```
|
| 689 |
+
/// let x = std::f64::consts::FRAC_PI_2;
|
| 690 |
+
///
|
| 691 |
+
/// let abs_difference = (x.sin() - 1.0).abs();
|
| 692 |
+
///
|
| 693 |
+
/// assert!(abs_difference < 1e-10);
|
| 694 |
+
/// ```
|
| 695 |
+
#[rustc_allow_incoherent_impl]
|
| 696 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 697 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 698 |
+
#[inline]
|
| 699 |
+
pub fn sin(self) -> f64 {
|
| 700 |
+
intrinsics::sinf64(self)
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
/// Computes the cosine of a number (in radians).
|
| 704 |
+
///
|
| 705 |
+
/// # Unspecified precision
|
| 706 |
+
///
|
| 707 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 708 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 709 |
+
///
|
| 710 |
+
/// # Examples
|
| 711 |
+
///
|
| 712 |
+
/// ```
|
| 713 |
+
/// let x = 2.0 * std::f64::consts::PI;
|
| 714 |
+
///
|
| 715 |
+
/// let abs_difference = (x.cos() - 1.0).abs();
|
| 716 |
+
///
|
| 717 |
+
/// assert!(abs_difference < 1e-10);
|
| 718 |
+
/// ```
|
| 719 |
+
#[rustc_allow_incoherent_impl]
|
| 720 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 721 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 722 |
+
#[inline]
|
| 723 |
+
pub fn cos(self) -> f64 {
|
| 724 |
+
intrinsics::cosf64(self)
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
/// Computes the tangent of a number (in radians).
|
| 728 |
+
///
|
| 729 |
+
/// # Unspecified precision
|
| 730 |
+
///
|
| 731 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 732 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 733 |
+
/// This function currently corresponds to the `tan` from libc on Unix and
|
| 734 |
+
/// Windows. Note that this might change in the future.
|
| 735 |
+
///
|
| 736 |
+
/// # Examples
|
| 737 |
+
///
|
| 738 |
+
/// ```
|
| 739 |
+
/// let x = std::f64::consts::FRAC_PI_4;
|
| 740 |
+
/// let abs_difference = (x.tan() - 1.0).abs();
|
| 741 |
+
///
|
| 742 |
+
/// assert!(abs_difference < 1e-14);
|
| 743 |
+
/// ```
|
| 744 |
+
#[rustc_allow_incoherent_impl]
|
| 745 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 746 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 747 |
+
#[inline]
|
| 748 |
+
pub fn tan(self) -> f64 {
|
| 749 |
+
cmath::tan(self)
|
| 750 |
+
}
|
| 751 |
+
|
| 752 |
+
/// Computes the arcsine of a number. Return value is in radians in
|
| 753 |
+
/// the range [-pi/2, pi/2] or NaN if the number is outside the range
|
| 754 |
+
/// [-1, 1].
|
| 755 |
+
///
|
| 756 |
+
/// # Unspecified precision
|
| 757 |
+
///
|
| 758 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 759 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 760 |
+
/// This function currently corresponds to the `asin` from libc on Unix and
|
| 761 |
+
/// Windows. Note that this might change in the future.
|
| 762 |
+
///
|
| 763 |
+
/// # Examples
|
| 764 |
+
///
|
| 765 |
+
/// ```
|
| 766 |
+
/// let f = std::f64::consts::FRAC_PI_4;
|
| 767 |
+
///
|
| 768 |
+
/// // asin(sin(pi/2))
|
| 769 |
+
/// let abs_difference = (f.sin().asin() - f).abs();
|
| 770 |
+
///
|
| 771 |
+
/// assert!(abs_difference < 1e-14);
|
| 772 |
+
/// ```
|
| 773 |
+
#[doc(alias = "arcsin")]
|
| 774 |
+
#[rustc_allow_incoherent_impl]
|
| 775 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 776 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 777 |
+
#[inline]
|
| 778 |
+
pub fn asin(self) -> f64 {
|
| 779 |
+
cmath::asin(self)
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
/// Computes the arccosine of a number. Return value is in radians in
|
| 783 |
+
/// the range [0, pi] or NaN if the number is outside the range
|
| 784 |
+
/// [-1, 1].
|
| 785 |
+
///
|
| 786 |
+
/// # Unspecified precision
|
| 787 |
+
///
|
| 788 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 789 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 790 |
+
/// This function currently corresponds to the `acos` from libc on Unix and
|
| 791 |
+
/// Windows. Note that this might change in the future.
|
| 792 |
+
///
|
| 793 |
+
/// # Examples
|
| 794 |
+
///
|
| 795 |
+
/// ```
|
| 796 |
+
/// let f = std::f64::consts::FRAC_PI_4;
|
| 797 |
+
///
|
| 798 |
+
/// // acos(cos(pi/4))
|
| 799 |
+
/// let abs_difference = (f.cos().acos() - std::f64::consts::FRAC_PI_4).abs();
|
| 800 |
+
///
|
| 801 |
+
/// assert!(abs_difference < 1e-10);
|
| 802 |
+
/// ```
|
| 803 |
+
#[doc(alias = "arccos")]
|
| 804 |
+
#[rustc_allow_incoherent_impl]
|
| 805 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 806 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 807 |
+
#[inline]
|
| 808 |
+
pub fn acos(self) -> f64 {
|
| 809 |
+
cmath::acos(self)
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
/// Computes the arctangent of a number. Return value is in radians in the
|
| 813 |
+
/// range [-pi/2, pi/2];
|
| 814 |
+
///
|
| 815 |
+
/// # Unspecified precision
|
| 816 |
+
///
|
| 817 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 818 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 819 |
+
/// This function currently corresponds to the `atan` from libc on Unix and
|
| 820 |
+
/// Windows. Note that this might change in the future.
|
| 821 |
+
///
|
| 822 |
+
/// # Examples
|
| 823 |
+
///
|
| 824 |
+
/// ```
|
| 825 |
+
/// let f = 1.0_f64;
|
| 826 |
+
///
|
| 827 |
+
/// // atan(tan(1))
|
| 828 |
+
/// let abs_difference = (f.tan().atan() - 1.0).abs();
|
| 829 |
+
///
|
| 830 |
+
/// assert!(abs_difference < 1e-10);
|
| 831 |
+
/// ```
|
| 832 |
+
#[doc(alias = "arctan")]
|
| 833 |
+
#[rustc_allow_incoherent_impl]
|
| 834 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 835 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 836 |
+
#[inline]
|
| 837 |
+
pub fn atan(self) -> f64 {
|
| 838 |
+
cmath::atan(self)
|
| 839 |
+
}
|
| 840 |
+
|
| 841 |
+
/// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) in radians.
|
| 842 |
+
///
|
| 843 |
+
/// | `x` | `y` | Piecewise Definition | Range |
|
| 844 |
+
/// |---------|---------|----------------------|---------------|
|
| 845 |
+
/// | `>= +0` | `>= +0` | `arctan(y/x)` | `[+0, +pi/2]` |
|
| 846 |
+
/// | `>= +0` | `<= -0` | `arctan(y/x)` | `[-pi/2, -0]` |
|
| 847 |
+
/// | `<= -0` | `>= +0` | `arctan(y/x) + pi` | `[+pi/2, +pi]`|
|
| 848 |
+
/// | `<= -0` | `<= -0` | `arctan(y/x) - pi` | `[-pi, -pi/2]`|
|
| 849 |
+
///
|
| 850 |
+
/// # Unspecified precision
|
| 851 |
+
///
|
| 852 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 853 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 854 |
+
/// This function currently corresponds to the `atan2` from libc on Unix
|
| 855 |
+
/// and Windows. Note that this might change in the future.
|
| 856 |
+
///
|
| 857 |
+
/// # Examples
|
| 858 |
+
///
|
| 859 |
+
/// ```
|
| 860 |
+
/// // Positive angles measured counter-clockwise
|
| 861 |
+
/// // from positive x axis
|
| 862 |
+
/// // -pi/4 radians (45 deg clockwise)
|
| 863 |
+
/// let x1 = 3.0_f64;
|
| 864 |
+
/// let y1 = -3.0_f64;
|
| 865 |
+
///
|
| 866 |
+
/// // 3pi/4 radians (135 deg counter-clockwise)
|
| 867 |
+
/// let x2 = -3.0_f64;
|
| 868 |
+
/// let y2 = 3.0_f64;
|
| 869 |
+
///
|
| 870 |
+
/// let abs_difference_1 = (y1.atan2(x1) - (-std::f64::consts::FRAC_PI_4)).abs();
|
| 871 |
+
/// let abs_difference_2 = (y2.atan2(x2) - (3.0 * std::f64::consts::FRAC_PI_4)).abs();
|
| 872 |
+
///
|
| 873 |
+
/// assert!(abs_difference_1 < 1e-10);
|
| 874 |
+
/// assert!(abs_difference_2 < 1e-10);
|
| 875 |
+
/// ```
|
| 876 |
+
#[rustc_allow_incoherent_impl]
|
| 877 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 878 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 879 |
+
#[inline]
|
| 880 |
+
pub fn atan2(self, other: f64) -> f64 {
|
| 881 |
+
cmath::atan2(self, other)
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
+
/// Simultaneously computes the sine and cosine of the number, `x`. Returns
|
| 885 |
+
/// `(sin(x), cos(x))`.
|
| 886 |
+
///
|
| 887 |
+
/// # Unspecified precision
|
| 888 |
+
///
|
| 889 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 890 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 891 |
+
/// This function currently corresponds to the `(f64::sin(x),
|
| 892 |
+
/// f64::cos(x))`. Note that this might change in the future.
|
| 893 |
+
///
|
| 894 |
+
/// # Examples
|
| 895 |
+
///
|
| 896 |
+
/// ```
|
| 897 |
+
/// let x = std::f64::consts::FRAC_PI_4;
|
| 898 |
+
/// let f = x.sin_cos();
|
| 899 |
+
///
|
| 900 |
+
/// let abs_difference_0 = (f.0 - x.sin()).abs();
|
| 901 |
+
/// let abs_difference_1 = (f.1 - x.cos()).abs();
|
| 902 |
+
///
|
| 903 |
+
/// assert!(abs_difference_0 < 1e-10);
|
| 904 |
+
/// assert!(abs_difference_1 < 1e-10);
|
| 905 |
+
/// ```
|
| 906 |
+
#[doc(alias = "sincos")]
|
| 907 |
+
#[rustc_allow_incoherent_impl]
|
| 908 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 909 |
+
#[inline]
|
| 910 |
+
pub fn sin_cos(self) -> (f64, f64) {
|
| 911 |
+
(self.sin(), self.cos())
|
| 912 |
+
}
|
| 913 |
+
|
| 914 |
+
/// Returns `e^(self) - 1` in a way that is accurate even if the
|
| 915 |
+
/// number is close to zero.
|
| 916 |
+
///
|
| 917 |
+
/// # Unspecified precision
|
| 918 |
+
///
|
| 919 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 920 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 921 |
+
/// This function currently corresponds to the `expm1` from libc on Unix
|
| 922 |
+
/// and Windows. Note that this might change in the future.
|
| 923 |
+
///
|
| 924 |
+
/// # Examples
|
| 925 |
+
///
|
| 926 |
+
/// ```
|
| 927 |
+
/// let x = 1e-16_f64;
|
| 928 |
+
///
|
| 929 |
+
/// // for very small x, e^x is approximately 1 + x + x^2 / 2
|
| 930 |
+
/// let approx = x + x * x / 2.0;
|
| 931 |
+
/// let abs_difference = (x.exp_m1() - approx).abs();
|
| 932 |
+
///
|
| 933 |
+
/// assert!(abs_difference < 1e-20);
|
| 934 |
+
/// ```
|
| 935 |
+
#[rustc_allow_incoherent_impl]
|
| 936 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 937 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 938 |
+
#[inline]
|
| 939 |
+
pub fn exp_m1(self) -> f64 {
|
| 940 |
+
cmath::expm1(self)
|
| 941 |
+
}
|
| 942 |
+
|
| 943 |
+
/// Returns `ln(1+n)` (natural logarithm) more accurately than if
|
| 944 |
+
/// the operations were performed separately.
|
| 945 |
+
///
|
| 946 |
+
/// This returns NaN when `n < -1.0`, and negative infinity when `n == -1.0`.
|
| 947 |
+
///
|
| 948 |
+
/// # Unspecified precision
|
| 949 |
+
///
|
| 950 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 951 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 952 |
+
/// This function currently corresponds to the `log1p` from libc on Unix
|
| 953 |
+
/// and Windows. Note that this might change in the future.
|
| 954 |
+
///
|
| 955 |
+
/// # Examples
|
| 956 |
+
///
|
| 957 |
+
/// ```
|
| 958 |
+
/// let x = 1e-16_f64;
|
| 959 |
+
///
|
| 960 |
+
/// // for very small x, ln(1 + x) is approximately x - x^2 / 2
|
| 961 |
+
/// let approx = x - x * x / 2.0;
|
| 962 |
+
/// let abs_difference = (x.ln_1p() - approx).abs();
|
| 963 |
+
///
|
| 964 |
+
/// assert!(abs_difference < 1e-20);
|
| 965 |
+
/// ```
|
| 966 |
+
///
|
| 967 |
+
/// Out-of-range values:
|
| 968 |
+
/// ```
|
| 969 |
+
/// assert_eq!((-1.0_f64).ln_1p(), f64::NEG_INFINITY);
|
| 970 |
+
/// assert!((-2.0_f64).ln_1p().is_nan());
|
| 971 |
+
/// ```
|
| 972 |
+
#[doc(alias = "log1p")]
|
| 973 |
+
#[rustc_allow_incoherent_impl]
|
| 974 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 975 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 976 |
+
#[inline]
|
| 977 |
+
pub fn ln_1p(self) -> f64 {
|
| 978 |
+
cmath::log1p(self)
|
| 979 |
+
}
|
| 980 |
+
|
| 981 |
+
/// Hyperbolic sine function.
|
| 982 |
+
///
|
| 983 |
+
/// # Unspecified precision
|
| 984 |
+
///
|
| 985 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 986 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 987 |
+
/// This function currently corresponds to the `sinh` from libc on Unix
|
| 988 |
+
/// and Windows. Note that this might change in the future.
|
| 989 |
+
///
|
| 990 |
+
/// # Examples
|
| 991 |
+
///
|
| 992 |
+
/// ```
|
| 993 |
+
/// let e = std::f64::consts::E;
|
| 994 |
+
/// let x = 1.0_f64;
|
| 995 |
+
///
|
| 996 |
+
/// let f = x.sinh();
|
| 997 |
+
/// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
|
| 998 |
+
/// let g = ((e * e) - 1.0) / (2.0 * e);
|
| 999 |
+
/// let abs_difference = (f - g).abs();
|
| 1000 |
+
///
|
| 1001 |
+
/// assert!(abs_difference < 1e-10);
|
| 1002 |
+
/// ```
|
| 1003 |
+
#[rustc_allow_incoherent_impl]
|
| 1004 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1005 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1006 |
+
#[inline]
|
| 1007 |
+
pub fn sinh(self) -> f64 {
|
| 1008 |
+
cmath::sinh(self)
|
| 1009 |
+
}
|
| 1010 |
+
|
| 1011 |
+
/// Hyperbolic cosine function.
|
| 1012 |
+
///
|
| 1013 |
+
/// # Unspecified precision
|
| 1014 |
+
///
|
| 1015 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1016 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1017 |
+
/// This function currently corresponds to the `cosh` from libc on Unix
|
| 1018 |
+
/// and Windows. Note that this might change in the future.
|
| 1019 |
+
///
|
| 1020 |
+
/// # Examples
|
| 1021 |
+
///
|
| 1022 |
+
/// ```
|
| 1023 |
+
/// let e = std::f64::consts::E;
|
| 1024 |
+
/// let x = 1.0_f64;
|
| 1025 |
+
/// let f = x.cosh();
|
| 1026 |
+
/// // Solving cosh() at 1 gives this result
|
| 1027 |
+
/// let g = ((e * e) + 1.0) / (2.0 * e);
|
| 1028 |
+
/// let abs_difference = (f - g).abs();
|
| 1029 |
+
///
|
| 1030 |
+
/// // Same result
|
| 1031 |
+
/// assert!(abs_difference < 1.0e-10);
|
| 1032 |
+
/// ```
|
| 1033 |
+
#[rustc_allow_incoherent_impl]
|
| 1034 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1035 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1036 |
+
#[inline]
|
| 1037 |
+
pub fn cosh(self) -> f64 {
|
| 1038 |
+
cmath::cosh(self)
|
| 1039 |
+
}
|
| 1040 |
+
|
| 1041 |
+
/// Hyperbolic tangent function.
|
| 1042 |
+
///
|
| 1043 |
+
/// # Unspecified precision
|
| 1044 |
+
///
|
| 1045 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1046 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1047 |
+
/// This function currently corresponds to the `tanh` from libc on Unix
|
| 1048 |
+
/// and Windows. Note that this might change in the future.
|
| 1049 |
+
///
|
| 1050 |
+
/// # Examples
|
| 1051 |
+
///
|
| 1052 |
+
/// ```
|
| 1053 |
+
/// let e = std::f64::consts::E;
|
| 1054 |
+
/// let x = 1.0_f64;
|
| 1055 |
+
///
|
| 1056 |
+
/// let f = x.tanh();
|
| 1057 |
+
/// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
|
| 1058 |
+
/// let g = (1.0 - e.powi(-2)) / (1.0 + e.powi(-2));
|
| 1059 |
+
/// let abs_difference = (f - g).abs();
|
| 1060 |
+
///
|
| 1061 |
+
/// assert!(abs_difference < 1.0e-10);
|
| 1062 |
+
/// ```
|
| 1063 |
+
#[rustc_allow_incoherent_impl]
|
| 1064 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1065 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1066 |
+
#[inline]
|
| 1067 |
+
pub fn tanh(self) -> f64 {
|
| 1068 |
+
cmath::tanh(self)
|
| 1069 |
+
}
|
| 1070 |
+
|
| 1071 |
+
/// Inverse hyperbolic sine function.
|
| 1072 |
+
///
|
| 1073 |
+
/// # Unspecified precision
|
| 1074 |
+
///
|
| 1075 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1076 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1077 |
+
///
|
| 1078 |
+
/// # Examples
|
| 1079 |
+
///
|
| 1080 |
+
/// ```
|
| 1081 |
+
/// let x = 1.0_f64;
|
| 1082 |
+
/// let f = x.sinh().asinh();
|
| 1083 |
+
///
|
| 1084 |
+
/// let abs_difference = (f - x).abs();
|
| 1085 |
+
///
|
| 1086 |
+
/// assert!(abs_difference < 1.0e-10);
|
| 1087 |
+
/// ```
|
| 1088 |
+
#[doc(alias = "arcsinh")]
|
| 1089 |
+
#[rustc_allow_incoherent_impl]
|
| 1090 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1091 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1092 |
+
#[inline]
|
| 1093 |
+
pub fn asinh(self) -> f64 {
|
| 1094 |
+
let ax = self.abs();
|
| 1095 |
+
let ix = 1.0 / ax;
|
| 1096 |
+
(ax + (ax / (Self::hypot(1.0, ix) + ix))).ln_1p().copysign(self)
|
| 1097 |
+
}
|
| 1098 |
+
|
| 1099 |
+
/// Inverse hyperbolic cosine function.
|
| 1100 |
+
///
|
| 1101 |
+
/// # Unspecified precision
|
| 1102 |
+
///
|
| 1103 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1104 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1105 |
+
///
|
| 1106 |
+
/// # Examples
|
| 1107 |
+
///
|
| 1108 |
+
/// ```
|
| 1109 |
+
/// let x = 1.0_f64;
|
| 1110 |
+
/// let f = x.cosh().acosh();
|
| 1111 |
+
///
|
| 1112 |
+
/// let abs_difference = (f - x).abs();
|
| 1113 |
+
///
|
| 1114 |
+
/// assert!(abs_difference < 1.0e-10);
|
| 1115 |
+
/// ```
|
| 1116 |
+
#[doc(alias = "arccosh")]
|
| 1117 |
+
#[rustc_allow_incoherent_impl]
|
| 1118 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1119 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1120 |
+
#[inline]
|
| 1121 |
+
pub fn acosh(self) -> f64 {
|
| 1122 |
+
if self < 1.0 {
|
| 1123 |
+
Self::NAN
|
| 1124 |
+
} else {
|
| 1125 |
+
(self + ((self - 1.0).sqrt() * (self + 1.0).sqrt())).ln()
|
| 1126 |
+
}
|
| 1127 |
+
}
|
| 1128 |
+
|
| 1129 |
+
/// Inverse hyperbolic tangent function.
|
| 1130 |
+
///
|
| 1131 |
+
/// # Unspecified precision
|
| 1132 |
+
///
|
| 1133 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1134 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1135 |
+
///
|
| 1136 |
+
/// # Examples
|
| 1137 |
+
///
|
| 1138 |
+
/// ```
|
| 1139 |
+
/// let x = std::f64::consts::FRAC_PI_6;
|
| 1140 |
+
/// let f = x.tanh().atanh();
|
| 1141 |
+
///
|
| 1142 |
+
/// let abs_difference = (f - x).abs();
|
| 1143 |
+
///
|
| 1144 |
+
/// assert!(abs_difference < 1.0e-10);
|
| 1145 |
+
/// ```
|
| 1146 |
+
#[doc(alias = "arctanh")]
|
| 1147 |
+
#[rustc_allow_incoherent_impl]
|
| 1148 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1149 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1150 |
+
#[inline]
|
| 1151 |
+
pub fn atanh(self) -> f64 {
|
| 1152 |
+
0.5 * ((2.0 * self) / (1.0 - self)).ln_1p()
|
| 1153 |
+
}
|
| 1154 |
+
|
| 1155 |
+
/// Gamma function.
|
| 1156 |
+
///
|
| 1157 |
+
/// # Unspecified precision
|
| 1158 |
+
///
|
| 1159 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1160 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1161 |
+
/// This function currently corresponds to the `tgamma` from libc on Unix
|
| 1162 |
+
/// and Windows. Note that this might change in the future.
|
| 1163 |
+
///
|
| 1164 |
+
/// # Examples
|
| 1165 |
+
///
|
| 1166 |
+
/// ```
|
| 1167 |
+
/// #![feature(float_gamma)]
|
| 1168 |
+
/// let x = 5.0f64;
|
| 1169 |
+
///
|
| 1170 |
+
/// let abs_difference = (x.gamma() - 24.0).abs();
|
| 1171 |
+
///
|
| 1172 |
+
/// assert!(abs_difference <= 1e-10);
|
| 1173 |
+
/// ```
|
| 1174 |
+
#[rustc_allow_incoherent_impl]
|
| 1175 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1176 |
+
#[unstable(feature = "float_gamma", issue = "99842")]
|
| 1177 |
+
#[inline]
|
| 1178 |
+
pub fn gamma(self) -> f64 {
|
| 1179 |
+
cmath::tgamma(self)
|
| 1180 |
+
}
|
| 1181 |
+
|
| 1182 |
+
/// Natural logarithm of the absolute value of the gamma function
|
| 1183 |
+
///
|
| 1184 |
+
/// The integer part of the tuple indicates the sign of the gamma function.
|
| 1185 |
+
///
|
| 1186 |
+
/// # Unspecified precision
|
| 1187 |
+
///
|
| 1188 |
+
/// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
|
| 1189 |
+
/// can even differ within the same execution from one invocation to the next.
|
| 1190 |
+
/// This function currently corresponds to the `lgamma_r` from libc on Unix
|
| 1191 |
+
/// and Windows. Note that this might change in the future.
|
| 1192 |
+
///
|
| 1193 |
+
/// # Examples
|
| 1194 |
+
///
|
| 1195 |
+
/// ```
|
| 1196 |
+
/// #![feature(float_gamma)]
|
| 1197 |
+
/// let x = 2.0f64;
|
| 1198 |
+
///
|
| 1199 |
+
/// let abs_difference = (x.ln_gamma().0 - 0.0).abs();
|
| 1200 |
+
///
|
| 1201 |
+
/// assert!(abs_difference <= f64::EPSILON);
|
| 1202 |
+
/// ```
|
| 1203 |
+
#[rustc_allow_incoherent_impl]
|
| 1204 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1205 |
+
#[unstable(feature = "float_gamma", issue = "99842")]
|
| 1206 |
+
#[inline]
|
| 1207 |
+
pub fn ln_gamma(self) -> (f64, i32) {
|
| 1208 |
+
let mut signgamp: i32 = 0;
|
| 1209 |
+
let x = cmath::lgamma_r(self, &mut signgamp);
|
| 1210 |
+
(x, signgamp)
|
| 1211 |
+
}
|
| 1212 |
+
|
| 1213 |
+
/// Error function.
|
| 1214 |
+
///
|
| 1215 |
+
/// # Unspecified precision
|
| 1216 |
+
///
|
| 1217 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 1218 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 1219 |
+
///
|
| 1220 |
+
/// This function currently corresponds to the `erf` from libc on Unix
|
| 1221 |
+
/// and Windows. Note that this might change in the future.
|
| 1222 |
+
///
|
| 1223 |
+
/// # Examples
|
| 1224 |
+
///
|
| 1225 |
+
/// ```
|
| 1226 |
+
/// #![feature(float_erf)]
|
| 1227 |
+
/// /// The error function relates what percent of a normal distribution lies
|
| 1228 |
+
/// /// within `x` standard deviations (scaled by `1/sqrt(2)`).
|
| 1229 |
+
/// fn within_standard_deviations(x: f64) -> f64 {
|
| 1230 |
+
/// (x * std::f64::consts::FRAC_1_SQRT_2).erf() * 100.0
|
| 1231 |
+
/// }
|
| 1232 |
+
///
|
| 1233 |
+
/// // 68% of a normal distribution is within one standard deviation
|
| 1234 |
+
/// assert!((within_standard_deviations(1.0) - 68.269).abs() < 0.01);
|
| 1235 |
+
/// // 95% of a normal distribution is within two standard deviations
|
| 1236 |
+
/// assert!((within_standard_deviations(2.0) - 95.450).abs() < 0.01);
|
| 1237 |
+
/// // 99.7% of a normal distribution is within three standard deviations
|
| 1238 |
+
/// assert!((within_standard_deviations(3.0) - 99.730).abs() < 0.01);
|
| 1239 |
+
/// ```
|
| 1240 |
+
#[rustc_allow_incoherent_impl]
|
| 1241 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1242 |
+
#[unstable(feature = "float_erf", issue = "136321")]
|
| 1243 |
+
#[inline]
|
| 1244 |
+
pub fn erf(self) -> f64 {
|
| 1245 |
+
cmath::erf(self)
|
| 1246 |
+
}
|
| 1247 |
+
|
| 1248 |
+
/// Complementary error function.
|
| 1249 |
+
///
|
| 1250 |
+
/// # Unspecified precision
|
| 1251 |
+
///
|
| 1252 |
+
/// The precision of this function is non-deterministic. This means it varies by platform,
|
| 1253 |
+
/// Rust version, and can even differ within the same execution from one invocation to the next.
|
| 1254 |
+
///
|
| 1255 |
+
/// This function currently corresponds to the `erfc` from libc on Unix
|
| 1256 |
+
/// and Windows. Note that this might change in the future.
|
| 1257 |
+
///
|
| 1258 |
+
/// # Examples
|
| 1259 |
+
///
|
| 1260 |
+
/// ```
|
| 1261 |
+
/// #![feature(float_erf)]
|
| 1262 |
+
/// let x: f64 = 0.123;
|
| 1263 |
+
///
|
| 1264 |
+
/// let one = x.erf() + x.erfc();
|
| 1265 |
+
/// let abs_difference = (one - 1.0).abs();
|
| 1266 |
+
///
|
| 1267 |
+
/// assert!(abs_difference <= 1e-10);
|
| 1268 |
+
/// ```
|
| 1269 |
+
#[rustc_allow_incoherent_impl]
|
| 1270 |
+
#[must_use = "method returns a new number and does not mutate the original value"]
|
| 1271 |
+
#[unstable(feature = "float_erf", issue = "136321")]
|
| 1272 |
+
#[inline]
|
| 1273 |
+
pub fn erfc(self) -> f64 {
|
| 1274 |
+
cmath::erfc(self)
|
| 1275 |
+
}
|
| 1276 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/num/mod.rs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Additional functionality for numerics.
|
| 2 |
+
//!
|
| 3 |
+
//! This module provides some extra types that are useful when doing numerical
|
| 4 |
+
//! work. See the individual documentation for each piece for more information.
|
| 5 |
+
|
| 6 |
+
#![stable(feature = "rust1", since = "1.0.0")]
|
| 7 |
+
#![allow(missing_docs)]
|
| 8 |
+
|
| 9 |
+
#[stable(feature = "int_error_matching", since = "1.55.0")]
|
| 10 |
+
pub use core::num::IntErrorKind;
|
| 11 |
+
#[stable(feature = "generic_nonzero", since = "1.79.0")]
|
| 12 |
+
pub use core::num::NonZero;
|
| 13 |
+
#[stable(feature = "saturating_int_impl", since = "1.74.0")]
|
| 14 |
+
pub use core::num::Saturating;
|
| 15 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 16 |
+
pub use core::num::Wrapping;
|
| 17 |
+
#[unstable(
|
| 18 |
+
feature = "nonzero_internals",
|
| 19 |
+
reason = "implementation detail which may disappear or be replaced at any time",
|
| 20 |
+
issue = "none"
|
| 21 |
+
)]
|
| 22 |
+
pub use core::num::ZeroablePrimitive;
|
| 23 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 24 |
+
pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError};
|
| 25 |
+
#[stable(feature = "signed_nonzero", since = "1.34.0")]
|
| 26 |
+
pub use core::num::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize};
|
| 27 |
+
#[stable(feature = "nonzero", since = "1.28.0")]
|
| 28 |
+
pub use core::num::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize};
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/os/mod.rs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! OS-specific functionality.
|
| 2 |
+
|
| 3 |
+
#![stable(feature = "os", since = "1.0.0")]
|
| 4 |
+
#![allow(missing_docs, nonstandard_style, missing_debug_implementations)]
|
| 5 |
+
#![allow(unsafe_op_in_unsafe_fn)]
|
| 6 |
+
|
| 7 |
+
pub mod raw;
|
| 8 |
+
|
| 9 |
+
// The code below could be written clearer using `cfg_if!`. However, the items below are
|
| 10 |
+
// publicly exported by `std` and external tools can have trouble analysing them because of the use
|
| 11 |
+
// of a macro that is not vendored by Rust and included in the toolchain.
|
| 12 |
+
// See https://github.com/rust-analyzer/rust-analyzer/issues/6038.
|
| 13 |
+
|
| 14 |
+
// On certain platforms right now the "main modules" modules that are
|
| 15 |
+
// documented don't compile (missing things in `libc` which is empty),
|
| 16 |
+
// so just omit them with an empty module and add the "unstable" attribute.
|
| 17 |
+
|
| 18 |
+
// darwin, unix, linux, wasi and windows are handled a bit differently.
|
| 19 |
+
#[cfg(all(
|
| 20 |
+
doc,
|
| 21 |
+
any(
|
| 22 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 23 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 24 |
+
)
|
| 25 |
+
))]
|
| 26 |
+
#[unstable(issue = "none", feature = "std_internals")]
|
| 27 |
+
pub mod darwin {}
|
| 28 |
+
#[cfg(all(
|
| 29 |
+
doc,
|
| 30 |
+
any(
|
| 31 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 32 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 33 |
+
)
|
| 34 |
+
))]
|
| 35 |
+
#[unstable(issue = "none", feature = "std_internals")]
|
| 36 |
+
pub mod unix {}
|
| 37 |
+
#[cfg(all(
|
| 38 |
+
doc,
|
| 39 |
+
any(
|
| 40 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 41 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 42 |
+
)
|
| 43 |
+
))]
|
| 44 |
+
#[unstable(issue = "none", feature = "std_internals")]
|
| 45 |
+
pub mod linux {}
|
| 46 |
+
#[cfg(all(
|
| 47 |
+
doc,
|
| 48 |
+
any(
|
| 49 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 50 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 51 |
+
)
|
| 52 |
+
))]
|
| 53 |
+
#[unstable(issue = "none", feature = "std_internals")]
|
| 54 |
+
pub mod wasi {}
|
| 55 |
+
#[cfg(all(
|
| 56 |
+
doc,
|
| 57 |
+
any(
|
| 58 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 59 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 60 |
+
)
|
| 61 |
+
))]
|
| 62 |
+
#[unstable(issue = "none", feature = "std_internals")]
|
| 63 |
+
pub mod windows {}
|
| 64 |
+
|
| 65 |
+
// darwin
|
| 66 |
+
#[cfg(not(all(
|
| 67 |
+
doc,
|
| 68 |
+
any(
|
| 69 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 70 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 71 |
+
)
|
| 72 |
+
)))]
|
| 73 |
+
#[cfg(any(target_vendor = "apple", doc))]
|
| 74 |
+
pub mod darwin;
|
| 75 |
+
|
| 76 |
+
// unix
|
| 77 |
+
#[cfg(not(all(
|
| 78 |
+
doc,
|
| 79 |
+
any(
|
| 80 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 81 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 82 |
+
)
|
| 83 |
+
)))]
|
| 84 |
+
#[cfg(all(not(target_os = "hermit"), any(unix, doc)))]
|
| 85 |
+
pub mod unix;
|
| 86 |
+
|
| 87 |
+
// linux
|
| 88 |
+
#[cfg(not(all(
|
| 89 |
+
doc,
|
| 90 |
+
any(
|
| 91 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 92 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 93 |
+
)
|
| 94 |
+
)))]
|
| 95 |
+
#[cfg(any(target_os = "linux", doc))]
|
| 96 |
+
pub mod linux;
|
| 97 |
+
|
| 98 |
+
// wasi
|
| 99 |
+
#[cfg(not(all(
|
| 100 |
+
doc,
|
| 101 |
+
any(
|
| 102 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 103 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 104 |
+
)
|
| 105 |
+
)))]
|
| 106 |
+
#[cfg(any(target_os = "wasi", any(target_env = "p1", target_env = "p2"), doc))]
|
| 107 |
+
pub mod wasi;
|
| 108 |
+
|
| 109 |
+
#[cfg(any(all(target_os = "wasi", target_env = "p2"), doc))]
|
| 110 |
+
pub mod wasip2;
|
| 111 |
+
|
| 112 |
+
// windows
|
| 113 |
+
#[cfg(not(all(
|
| 114 |
+
doc,
|
| 115 |
+
any(
|
| 116 |
+
all(target_arch = "wasm32", not(target_os = "wasi")),
|
| 117 |
+
all(target_vendor = "fortanix", target_env = "sgx")
|
| 118 |
+
)
|
| 119 |
+
)))]
|
| 120 |
+
#[cfg(any(windows, doc))]
|
| 121 |
+
pub mod windows;
|
| 122 |
+
|
| 123 |
+
// Others.
|
| 124 |
+
#[cfg(target_os = "aix")]
|
| 125 |
+
pub mod aix;
|
| 126 |
+
#[cfg(target_os = "android")]
|
| 127 |
+
pub mod android;
|
| 128 |
+
#[cfg(target_os = "cygwin")]
|
| 129 |
+
pub mod cygwin;
|
| 130 |
+
#[cfg(target_os = "dragonfly")]
|
| 131 |
+
pub mod dragonfly;
|
| 132 |
+
#[cfg(target_os = "emscripten")]
|
| 133 |
+
pub mod emscripten;
|
| 134 |
+
#[cfg(target_os = "espidf")]
|
| 135 |
+
pub mod espidf;
|
| 136 |
+
#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))]
|
| 137 |
+
pub mod fortanix_sgx;
|
| 138 |
+
#[cfg(target_os = "freebsd")]
|
| 139 |
+
pub mod freebsd;
|
| 140 |
+
#[cfg(target_os = "fuchsia")]
|
| 141 |
+
pub mod fuchsia;
|
| 142 |
+
#[cfg(target_os = "haiku")]
|
| 143 |
+
pub mod haiku;
|
| 144 |
+
#[cfg(target_os = "hermit")]
|
| 145 |
+
pub mod hermit;
|
| 146 |
+
#[cfg(target_os = "horizon")]
|
| 147 |
+
pub mod horizon;
|
| 148 |
+
#[cfg(target_os = "hurd")]
|
| 149 |
+
pub mod hurd;
|
| 150 |
+
#[cfg(target_os = "illumos")]
|
| 151 |
+
pub mod illumos;
|
| 152 |
+
#[cfg(target_os = "ios")]
|
| 153 |
+
pub mod ios;
|
| 154 |
+
#[cfg(target_os = "l4re")]
|
| 155 |
+
pub mod l4re;
|
| 156 |
+
#[cfg(target_os = "macos")]
|
| 157 |
+
pub mod macos;
|
| 158 |
+
#[cfg(target_os = "motor")]
|
| 159 |
+
pub mod motor;
|
| 160 |
+
#[cfg(target_os = "netbsd")]
|
| 161 |
+
pub mod netbsd;
|
| 162 |
+
#[cfg(target_os = "nto")]
|
| 163 |
+
pub mod nto;
|
| 164 |
+
#[cfg(target_os = "nuttx")]
|
| 165 |
+
pub mod nuttx;
|
| 166 |
+
#[cfg(target_os = "openbsd")]
|
| 167 |
+
pub mod openbsd;
|
| 168 |
+
#[cfg(target_os = "redox")]
|
| 169 |
+
pub mod redox;
|
| 170 |
+
#[cfg(target_os = "rtems")]
|
| 171 |
+
pub mod rtems;
|
| 172 |
+
#[cfg(target_os = "solaris")]
|
| 173 |
+
pub mod solaris;
|
| 174 |
+
#[cfg(target_os = "solid_asp3")]
|
| 175 |
+
pub mod solid;
|
| 176 |
+
#[cfg(target_os = "trusty")]
|
| 177 |
+
pub mod trusty;
|
| 178 |
+
#[cfg(target_os = "uefi")]
|
| 179 |
+
pub mod uefi;
|
| 180 |
+
#[cfg(target_os = "vita")]
|
| 181 |
+
pub mod vita;
|
| 182 |
+
#[cfg(target_os = "vxworks")]
|
| 183 |
+
pub mod vxworks;
|
| 184 |
+
#[cfg(target_os = "xous")]
|
| 185 |
+
pub mod xous;
|
| 186 |
+
|
| 187 |
+
#[cfg(any(
|
| 188 |
+
unix,
|
| 189 |
+
target_os = "hermit",
|
| 190 |
+
target_os = "trusty",
|
| 191 |
+
target_os = "wasi",
|
| 192 |
+
target_os = "motor",
|
| 193 |
+
doc
|
| 194 |
+
))]
|
| 195 |
+
pub mod fd;
|
| 196 |
+
|
| 197 |
+
#[cfg(any(target_os = "linux", target_os = "android", target_os = "cygwin", doc))]
|
| 198 |
+
mod net;
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/prelude/mod.rs
ADDED
|
@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! # The Rust Prelude
|
| 2 |
+
//!
|
| 3 |
+
//! Rust comes with a variety of things in its standard library. However, if
|
| 4 |
+
//! you had to manually import every single thing that you used, it would be
|
| 5 |
+
//! very verbose. But importing a lot of things that a program never uses isn't
|
| 6 |
+
//! good either. A balance needs to be struck.
|
| 7 |
+
//!
|
| 8 |
+
//! The *prelude* is the list of things that Rust automatically imports into
|
| 9 |
+
//! every Rust program. It's kept as small as possible, and is focused on
|
| 10 |
+
//! things, particularly traits, which are used in almost every single Rust
|
| 11 |
+
//! program.
|
| 12 |
+
//!
|
| 13 |
+
//! # Other preludes
|
| 14 |
+
//!
|
| 15 |
+
//! Preludes can be seen as a pattern to make using multiple types more
|
| 16 |
+
//! convenient. As such, you'll find other preludes in the standard library,
|
| 17 |
+
//! such as [`std::io::prelude`]. Various libraries in the Rust ecosystem may
|
| 18 |
+
//! also define their own preludes.
|
| 19 |
+
//!
|
| 20 |
+
//! [`std::io::prelude`]: crate::io::prelude
|
| 21 |
+
//!
|
| 22 |
+
//! The difference between 'the prelude' and these other preludes is that they
|
| 23 |
+
//! are not automatically `use`'d, and must be imported manually. This is still
|
| 24 |
+
//! easier than importing all of their constituent components.
|
| 25 |
+
//!
|
| 26 |
+
//! # Prelude contents
|
| 27 |
+
//!
|
| 28 |
+
//! The items included in the prelude depend on the edition of the crate.
|
| 29 |
+
//! The first version of the prelude is used in Rust 2015 and Rust 2018,
|
| 30 |
+
//! and lives in [`std::prelude::v1`].
|
| 31 |
+
//! [`std::prelude::rust_2015`] and [`std::prelude::rust_2018`] re-export this prelude.
|
| 32 |
+
//! It re-exports the following:
|
| 33 |
+
//!
|
| 34 |
+
//! * <code>[std::marker]::{[Copy], [Send], [Sized], [Sync], [Unpin]}</code>,
|
| 35 |
+
//! marker traits that indicate fundamental properties of types.
|
| 36 |
+
//! * <code>[std::ops]::{[Fn], [FnMut], [FnOnce]}</code>, and their analogous
|
| 37 |
+
//! async traits, <code>[std::ops]::{[AsyncFn], [AsyncFnMut], [AsyncFnOnce]}</code>.
|
| 38 |
+
//! * <code>[std::ops]::[Drop]</code>, for implementing destructors.
|
| 39 |
+
//! * <code>[std::mem]::[drop]</code>, a convenience function for explicitly
|
| 40 |
+
//! dropping a value.
|
| 41 |
+
//! * <code>[std::mem]::{[size_of], [size_of_val]}</code>, to get the size of
|
| 42 |
+
//! a type or value.
|
| 43 |
+
//! * <code>[std::mem]::{[align_of], [align_of_val]}</code>, to get the
|
| 44 |
+
//! alignment of a type or value.
|
| 45 |
+
//! * <code>[std::boxed]::[Box]</code>, a way to allocate values on the heap.
|
| 46 |
+
//! * <code>[std::borrow]::[ToOwned]</code>, the conversion trait that defines
|
| 47 |
+
//! [`to_owned`], the generic method for creating an owned type from a
|
| 48 |
+
//! borrowed type.
|
| 49 |
+
//! * <code>[std::clone]::[Clone]</code>, the ubiquitous trait that defines
|
| 50 |
+
//! [`clone`][Clone::clone], the method for producing a copy of a value.
|
| 51 |
+
//! * <code>[std::cmp]::{[PartialEq], [PartialOrd], [Eq], [Ord]}</code>, the
|
| 52 |
+
//! comparison traits, which implement the comparison operators and are often
|
| 53 |
+
//! seen in trait bounds.
|
| 54 |
+
//! * <code>[std::convert]::{[AsRef], [AsMut], [Into], [From]}</code>, generic
|
| 55 |
+
//! conversions, used by savvy API authors to create overloaded methods.
|
| 56 |
+
//! * <code>[std::default]::[Default]</code>, types that have default values.
|
| 57 |
+
//! * <code>[std::iter]::{[Iterator], [Extend], [IntoIterator], [DoubleEndedIterator],
|
| 58 |
+
//! [ExactSizeIterator]}</code>, iterators of various kinds.
|
| 59 |
+
//! * Most of the standard macros.
|
| 60 |
+
//! * <code>[std::option]::[Option]::{[self][Option], [Some], [None]}</code>, a
|
| 61 |
+
//! type which expresses the presence or absence of a value. This type is so
|
| 62 |
+
//! commonly used, its variants are also exported.
|
| 63 |
+
//! * <code>[std::result]::[Result]::{[self][Result], [Ok], [Err]}</code>, a type
|
| 64 |
+
//! for functions that may succeed or fail. Like [`Option`], its variants are
|
| 65 |
+
//! exported as well.
|
| 66 |
+
//! * <code>[std::string]::{[String], [ToString]}</code>, heap-allocated strings.
|
| 67 |
+
//! * <code>[std::vec]::[Vec]</code>, a growable, heap-allocated vector.
|
| 68 |
+
//!
|
| 69 |
+
//! The prelude used in Rust 2021, [`std::prelude::rust_2021`], includes all of the above,
|
| 70 |
+
//! and in addition re-exports:
|
| 71 |
+
//!
|
| 72 |
+
//! * <code>[std::convert]::{[TryFrom], [TryInto]}</code>.
|
| 73 |
+
//! * <code>[std::iter]::[FromIterator]</code>.
|
| 74 |
+
//!
|
| 75 |
+
//! The prelude used in Rust 2024, [`std::prelude::rust_2024`], includes all of the above,
|
| 76 |
+
//! and in addition re-exports:
|
| 77 |
+
//!
|
| 78 |
+
//! * <code>[std::future]::{[Future], [IntoFuture]}</code>.
|
| 79 |
+
//!
|
| 80 |
+
//! [std::borrow]: crate::borrow
|
| 81 |
+
//! [std::boxed]: crate::boxed
|
| 82 |
+
//! [std::clone]: crate::clone
|
| 83 |
+
//! [std::cmp]: crate::cmp
|
| 84 |
+
//! [std::convert]: crate::convert
|
| 85 |
+
//! [std::default]: crate::default
|
| 86 |
+
//! [std::future]: crate::future
|
| 87 |
+
//! [std::iter]: crate::iter
|
| 88 |
+
//! [std::marker]: crate::marker
|
| 89 |
+
//! [std::mem]: crate::mem
|
| 90 |
+
//! [std::ops]: crate::ops
|
| 91 |
+
//! [std::option]: crate::option
|
| 92 |
+
//! [`std::prelude::v1`]: v1
|
| 93 |
+
//! [`std::prelude::rust_2015`]: rust_2015
|
| 94 |
+
//! [`std::prelude::rust_2018`]: rust_2018
|
| 95 |
+
//! [`std::prelude::rust_2021`]: rust_2021
|
| 96 |
+
//! [`std::prelude::rust_2024`]: rust_2024
|
| 97 |
+
//! [std::result]: crate::result
|
| 98 |
+
//! [std::slice]: crate::slice
|
| 99 |
+
//! [std::string]: crate::string
|
| 100 |
+
//! [std::vec]: mod@crate::vec
|
| 101 |
+
//! [`to_owned`]: crate::borrow::ToOwned::to_owned
|
| 102 |
+
//! [book-closures]: ../../book/ch13-01-closures.html
|
| 103 |
+
//! [book-dtor]: ../../book/ch15-03-drop.html
|
| 104 |
+
//! [book-enums]: ../../book/ch06-01-defining-an-enum.html
|
| 105 |
+
//! [book-iter]: ../../book/ch13-02-iterators.html
|
| 106 |
+
//! [Future]: crate::future::Future
|
| 107 |
+
//! [IntoFuture]: crate::future::IntoFuture
|
| 108 |
+
|
| 109 |
+
// No formatting: this file is nothing but re-exports, and their order is worth preserving.
|
| 110 |
+
#![cfg_attr(rustfmt, rustfmt::skip)]
|
| 111 |
+
|
| 112 |
+
#![stable(feature = "rust1", since = "1.0.0")]
|
| 113 |
+
|
| 114 |
+
pub mod v1;
|
| 115 |
+
|
| 116 |
+
/// The 2015 version of the prelude of The Rust Standard Library.
|
| 117 |
+
///
|
| 118 |
+
/// See the [module-level documentation](self) for more.
|
| 119 |
+
#[stable(feature = "prelude_2015", since = "1.55.0")]
|
| 120 |
+
pub mod rust_2015 {
|
| 121 |
+
#[stable(feature = "prelude_2015", since = "1.55.0")]
|
| 122 |
+
#[doc(no_inline)]
|
| 123 |
+
pub use super::v1::*;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
/// The 2018 version of the prelude of The Rust Standard Library.
|
| 127 |
+
///
|
| 128 |
+
/// See the [module-level documentation](self) for more.
|
| 129 |
+
#[stable(feature = "prelude_2018", since = "1.55.0")]
|
| 130 |
+
pub mod rust_2018 {
|
| 131 |
+
#[stable(feature = "prelude_2018", since = "1.55.0")]
|
| 132 |
+
#[doc(no_inline)]
|
| 133 |
+
pub use super::v1::*;
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
/// The 2021 version of the prelude of The Rust Standard Library.
|
| 137 |
+
///
|
| 138 |
+
/// See the [module-level documentation](self) for more.
|
| 139 |
+
#[stable(feature = "prelude_2021", since = "1.55.0")]
|
| 140 |
+
pub mod rust_2021 {
|
| 141 |
+
#[stable(feature = "prelude_2021", since = "1.55.0")]
|
| 142 |
+
#[doc(no_inline)]
|
| 143 |
+
pub use super::v1::*;
|
| 144 |
+
|
| 145 |
+
#[stable(feature = "prelude_2021", since = "1.55.0")]
|
| 146 |
+
#[doc(no_inline)]
|
| 147 |
+
pub use core::prelude::rust_2021::*;
|
| 148 |
+
|
| 149 |
+
// There are two different panic macros, one in `core` and one in `std`. They are slightly
|
| 150 |
+
// different. For `std` we explicitly want the one defined in `std`.
|
| 151 |
+
#[stable(feature = "prelude_2021", since = "1.55.0")]
|
| 152 |
+
pub use super::v1::panic;
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
/// The 2024 version of the prelude of The Rust Standard Library.
|
| 156 |
+
///
|
| 157 |
+
/// See the [module-level documentation](self) for more.
|
| 158 |
+
#[stable(feature = "prelude_2024", since = "1.85.0")]
|
| 159 |
+
pub mod rust_2024 {
|
| 160 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 161 |
+
#[doc(no_inline)]
|
| 162 |
+
pub use super::v1::*;
|
| 163 |
+
|
| 164 |
+
#[stable(feature = "prelude_2024", since = "1.85.0")]
|
| 165 |
+
#[doc(no_inline)]
|
| 166 |
+
pub use core::prelude::rust_2024::*;
|
| 167 |
+
|
| 168 |
+
// There are two different panic macros, one in `core` and one in `std`. They are slightly
|
| 169 |
+
// different. For `std` we explicitly want the one defined in `std`.
|
| 170 |
+
#[stable(feature = "prelude_2024", since = "1.85.0")]
|
| 171 |
+
pub use super::v1::panic;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
/// The Future version of the prelude of The Rust Standard Library.
|
| 175 |
+
///
|
| 176 |
+
/// See the [module-level documentation](self) for more.
|
| 177 |
+
#[doc(hidden)]
|
| 178 |
+
#[unstable(feature = "prelude_future", issue = "none")]
|
| 179 |
+
pub mod rust_future {
|
| 180 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 181 |
+
#[doc(no_inline)]
|
| 182 |
+
pub use super::v1::*;
|
| 183 |
+
|
| 184 |
+
#[unstable(feature = "prelude_next", issue = "none")]
|
| 185 |
+
#[doc(no_inline)]
|
| 186 |
+
pub use core::prelude::rust_future::*;
|
| 187 |
+
|
| 188 |
+
// There are two different panic macros, one in `core` and one in `std`. They are slightly
|
| 189 |
+
// different. For `std` we explicitly want the one defined in `std`.
|
| 190 |
+
#[unstable(feature = "prelude_next", issue = "none")]
|
| 191 |
+
pub use super::v1::panic;
|
| 192 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/prelude/v1.rs
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! The first version of the prelude of The Rust Standard Library.
|
| 2 |
+
//!
|
| 3 |
+
//! See the [module-level documentation](super) for more.
|
| 4 |
+
|
| 5 |
+
#![stable(feature = "rust1", since = "1.0.0")]
|
| 6 |
+
|
| 7 |
+
// No formatting: this file is nothing but re-exports, and their order is worth preserving.
|
| 8 |
+
#![cfg_attr(rustfmt, rustfmt::skip)]
|
| 9 |
+
|
| 10 |
+
// Re-exported core operators
|
| 11 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 12 |
+
#[doc(no_inline)]
|
| 13 |
+
pub use crate::marker::{Send, Sized, Sync, Unpin};
|
| 14 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 15 |
+
#[doc(no_inline)]
|
| 16 |
+
pub use crate::ops::{Drop, Fn, FnMut, FnOnce};
|
| 17 |
+
#[stable(feature = "async_closure", since = "1.85.0")]
|
| 18 |
+
#[doc(no_inline)]
|
| 19 |
+
pub use crate::ops::{AsyncFn, AsyncFnMut, AsyncFnOnce};
|
| 20 |
+
|
| 21 |
+
// Re-exported functions
|
| 22 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 23 |
+
#[doc(no_inline)]
|
| 24 |
+
pub use crate::mem::drop;
|
| 25 |
+
#[stable(feature = "size_of_prelude", since = "1.80.0")]
|
| 26 |
+
#[doc(no_inline)]
|
| 27 |
+
pub use crate::mem::{align_of, align_of_val, size_of, size_of_val};
|
| 28 |
+
|
| 29 |
+
// Re-exported types and traits
|
| 30 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 31 |
+
#[doc(no_inline)]
|
| 32 |
+
pub use crate::convert::{AsMut, AsRef, From, Into};
|
| 33 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 34 |
+
#[doc(no_inline)]
|
| 35 |
+
pub use crate::iter::{DoubleEndedIterator, ExactSizeIterator};
|
| 36 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 37 |
+
#[doc(no_inline)]
|
| 38 |
+
pub use crate::iter::{Extend, IntoIterator, Iterator};
|
| 39 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 40 |
+
#[doc(no_inline)]
|
| 41 |
+
pub use crate::option::Option::{self, None, Some};
|
| 42 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 43 |
+
#[doc(no_inline)]
|
| 44 |
+
pub use crate::result::Result::{self, Err, Ok};
|
| 45 |
+
|
| 46 |
+
// Re-exported built-in macros and traits
|
| 47 |
+
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
|
| 48 |
+
#[doc(no_inline)]
|
| 49 |
+
#[expect(deprecated)]
|
| 50 |
+
pub use core::prelude::v1::{
|
| 51 |
+
assert, assert_eq, assert_ne, cfg, column, compile_error, concat, debug_assert, debug_assert_eq,
|
| 52 |
+
debug_assert_ne, env, file, format_args, include, include_bytes, include_str, line, matches,
|
| 53 |
+
module_path, option_env, stringify, todo, r#try, unimplemented, unreachable, write,
|
| 54 |
+
writeln, Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd,
|
| 55 |
+
};
|
| 56 |
+
|
| 57 |
+
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
|
| 58 |
+
#[doc(no_inline)]
|
| 59 |
+
pub use crate::{
|
| 60 |
+
dbg, eprint, eprintln, format, is_x86_feature_detected, print, println, thread_local
|
| 61 |
+
};
|
| 62 |
+
|
| 63 |
+
// These macros need special handling, so that we don't export them *and* the modules of the same
|
| 64 |
+
// name. We only want the macros in the prelude so we shadow the original modules with private
|
| 65 |
+
// modules with the same names.
|
| 66 |
+
mod ambiguous_macros_only {
|
| 67 |
+
#[expect(hidden_glob_reexports)]
|
| 68 |
+
mod vec {}
|
| 69 |
+
#[expect(hidden_glob_reexports)]
|
| 70 |
+
mod panic {}
|
| 71 |
+
// Building std without the expect exported_private_dependencies will create warnings, but then
|
| 72 |
+
// clippy claims its a useless_attribute. So silence both.
|
| 73 |
+
#[expect(clippy::useless_attribute)]
|
| 74 |
+
#[expect(exported_private_dependencies)]
|
| 75 |
+
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
|
| 76 |
+
pub use crate::*;
|
| 77 |
+
}
|
| 78 |
+
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
|
| 79 |
+
#[doc(no_inline)]
|
| 80 |
+
pub use self::ambiguous_macros_only::{vec, panic};
|
| 81 |
+
|
| 82 |
+
#[stable(feature = "cfg_select", since = "1.95.0")]
|
| 83 |
+
#[doc(no_inline)]
|
| 84 |
+
pub use core::prelude::v1::cfg_select;
|
| 85 |
+
|
| 86 |
+
#[unstable(
|
| 87 |
+
feature = "concat_bytes",
|
| 88 |
+
issue = "87555",
|
| 89 |
+
reason = "`concat_bytes` is not stable enough for use and is subject to change"
|
| 90 |
+
)]
|
| 91 |
+
#[doc(no_inline)]
|
| 92 |
+
pub use core::prelude::v1::concat_bytes;
|
| 93 |
+
|
| 94 |
+
#[unstable(feature = "const_format_args", issue = "none")]
|
| 95 |
+
#[doc(no_inline)]
|
| 96 |
+
pub use core::prelude::v1::const_format_args;
|
| 97 |
+
|
| 98 |
+
#[unstable(
|
| 99 |
+
feature = "log_syntax",
|
| 100 |
+
issue = "29598",
|
| 101 |
+
reason = "`log_syntax!` is not stable enough for use and is subject to change"
|
| 102 |
+
)]
|
| 103 |
+
#[doc(no_inline)]
|
| 104 |
+
pub use core::prelude::v1::log_syntax;
|
| 105 |
+
|
| 106 |
+
#[unstable(
|
| 107 |
+
feature = "trace_macros",
|
| 108 |
+
issue = "29598",
|
| 109 |
+
reason = "`trace_macros` is not stable enough for use and is subject to change"
|
| 110 |
+
)]
|
| 111 |
+
#[doc(no_inline)]
|
| 112 |
+
pub use core::prelude::v1::trace_macros;
|
| 113 |
+
|
| 114 |
+
// Do not `doc(no_inline)` so that they become doc items on their own
|
| 115 |
+
// (no public module for them to be re-exported from).
|
| 116 |
+
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
|
| 117 |
+
pub use core::prelude::v1::{
|
| 118 |
+
alloc_error_handler, bench, derive, global_allocator, test, test_case,
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
#[unstable(feature = "derive_const", issue = "118304")]
|
| 122 |
+
pub use core::prelude::v1::derive_const;
|
| 123 |
+
|
| 124 |
+
// Do not `doc(no_inline)` either.
|
| 125 |
+
#[unstable(
|
| 126 |
+
feature = "cfg_accessible",
|
| 127 |
+
issue = "64797",
|
| 128 |
+
reason = "`cfg_accessible` is not fully implemented"
|
| 129 |
+
)]
|
| 130 |
+
pub use core::prelude::v1::cfg_accessible;
|
| 131 |
+
|
| 132 |
+
// Do not `doc(no_inline)` either.
|
| 133 |
+
#[unstable(
|
| 134 |
+
feature = "cfg_eval",
|
| 135 |
+
issue = "82679",
|
| 136 |
+
reason = "`cfg_eval` is a recently implemented feature"
|
| 137 |
+
)]
|
| 138 |
+
pub use core::prelude::v1::cfg_eval;
|
| 139 |
+
|
| 140 |
+
// Do not `doc(no_inline)` either.
|
| 141 |
+
#[unstable(
|
| 142 |
+
feature = "type_ascription",
|
| 143 |
+
issue = "23416",
|
| 144 |
+
reason = "placeholder syntax for type ascription"
|
| 145 |
+
)]
|
| 146 |
+
pub use core::prelude::v1::type_ascribe;
|
| 147 |
+
|
| 148 |
+
// Do not `doc(no_inline)` either.
|
| 149 |
+
#[unstable(
|
| 150 |
+
feature = "deref_patterns",
|
| 151 |
+
issue = "87121",
|
| 152 |
+
reason = "placeholder syntax for deref patterns"
|
| 153 |
+
)]
|
| 154 |
+
pub use core::prelude::v1::deref;
|
| 155 |
+
|
| 156 |
+
// Do not `doc(no_inline)` either.
|
| 157 |
+
#[unstable(
|
| 158 |
+
feature = "type_alias_impl_trait",
|
| 159 |
+
issue = "63063",
|
| 160 |
+
reason = "`type_alias_impl_trait` has open design concerns"
|
| 161 |
+
)]
|
| 162 |
+
pub use core::prelude::v1::define_opaque;
|
| 163 |
+
|
| 164 |
+
#[unstable(feature = "extern_item_impls", issue = "125418")]
|
| 165 |
+
pub use core::prelude::v1::{eii, unsafe_eii};
|
| 166 |
+
|
| 167 |
+
#[unstable(feature = "eii_internals", issue = "none")]
|
| 168 |
+
pub use core::prelude::v1::eii_declaration;
|
| 169 |
+
|
| 170 |
+
// The file so far is equivalent to core/src/prelude/v1.rs. It is duplicated
|
| 171 |
+
// rather than glob imported because we want docs to show these re-exports as
|
| 172 |
+
// pointing to within `std`.
|
| 173 |
+
// Below are the items from the alloc crate.
|
| 174 |
+
|
| 175 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 176 |
+
#[doc(no_inline)]
|
| 177 |
+
pub use crate::borrow::ToOwned;
|
| 178 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 179 |
+
#[doc(no_inline)]
|
| 180 |
+
pub use crate::boxed::Box;
|
| 181 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 182 |
+
#[doc(no_inline)]
|
| 183 |
+
pub use crate::string::{String, ToString};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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use super::{Command, Output, Stdio};
|
| 2 |
+
use crate::io::prelude::*;
|
| 3 |
+
use crate::io::{BorrowedBuf, ErrorKind};
|
| 4 |
+
use crate::mem::MaybeUninit;
|
| 5 |
+
use crate::str;
|
| 6 |
+
|
| 7 |
+
fn known_command() -> Command {
|
| 8 |
+
if cfg!(windows) {
|
| 9 |
+
Command::new("help")
|
| 10 |
+
} else if cfg!(all(target_vendor = "apple", not(target_os = "macos"))) {
|
| 11 |
+
// iOS/tvOS/watchOS/visionOS have a very limited set of commandline
|
| 12 |
+
// binaries available.
|
| 13 |
+
Command::new("log")
|
| 14 |
+
} else {
|
| 15 |
+
Command::new("echo")
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
#[cfg(target_os = "android")]
|
| 20 |
+
fn shell_cmd() -> Command {
|
| 21 |
+
Command::new("/system/bin/sh")
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
#[cfg(not(target_os = "android"))]
|
| 25 |
+
fn shell_cmd() -> Command {
|
| 26 |
+
Command::new("/bin/sh")
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
#[test]
|
| 30 |
+
#[cfg_attr(
|
| 31 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 32 |
+
ignore = "no shell available"
|
| 33 |
+
)]
|
| 34 |
+
fn smoke() {
|
| 35 |
+
let p = if cfg!(target_os = "windows") {
|
| 36 |
+
Command::new("cmd").args(&["/C", "exit 0"]).spawn()
|
| 37 |
+
} else {
|
| 38 |
+
shell_cmd().arg("-c").arg("true").spawn()
|
| 39 |
+
};
|
| 40 |
+
assert!(p.is_ok());
|
| 41 |
+
let mut p = p.unwrap();
|
| 42 |
+
assert!(p.wait().unwrap().success());
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
#[test]
|
| 46 |
+
#[cfg_attr(target_os = "android", ignore)]
|
| 47 |
+
fn smoke_failure() {
|
| 48 |
+
match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
|
| 49 |
+
Ok(..) => panic!(),
|
| 50 |
+
Err(..) => {}
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
#[test]
|
| 55 |
+
#[cfg_attr(
|
| 56 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 57 |
+
ignore = "no shell available"
|
| 58 |
+
)]
|
| 59 |
+
fn exit_reported_right() {
|
| 60 |
+
let p = if cfg!(target_os = "windows") {
|
| 61 |
+
Command::new("cmd").args(&["/C", "exit 1"]).spawn()
|
| 62 |
+
} else {
|
| 63 |
+
shell_cmd().arg("-c").arg("false").spawn()
|
| 64 |
+
};
|
| 65 |
+
assert!(p.is_ok());
|
| 66 |
+
let mut p = p.unwrap();
|
| 67 |
+
assert!(p.wait().unwrap().code() == Some(1));
|
| 68 |
+
drop(p.wait());
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
#[test]
|
| 72 |
+
#[cfg(unix)]
|
| 73 |
+
#[cfg_attr(
|
| 74 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 75 |
+
ignore = "no shell available"
|
| 76 |
+
)]
|
| 77 |
+
fn signal_reported_right() {
|
| 78 |
+
use crate::os::unix::process::ExitStatusExt;
|
| 79 |
+
|
| 80 |
+
let mut p = shell_cmd().arg("-c").arg("read a").stdin(Stdio::piped()).spawn().unwrap();
|
| 81 |
+
p.kill().unwrap();
|
| 82 |
+
match p.wait().unwrap().signal() {
|
| 83 |
+
Some(9) => {}
|
| 84 |
+
result => panic!("not terminated by signal 9 (instead, {result:?})"),
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
pub fn run_output(mut cmd: Command) -> String {
|
| 89 |
+
let p = cmd.spawn();
|
| 90 |
+
assert!(p.is_ok());
|
| 91 |
+
let mut p = p.unwrap();
|
| 92 |
+
assert!(p.stdout.is_some());
|
| 93 |
+
let mut ret = String::new();
|
| 94 |
+
p.stdout.as_mut().unwrap().read_to_string(&mut ret).unwrap();
|
| 95 |
+
assert!(p.wait().unwrap().success());
|
| 96 |
+
return ret;
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
#[test]
|
| 100 |
+
#[cfg_attr(
|
| 101 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 102 |
+
ignore = "no shell available"
|
| 103 |
+
)]
|
| 104 |
+
fn stdout_works() {
|
| 105 |
+
if cfg!(target_os = "windows") {
|
| 106 |
+
let mut cmd = Command::new("cmd");
|
| 107 |
+
cmd.args(&["/C", "echo foobar"]).stdout(Stdio::piped());
|
| 108 |
+
assert_eq!(run_output(cmd), "foobar\r\n");
|
| 109 |
+
} else {
|
| 110 |
+
let mut cmd = shell_cmd();
|
| 111 |
+
cmd.arg("-c").arg("echo foobar").stdout(Stdio::piped());
|
| 112 |
+
assert_eq!(run_output(cmd), "foobar\n");
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
#[test]
|
| 117 |
+
#[cfg_attr(windows, ignore)]
|
| 118 |
+
#[cfg_attr(
|
| 119 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 120 |
+
ignore = "no shell available"
|
| 121 |
+
)]
|
| 122 |
+
fn set_current_dir_works() {
|
| 123 |
+
// On many Unix platforms this will use the posix_spawn path.
|
| 124 |
+
let mut cmd = shell_cmd();
|
| 125 |
+
cmd.arg("-c").arg("pwd").current_dir("/").stdout(Stdio::piped());
|
| 126 |
+
assert_eq!(run_output(cmd), "/\n");
|
| 127 |
+
|
| 128 |
+
// Also test the fork/exec path by setting a pre_exec function.
|
| 129 |
+
#[cfg(unix)]
|
| 130 |
+
{
|
| 131 |
+
use crate::os::unix::process::CommandExt;
|
| 132 |
+
|
| 133 |
+
let mut cmd = shell_cmd();
|
| 134 |
+
cmd.arg("-c").arg("pwd").current_dir("/").stdout(Stdio::piped());
|
| 135 |
+
unsafe {
|
| 136 |
+
cmd.pre_exec(|| Ok(()));
|
| 137 |
+
}
|
| 138 |
+
assert_eq!(run_output(cmd), "/\n");
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
#[test]
|
| 143 |
+
#[cfg_attr(windows, ignore)]
|
| 144 |
+
#[cfg_attr(
|
| 145 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 146 |
+
ignore = "no shell available"
|
| 147 |
+
)]
|
| 148 |
+
fn stdin_works() {
|
| 149 |
+
let mut p = shell_cmd()
|
| 150 |
+
.arg("-c")
|
| 151 |
+
.arg("read line; echo $line")
|
| 152 |
+
.stdin(Stdio::piped())
|
| 153 |
+
.stdout(Stdio::piped())
|
| 154 |
+
.spawn()
|
| 155 |
+
.unwrap();
|
| 156 |
+
p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
|
| 157 |
+
drop(p.stdin.take());
|
| 158 |
+
let mut out = String::new();
|
| 159 |
+
p.stdout.as_mut().unwrap().read_to_string(&mut out).unwrap();
|
| 160 |
+
assert!(p.wait().unwrap().success());
|
| 161 |
+
assert_eq!(out, "foobar\n");
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
#[test]
|
| 165 |
+
#[cfg_attr(
|
| 166 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 167 |
+
ignore = "no shell available"
|
| 168 |
+
)]
|
| 169 |
+
fn child_stdout_read_buf() {
|
| 170 |
+
let mut cmd = if cfg!(target_os = "windows") {
|
| 171 |
+
let mut cmd = Command::new("cmd");
|
| 172 |
+
cmd.arg("/C").arg("echo abc");
|
| 173 |
+
cmd
|
| 174 |
+
} else {
|
| 175 |
+
let mut cmd = shell_cmd();
|
| 176 |
+
cmd.arg("-c").arg("echo abc");
|
| 177 |
+
cmd
|
| 178 |
+
};
|
| 179 |
+
cmd.stdin(Stdio::null());
|
| 180 |
+
cmd.stdout(Stdio::piped());
|
| 181 |
+
let child = cmd.spawn().unwrap();
|
| 182 |
+
|
| 183 |
+
let mut stdout = child.stdout.unwrap();
|
| 184 |
+
let mut buf: [MaybeUninit<u8>; 128] = [MaybeUninit::uninit(); 128];
|
| 185 |
+
let mut buf = BorrowedBuf::from(buf.as_mut_slice());
|
| 186 |
+
stdout.read_buf(buf.unfilled()).unwrap();
|
| 187 |
+
|
| 188 |
+
// ChildStdout::read_buf should omit buffer initialization.
|
| 189 |
+
if cfg!(target_os = "windows") {
|
| 190 |
+
assert_eq!(buf.filled(), b"abc\r\n");
|
| 191 |
+
assert_eq!(buf.init_len(), 5);
|
| 192 |
+
} else {
|
| 193 |
+
assert_eq!(buf.filled(), b"abc\n");
|
| 194 |
+
assert_eq!(buf.init_len(), 4);
|
| 195 |
+
};
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
#[test]
|
| 199 |
+
#[cfg_attr(
|
| 200 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 201 |
+
ignore = "no shell available"
|
| 202 |
+
)]
|
| 203 |
+
fn test_process_status() {
|
| 204 |
+
let mut status = if cfg!(target_os = "windows") {
|
| 205 |
+
Command::new("cmd").args(&["/C", "exit 1"]).status().unwrap()
|
| 206 |
+
} else {
|
| 207 |
+
shell_cmd().arg("-c").arg("false").status().unwrap()
|
| 208 |
+
};
|
| 209 |
+
assert!(status.code() == Some(1));
|
| 210 |
+
|
| 211 |
+
status = if cfg!(target_os = "windows") {
|
| 212 |
+
Command::new("cmd").args(&["/C", "exit 0"]).status().unwrap()
|
| 213 |
+
} else {
|
| 214 |
+
shell_cmd().arg("-c").arg("true").status().unwrap()
|
| 215 |
+
};
|
| 216 |
+
assert!(status.success());
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
#[test]
|
| 220 |
+
fn test_process_output_fail_to_start() {
|
| 221 |
+
match Command::new("/no-binary-by-this-name-should-exist").output() {
|
| 222 |
+
Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
|
| 223 |
+
Ok(..) => panic!(),
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
#[test]
|
| 228 |
+
#[cfg_attr(
|
| 229 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 230 |
+
ignore = "no shell available"
|
| 231 |
+
)]
|
| 232 |
+
fn test_process_output_output() {
|
| 233 |
+
let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
|
| 234 |
+
Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
|
| 235 |
+
} else {
|
| 236 |
+
shell_cmd().arg("-c").arg("echo hello").output().unwrap()
|
| 237 |
+
};
|
| 238 |
+
let output_str = str::from_utf8(&stdout).unwrap();
|
| 239 |
+
|
| 240 |
+
assert!(status.success());
|
| 241 |
+
assert_eq!(output_str.trim().to_string(), "hello");
|
| 242 |
+
assert_eq!(stderr, Vec::new());
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
#[test]
|
| 246 |
+
#[cfg_attr(
|
| 247 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 248 |
+
ignore = "no shell available"
|
| 249 |
+
)]
|
| 250 |
+
fn test_process_output_error() {
|
| 251 |
+
let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
|
| 252 |
+
Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
|
| 253 |
+
} else {
|
| 254 |
+
Command::new("mkdir").arg("./").output().unwrap()
|
| 255 |
+
};
|
| 256 |
+
|
| 257 |
+
assert!(status.code().is_some());
|
| 258 |
+
assert!(status.code() != Some(0));
|
| 259 |
+
assert_eq!(stdout, Vec::new());
|
| 260 |
+
assert!(!stderr.is_empty());
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
#[test]
|
| 264 |
+
#[cfg_attr(
|
| 265 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 266 |
+
ignore = "no shell available"
|
| 267 |
+
)]
|
| 268 |
+
fn test_finish_once() {
|
| 269 |
+
let mut prog = if cfg!(target_os = "windows") {
|
| 270 |
+
Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
|
| 271 |
+
} else {
|
| 272 |
+
shell_cmd().arg("-c").arg("false").spawn().unwrap()
|
| 273 |
+
};
|
| 274 |
+
assert!(prog.wait().unwrap().code() == Some(1));
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
#[test]
|
| 278 |
+
#[cfg_attr(
|
| 279 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 280 |
+
ignore = "no shell available"
|
| 281 |
+
)]
|
| 282 |
+
fn test_finish_twice() {
|
| 283 |
+
let mut prog = if cfg!(target_os = "windows") {
|
| 284 |
+
Command::new("cmd").args(&["/C", "exit 1"]).spawn().unwrap()
|
| 285 |
+
} else {
|
| 286 |
+
shell_cmd().arg("-c").arg("false").spawn().unwrap()
|
| 287 |
+
};
|
| 288 |
+
assert!(prog.wait().unwrap().code() == Some(1));
|
| 289 |
+
assert!(prog.wait().unwrap().code() == Some(1));
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
#[test]
|
| 293 |
+
#[cfg_attr(
|
| 294 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 295 |
+
ignore = "no shell available"
|
| 296 |
+
)]
|
| 297 |
+
fn test_wait_with_output_once() {
|
| 298 |
+
let prog = if cfg!(target_os = "windows") {
|
| 299 |
+
Command::new("cmd").args(&["/C", "echo hello"]).stdout(Stdio::piped()).spawn().unwrap()
|
| 300 |
+
} else {
|
| 301 |
+
shell_cmd().arg("-c").arg("echo hello").stdout(Stdio::piped()).spawn().unwrap()
|
| 302 |
+
};
|
| 303 |
+
|
| 304 |
+
let Output { status, stdout, stderr } = prog.wait_with_output().unwrap();
|
| 305 |
+
let output_str = str::from_utf8(&stdout).unwrap();
|
| 306 |
+
|
| 307 |
+
assert!(status.success());
|
| 308 |
+
assert_eq!(output_str.trim().to_string(), "hello");
|
| 309 |
+
assert_eq!(stderr, Vec::new());
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
#[cfg(all(unix, not(target_os = "android")))]
|
| 313 |
+
pub fn env_cmd() -> Command {
|
| 314 |
+
Command::new("env")
|
| 315 |
+
}
|
| 316 |
+
#[cfg(target_os = "android")]
|
| 317 |
+
pub fn env_cmd() -> Command {
|
| 318 |
+
let mut cmd = Command::new("/system/bin/sh");
|
| 319 |
+
cmd.arg("-c").arg("set");
|
| 320 |
+
cmd
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
#[cfg(windows)]
|
| 324 |
+
pub fn env_cmd() -> Command {
|
| 325 |
+
let mut cmd = Command::new("cmd");
|
| 326 |
+
cmd.arg("/c").arg("set");
|
| 327 |
+
cmd
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
#[test]
|
| 331 |
+
#[cfg_attr(
|
| 332 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 333 |
+
ignore = "no shell available"
|
| 334 |
+
)]
|
| 335 |
+
fn test_override_env() {
|
| 336 |
+
use crate::env;
|
| 337 |
+
|
| 338 |
+
// In some build environments (such as chrooted Nix builds), `env` can
|
| 339 |
+
// only be found in the explicitly-provided PATH env variable, not in
|
| 340 |
+
// default places such as /bin or /usr/bin. So we need to pass through
|
| 341 |
+
// PATH to our sub-process.
|
| 342 |
+
let mut cmd = env_cmd();
|
| 343 |
+
cmd.env_clear().env("RUN_TEST_NEW_ENV", "123");
|
| 344 |
+
if let Some(p) = env::var_os("PATH") {
|
| 345 |
+
cmd.env("PATH", &p);
|
| 346 |
+
}
|
| 347 |
+
let result = cmd.output().unwrap();
|
| 348 |
+
let output = String::from_utf8_lossy(&result.stdout).to_string();
|
| 349 |
+
|
| 350 |
+
assert!(
|
| 351 |
+
output.contains("RUN_TEST_NEW_ENV=123"),
|
| 352 |
+
"didn't find RUN_TEST_NEW_ENV inside of:\n\n{output}",
|
| 353 |
+
);
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
#[test]
|
| 357 |
+
#[cfg_attr(
|
| 358 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 359 |
+
ignore = "no shell available"
|
| 360 |
+
)]
|
| 361 |
+
fn test_add_to_env() {
|
| 362 |
+
let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
|
| 363 |
+
let output = String::from_utf8_lossy(&result.stdout).to_string();
|
| 364 |
+
|
| 365 |
+
assert!(
|
| 366 |
+
output.contains("RUN_TEST_NEW_ENV=123"),
|
| 367 |
+
"didn't find RUN_TEST_NEW_ENV inside of:\n\n{output}"
|
| 368 |
+
);
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
#[test]
|
| 372 |
+
#[cfg_attr(
|
| 373 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 374 |
+
ignore = "no shell available"
|
| 375 |
+
)]
|
| 376 |
+
fn test_capture_env_at_spawn() {
|
| 377 |
+
use crate::env;
|
| 378 |
+
|
| 379 |
+
let mut cmd = env_cmd();
|
| 380 |
+
cmd.env("RUN_TEST_NEW_ENV1", "123");
|
| 381 |
+
|
| 382 |
+
// This variable will not be present if the environment has already
|
| 383 |
+
// been captured above.
|
| 384 |
+
unsafe {
|
| 385 |
+
env::set_var("RUN_TEST_NEW_ENV2", "456");
|
| 386 |
+
}
|
| 387 |
+
let result = cmd.output().unwrap();
|
| 388 |
+
unsafe {
|
| 389 |
+
env::remove_var("RUN_TEST_NEW_ENV2");
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
let output = String::from_utf8_lossy(&result.stdout).to_string();
|
| 393 |
+
|
| 394 |
+
assert!(
|
| 395 |
+
output.contains("RUN_TEST_NEW_ENV1=123"),
|
| 396 |
+
"didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{output}"
|
| 397 |
+
);
|
| 398 |
+
assert!(
|
| 399 |
+
output.contains("RUN_TEST_NEW_ENV2=456"),
|
| 400 |
+
"didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{output}"
|
| 401 |
+
);
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
// Regression tests for #30858.
|
| 405 |
+
#[test]
|
| 406 |
+
fn test_interior_nul_in_progname_is_error() {
|
| 407 |
+
match Command::new("has-some-\0\0s-inside").spawn() {
|
| 408 |
+
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
|
| 409 |
+
Ok(_) => panic!(),
|
| 410 |
+
}
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
#[test]
|
| 414 |
+
fn test_interior_nul_in_arg_is_error() {
|
| 415 |
+
match known_command().arg("has-some-\0\0s-inside").spawn() {
|
| 416 |
+
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
|
| 417 |
+
Ok(_) => panic!(),
|
| 418 |
+
}
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
#[test]
|
| 422 |
+
fn test_interior_nul_in_args_is_error() {
|
| 423 |
+
match known_command().args(&["has-some-\0\0s-inside"]).spawn() {
|
| 424 |
+
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
|
| 425 |
+
Ok(_) => panic!(),
|
| 426 |
+
}
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
#[test]
|
| 430 |
+
fn test_interior_nul_in_current_dir_is_error() {
|
| 431 |
+
match known_command().current_dir("has-some-\0\0s-inside").spawn() {
|
| 432 |
+
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
|
| 433 |
+
Ok(_) => panic!(),
|
| 434 |
+
}
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
// Regression tests for #30862.
|
| 438 |
+
#[test]
|
| 439 |
+
#[cfg_attr(
|
| 440 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 441 |
+
ignore = "no `env` cmd available"
|
| 442 |
+
)]
|
| 443 |
+
fn test_interior_nul_in_env_key_is_error() {
|
| 444 |
+
match env_cmd().env("has-some-\0\0s-inside", "value").spawn() {
|
| 445 |
+
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
|
| 446 |
+
Ok(_) => panic!(),
|
| 447 |
+
}
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
#[test]
|
| 451 |
+
#[cfg_attr(
|
| 452 |
+
any(target_os = "vxworks", all(target_vendor = "apple", not(target_os = "macos"))),
|
| 453 |
+
ignore = "no `env` cmd available"
|
| 454 |
+
)]
|
| 455 |
+
fn test_interior_nul_in_env_value_is_error() {
|
| 456 |
+
match env_cmd().env("key", "has-some-\0\0s-inside").spawn() {
|
| 457 |
+
Err(e) => assert_eq!(e.kind(), ErrorKind::InvalidInput),
|
| 458 |
+
Ok(_) => panic!(),
|
| 459 |
+
}
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
#[test]
|
| 463 |
+
fn test_command_implements_send_sync() {
|
| 464 |
+
fn take_send_sync_type<T: Send + Sync>(_: T) {}
|
| 465 |
+
take_send_sync_type(Command::new(""))
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
// Ensure that starting a process with no environment variables works on Windows.
|
| 469 |
+
// This will fail if the environment block is ill-formed.
|
| 470 |
+
#[test]
|
| 471 |
+
#[cfg(windows)]
|
| 472 |
+
fn env_empty() {
|
| 473 |
+
let p = Command::new("cmd").args(&["/C", "exit 0"]).env_clear().spawn();
|
| 474 |
+
assert!(p.is_ok());
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
#[test]
|
| 478 |
+
#[cfg(not(windows))]
|
| 479 |
+
#[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)]
|
| 480 |
+
fn debug_print() {
|
| 481 |
+
const PIDFD: &'static str =
|
| 482 |
+
if cfg!(target_os = "linux") { " create_pidfd: false,\n" } else { "" };
|
| 483 |
+
|
| 484 |
+
let mut command = Command::new("some-boring-name");
|
| 485 |
+
|
| 486 |
+
assert_eq!(format!("{command:?}"), format!(r#""some-boring-name""#));
|
| 487 |
+
|
| 488 |
+
assert_eq!(
|
| 489 |
+
format!("{command:#?}"),
|
| 490 |
+
format!(
|
| 491 |
+
r#"Command {{
|
| 492 |
+
program: "some-boring-name",
|
| 493 |
+
args: [
|
| 494 |
+
"some-boring-name",
|
| 495 |
+
],
|
| 496 |
+
{PIDFD}}}"#
|
| 497 |
+
)
|
| 498 |
+
);
|
| 499 |
+
|
| 500 |
+
command.args(&["1", "2", "3"]);
|
| 501 |
+
|
| 502 |
+
assert_eq!(format!("{command:?}"), format!(r#""some-boring-name" "1" "2" "3""#));
|
| 503 |
+
|
| 504 |
+
assert_eq!(
|
| 505 |
+
format!("{command:#?}"),
|
| 506 |
+
format!(
|
| 507 |
+
r#"Command {{
|
| 508 |
+
program: "some-boring-name",
|
| 509 |
+
args: [
|
| 510 |
+
"some-boring-name",
|
| 511 |
+
"1",
|
| 512 |
+
"2",
|
| 513 |
+
"3",
|
| 514 |
+
],
|
| 515 |
+
{PIDFD}}}"#
|
| 516 |
+
)
|
| 517 |
+
);
|
| 518 |
+
|
| 519 |
+
crate::os::unix::process::CommandExt::arg0(&mut command, "exciting-name");
|
| 520 |
+
|
| 521 |
+
assert_eq!(
|
| 522 |
+
format!("{command:?}"),
|
| 523 |
+
format!(r#"["some-boring-name"] "exciting-name" "1" "2" "3""#)
|
| 524 |
+
);
|
| 525 |
+
|
| 526 |
+
assert_eq!(
|
| 527 |
+
format!("{command:#?}"),
|
| 528 |
+
format!(
|
| 529 |
+
r#"Command {{
|
| 530 |
+
program: "some-boring-name",
|
| 531 |
+
args: [
|
| 532 |
+
"exciting-name",
|
| 533 |
+
"1",
|
| 534 |
+
"2",
|
| 535 |
+
"3",
|
| 536 |
+
],
|
| 537 |
+
{PIDFD}}}"#
|
| 538 |
+
)
|
| 539 |
+
);
|
| 540 |
+
|
| 541 |
+
let mut command_with_env_and_cwd = Command::new("boring-name");
|
| 542 |
+
command_with_env_and_cwd.current_dir("/some/path").env("FOO", "bar");
|
| 543 |
+
assert_eq!(
|
| 544 |
+
format!("{command_with_env_and_cwd:?}"),
|
| 545 |
+
r#"cd "/some/path" && FOO="bar" "boring-name""#
|
| 546 |
+
);
|
| 547 |
+
assert_eq!(
|
| 548 |
+
format!("{command_with_env_and_cwd:#?}"),
|
| 549 |
+
format!(
|
| 550 |
+
r#"Command {{
|
| 551 |
+
program: "boring-name",
|
| 552 |
+
args: [
|
| 553 |
+
"boring-name",
|
| 554 |
+
],
|
| 555 |
+
env: CommandEnv {{
|
| 556 |
+
clear: false,
|
| 557 |
+
vars: {{
|
| 558 |
+
"FOO": Some(
|
| 559 |
+
"bar",
|
| 560 |
+
),
|
| 561 |
+
}},
|
| 562 |
+
}},
|
| 563 |
+
cwd: Some(
|
| 564 |
+
"/some/path",
|
| 565 |
+
),
|
| 566 |
+
{PIDFD}}}"#
|
| 567 |
+
)
|
| 568 |
+
);
|
| 569 |
+
|
| 570 |
+
let mut command_with_removed_env = Command::new("boring-name");
|
| 571 |
+
command_with_removed_env.env_remove("FOO").env_remove("BAR");
|
| 572 |
+
assert_eq!(format!("{command_with_removed_env:?}"), r#"env -u BAR -u FOO "boring-name""#);
|
| 573 |
+
assert_eq!(
|
| 574 |
+
format!("{command_with_removed_env:#?}"),
|
| 575 |
+
format!(
|
| 576 |
+
r#"Command {{
|
| 577 |
+
program: "boring-name",
|
| 578 |
+
args: [
|
| 579 |
+
"boring-name",
|
| 580 |
+
],
|
| 581 |
+
env: CommandEnv {{
|
| 582 |
+
clear: false,
|
| 583 |
+
vars: {{
|
| 584 |
+
"BAR": None,
|
| 585 |
+
"FOO": None,
|
| 586 |
+
}},
|
| 587 |
+
}},
|
| 588 |
+
{PIDFD}}}"#
|
| 589 |
+
)
|
| 590 |
+
);
|
| 591 |
+
|
| 592 |
+
let mut command_with_cleared_env = Command::new("boring-name");
|
| 593 |
+
command_with_cleared_env.env_clear().env("BAR", "val").env_remove("FOO");
|
| 594 |
+
assert_eq!(format!("{command_with_cleared_env:?}"), r#"env -i BAR="val" "boring-name""#);
|
| 595 |
+
assert_eq!(
|
| 596 |
+
format!("{command_with_cleared_env:#?}"),
|
| 597 |
+
format!(
|
| 598 |
+
r#"Command {{
|
| 599 |
+
program: "boring-name",
|
| 600 |
+
args: [
|
| 601 |
+
"boring-name",
|
| 602 |
+
],
|
| 603 |
+
env: CommandEnv {{
|
| 604 |
+
clear: true,
|
| 605 |
+
vars: {{
|
| 606 |
+
"BAR": Some(
|
| 607 |
+
"val",
|
| 608 |
+
),
|
| 609 |
+
}},
|
| 610 |
+
}},
|
| 611 |
+
{PIDFD}}}"#
|
| 612 |
+
)
|
| 613 |
+
);
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
// See issue #91991
|
| 617 |
+
#[test]
|
| 618 |
+
#[cfg(windows)]
|
| 619 |
+
fn run_bat_script() {
|
| 620 |
+
let tempdir = crate::test_helpers::tmpdir();
|
| 621 |
+
let script_path = tempdir.join("hello.cmd");
|
| 622 |
+
|
| 623 |
+
crate::fs::write(&script_path, "@echo Hello, %~1!").unwrap();
|
| 624 |
+
let output = Command::new(&script_path)
|
| 625 |
+
.arg("fellow Rustaceans")
|
| 626 |
+
.stdout(crate::process::Stdio::piped())
|
| 627 |
+
.spawn()
|
| 628 |
+
.unwrap()
|
| 629 |
+
.wait_with_output()
|
| 630 |
+
.unwrap();
|
| 631 |
+
assert!(output.status.success());
|
| 632 |
+
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "Hello, fellow Rustaceans!");
|
| 633 |
+
}
|
| 634 |
+
|
| 635 |
+
// See issue #95178
|
| 636 |
+
#[test]
|
| 637 |
+
#[cfg(windows)]
|
| 638 |
+
fn run_canonical_bat_script() {
|
| 639 |
+
let tempdir = crate::test_helpers::tmpdir();
|
| 640 |
+
let script_path = tempdir.join("hello.cmd");
|
| 641 |
+
|
| 642 |
+
crate::fs::write(&script_path, "@echo Hello, %~1!").unwrap();
|
| 643 |
+
|
| 644 |
+
// Try using a canonical path
|
| 645 |
+
let output = Command::new(&script_path.canonicalize().unwrap())
|
| 646 |
+
.arg("fellow Rustaceans")
|
| 647 |
+
.stdout(crate::process::Stdio::piped())
|
| 648 |
+
.spawn()
|
| 649 |
+
.unwrap()
|
| 650 |
+
.wait_with_output()
|
| 651 |
+
.unwrap();
|
| 652 |
+
assert!(output.status.success());
|
| 653 |
+
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "Hello, fellow Rustaceans!");
|
| 654 |
+
}
|
| 655 |
+
|
| 656 |
+
#[test]
|
| 657 |
+
fn terminate_exited_process() {
|
| 658 |
+
let mut cmd = if cfg!(target_os = "android") {
|
| 659 |
+
let mut p = shell_cmd();
|
| 660 |
+
p.args(&["-c", "true"]);
|
| 661 |
+
p
|
| 662 |
+
} else {
|
| 663 |
+
known_command()
|
| 664 |
+
};
|
| 665 |
+
let mut p = cmd.stdout(Stdio::null()).spawn().unwrap();
|
| 666 |
+
p.wait().unwrap();
|
| 667 |
+
assert!(p.kill().is_ok());
|
| 668 |
+
assert!(p.kill().is_ok());
|
| 669 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/barrier.rs
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::fmt;
|
| 2 |
+
use crate::panic::RefUnwindSafe;
|
| 3 |
+
use crate::sync::nonpoison::{Condvar, Mutex};
|
| 4 |
+
|
| 5 |
+
/// A barrier enables multiple threads to synchronize the beginning
|
| 6 |
+
/// of some computation.
|
| 7 |
+
///
|
| 8 |
+
/// # Examples
|
| 9 |
+
///
|
| 10 |
+
/// ```
|
| 11 |
+
/// use std::sync::Barrier;
|
| 12 |
+
/// use std::thread;
|
| 13 |
+
///
|
| 14 |
+
/// let n = 10;
|
| 15 |
+
/// let barrier = Barrier::new(n);
|
| 16 |
+
/// thread::scope(|s| {
|
| 17 |
+
/// for _ in 0..n {
|
| 18 |
+
/// // The same messages will be printed together.
|
| 19 |
+
/// // You will NOT see any interleaving.
|
| 20 |
+
/// s.spawn(|| {
|
| 21 |
+
/// println!("before wait");
|
| 22 |
+
/// barrier.wait();
|
| 23 |
+
/// println!("after wait");
|
| 24 |
+
/// });
|
| 25 |
+
/// }
|
| 26 |
+
/// });
|
| 27 |
+
/// ```
|
| 28 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 29 |
+
pub struct Barrier {
|
| 30 |
+
lock: Mutex<BarrierState>,
|
| 31 |
+
cvar: Condvar,
|
| 32 |
+
num_threads: usize,
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
#[stable(feature = "unwind_safe_lock_refs", since = "1.12.0")]
|
| 36 |
+
impl RefUnwindSafe for Barrier {}
|
| 37 |
+
|
| 38 |
+
// The inner state of a double barrier
|
| 39 |
+
struct BarrierState {
|
| 40 |
+
count: usize,
|
| 41 |
+
generation_id: usize,
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
/// A `BarrierWaitResult` is returned by [`Barrier::wait()`] when all threads
|
| 45 |
+
/// in the [`Barrier`] have rendezvoused.
|
| 46 |
+
///
|
| 47 |
+
/// # Examples
|
| 48 |
+
///
|
| 49 |
+
/// ```
|
| 50 |
+
/// use std::sync::Barrier;
|
| 51 |
+
///
|
| 52 |
+
/// let barrier = Barrier::new(1);
|
| 53 |
+
/// let barrier_wait_result = barrier.wait();
|
| 54 |
+
/// ```
|
| 55 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 56 |
+
pub struct BarrierWaitResult(bool);
|
| 57 |
+
|
| 58 |
+
#[stable(feature = "std_debug", since = "1.16.0")]
|
| 59 |
+
impl fmt::Debug for Barrier {
|
| 60 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 61 |
+
f.debug_struct("Barrier").finish_non_exhaustive()
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
impl Barrier {
|
| 66 |
+
/// Creates a new barrier that can block a given number of threads.
|
| 67 |
+
///
|
| 68 |
+
/// A barrier will block all threads which call [`wait()`] until the `n`th thread calls [`wait()`],
|
| 69 |
+
/// and then wake up all threads at once.
|
| 70 |
+
///
|
| 71 |
+
/// [`wait()`]: Barrier::wait
|
| 72 |
+
///
|
| 73 |
+
/// # Examples
|
| 74 |
+
///
|
| 75 |
+
/// ```
|
| 76 |
+
/// use std::sync::Barrier;
|
| 77 |
+
///
|
| 78 |
+
/// let barrier = Barrier::new(10);
|
| 79 |
+
/// ```
|
| 80 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 81 |
+
#[rustc_const_stable(feature = "const_barrier", since = "1.78.0")]
|
| 82 |
+
#[must_use]
|
| 83 |
+
#[inline]
|
| 84 |
+
pub const fn new(n: usize) -> Barrier {
|
| 85 |
+
Barrier {
|
| 86 |
+
lock: Mutex::new(BarrierState { count: 0, generation_id: 0 }),
|
| 87 |
+
cvar: Condvar::new(),
|
| 88 |
+
num_threads: n,
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
/// Blocks the current thread until all threads have rendezvoused here.
|
| 93 |
+
///
|
| 94 |
+
/// Barriers are re-usable after all threads have rendezvoused once, and can
|
| 95 |
+
/// be used continuously.
|
| 96 |
+
///
|
| 97 |
+
/// A single (arbitrary) thread will receive a [`BarrierWaitResult`] that
|
| 98 |
+
/// returns `true` from [`BarrierWaitResult::is_leader()`] when returning
|
| 99 |
+
/// from this function, and all other threads will receive a result that
|
| 100 |
+
/// will return `false` from [`BarrierWaitResult::is_leader()`].
|
| 101 |
+
///
|
| 102 |
+
/// # Examples
|
| 103 |
+
///
|
| 104 |
+
/// ```
|
| 105 |
+
/// use std::sync::Barrier;
|
| 106 |
+
/// use std::thread;
|
| 107 |
+
///
|
| 108 |
+
/// let n = 10;
|
| 109 |
+
/// let barrier = Barrier::new(n);
|
| 110 |
+
/// thread::scope(|s| {
|
| 111 |
+
/// for _ in 0..n {
|
| 112 |
+
/// // The same messages will be printed together.
|
| 113 |
+
/// // You will NOT see any interleaving.
|
| 114 |
+
/// s.spawn(|| {
|
| 115 |
+
/// println!("before wait");
|
| 116 |
+
/// barrier.wait();
|
| 117 |
+
/// println!("after wait");
|
| 118 |
+
/// });
|
| 119 |
+
/// }
|
| 120 |
+
/// });
|
| 121 |
+
/// ```
|
| 122 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 123 |
+
pub fn wait(&self) -> BarrierWaitResult {
|
| 124 |
+
let mut lock = self.lock.lock();
|
| 125 |
+
let local_gen = lock.generation_id;
|
| 126 |
+
lock.count += 1;
|
| 127 |
+
if lock.count < self.num_threads {
|
| 128 |
+
self.cvar.wait_while(&mut lock, |state| local_gen == state.generation_id);
|
| 129 |
+
BarrierWaitResult(false)
|
| 130 |
+
} else {
|
| 131 |
+
lock.count = 0;
|
| 132 |
+
lock.generation_id = lock.generation_id.wrapping_add(1);
|
| 133 |
+
self.cvar.notify_all();
|
| 134 |
+
BarrierWaitResult(true)
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
#[stable(feature = "std_debug", since = "1.16.0")]
|
| 140 |
+
impl fmt::Debug for BarrierWaitResult {
|
| 141 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 142 |
+
f.debug_struct("BarrierWaitResult").field("is_leader", &self.is_leader()).finish()
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
impl BarrierWaitResult {
|
| 147 |
+
/// Returns `true` if this thread is the "leader thread" for the call to
|
| 148 |
+
/// [`Barrier::wait()`].
|
| 149 |
+
///
|
| 150 |
+
/// Only one thread will have `true` returned from their result, all other
|
| 151 |
+
/// threads will have `false` returned.
|
| 152 |
+
///
|
| 153 |
+
/// # Examples
|
| 154 |
+
///
|
| 155 |
+
/// ```
|
| 156 |
+
/// use std::sync::Barrier;
|
| 157 |
+
///
|
| 158 |
+
/// let barrier = Barrier::new(1);
|
| 159 |
+
/// let barrier_wait_result = barrier.wait();
|
| 160 |
+
/// println!("{:?}", barrier_wait_result.is_leader());
|
| 161 |
+
/// ```
|
| 162 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 163 |
+
#[must_use]
|
| 164 |
+
pub fn is_leader(&self) -> bool {
|
| 165 |
+
self.0
|
| 166 |
+
}
|
| 167 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/lazy_lock.rs
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use super::once::OnceExclusiveState;
|
| 2 |
+
use crate::cell::UnsafeCell;
|
| 3 |
+
use crate::mem::ManuallyDrop;
|
| 4 |
+
use crate::ops::{Deref, DerefMut};
|
| 5 |
+
use crate::panic::{RefUnwindSafe, UnwindSafe};
|
| 6 |
+
use crate::sync::Once;
|
| 7 |
+
use crate::{fmt, ptr};
|
| 8 |
+
|
| 9 |
+
// We use the state of a Once as discriminant value. Upon creation, the state is
|
| 10 |
+
// "incomplete" and `f` contains the initialization closure. In the first call to
|
| 11 |
+
// `call_once`, `f` is taken and run. If it succeeds, `value` is set and the state
|
| 12 |
+
// is changed to "complete". If it panics, the Once is poisoned, so none of the
|
| 13 |
+
// two fields is initialized.
|
| 14 |
+
union Data<T, F> {
|
| 15 |
+
value: ManuallyDrop<T>,
|
| 16 |
+
f: ManuallyDrop<F>,
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
/// A value which is initialized on the first access.
|
| 20 |
+
///
|
| 21 |
+
/// This type is a thread-safe [`LazyCell`], and can be used in statics.
|
| 22 |
+
/// Since initialization may be called from multiple threads, any
|
| 23 |
+
/// dereferencing call will block the calling thread if another
|
| 24 |
+
/// initialization routine is currently running.
|
| 25 |
+
///
|
| 26 |
+
/// [`LazyCell`]: crate::cell::LazyCell
|
| 27 |
+
///
|
| 28 |
+
/// # Poisoning
|
| 29 |
+
///
|
| 30 |
+
/// If the initialization closure passed to [`LazyLock::new`] panics, the lock will be poisoned.
|
| 31 |
+
/// Once the lock is poisoned, any threads that attempt to access this lock (via a dereference
|
| 32 |
+
/// or via an explicit call to [`force()`]) will panic.
|
| 33 |
+
///
|
| 34 |
+
/// This concept is similar to that of poisoning in the [`std::sync::poison`] module. A key
|
| 35 |
+
/// difference, however, is that poisoning in `LazyLock` is _unrecoverable_. All future accesses of
|
| 36 |
+
/// the lock from other threads will panic, whereas a type in [`std::sync::poison`] like
|
| 37 |
+
/// [`std::sync::poison::Mutex`] allows recovery via [`PoisonError::into_inner()`].
|
| 38 |
+
///
|
| 39 |
+
/// [`force()`]: LazyLock::force
|
| 40 |
+
/// [`std::sync::poison`]: crate::sync::poison
|
| 41 |
+
/// [`std::sync::poison::Mutex`]: crate::sync::poison::Mutex
|
| 42 |
+
/// [`PoisonError::into_inner()`]: crate::sync::poison::PoisonError::into_inner
|
| 43 |
+
///
|
| 44 |
+
/// # Examples
|
| 45 |
+
///
|
| 46 |
+
/// Initialize static variables with `LazyLock`.
|
| 47 |
+
/// ```
|
| 48 |
+
/// use std::sync::LazyLock;
|
| 49 |
+
///
|
| 50 |
+
/// // Note: static items do not call [`Drop`] on program termination, so this won't be deallocated.
|
| 51 |
+
/// // this is fine, as the OS can deallocate the terminated program faster than we can free memory
|
| 52 |
+
/// // but tools like valgrind might report "memory leaks" as it isn't obvious this is intentional.
|
| 53 |
+
/// static DEEP_THOUGHT: LazyLock<String> = LazyLock::new(|| {
|
| 54 |
+
/// # mod another_crate {
|
| 55 |
+
/// # pub fn great_question() -> String { "42".to_string() }
|
| 56 |
+
/// # }
|
| 57 |
+
/// // M3 Ultra takes about 16 million years in --release config
|
| 58 |
+
/// another_crate::great_question()
|
| 59 |
+
/// });
|
| 60 |
+
///
|
| 61 |
+
/// // The `String` is built, stored in the `LazyLock`, and returned as `&String`.
|
| 62 |
+
/// let _ = &*DEEP_THOUGHT;
|
| 63 |
+
/// ```
|
| 64 |
+
///
|
| 65 |
+
/// Initialize fields with `LazyLock`.
|
| 66 |
+
/// ```
|
| 67 |
+
/// use std::sync::LazyLock;
|
| 68 |
+
///
|
| 69 |
+
/// #[derive(Debug)]
|
| 70 |
+
/// struct UseCellLock {
|
| 71 |
+
/// number: LazyLock<u32>,
|
| 72 |
+
/// }
|
| 73 |
+
/// fn main() {
|
| 74 |
+
/// let lock: LazyLock<u32> = LazyLock::new(|| 0u32);
|
| 75 |
+
///
|
| 76 |
+
/// let data = UseCellLock { number: lock };
|
| 77 |
+
/// println!("{}", *data.number);
|
| 78 |
+
/// }
|
| 79 |
+
/// ```
|
| 80 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 81 |
+
pub struct LazyLock<T, F = fn() -> T> {
|
| 82 |
+
// FIXME(nonpoison_once): if possible, switch to nonpoison version once it is available
|
| 83 |
+
once: Once,
|
| 84 |
+
data: UnsafeCell<Data<T, F>>,
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
impl<T, F: FnOnce() -> T> LazyLock<T, F> {
|
| 88 |
+
/// Creates a new lazy value with the given initializing function.
|
| 89 |
+
///
|
| 90 |
+
/// # Examples
|
| 91 |
+
///
|
| 92 |
+
/// ```
|
| 93 |
+
/// use std::sync::LazyLock;
|
| 94 |
+
///
|
| 95 |
+
/// let hello = "Hello, World!".to_string();
|
| 96 |
+
///
|
| 97 |
+
/// let lazy = LazyLock::new(|| hello.to_uppercase());
|
| 98 |
+
///
|
| 99 |
+
/// assert_eq!(&*lazy, "HELLO, WORLD!");
|
| 100 |
+
/// ```
|
| 101 |
+
#[inline]
|
| 102 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 103 |
+
#[rustc_const_stable(feature = "lazy_cell", since = "1.80.0")]
|
| 104 |
+
pub const fn new(f: F) -> LazyLock<T, F> {
|
| 105 |
+
LazyLock { once: Once::new(), data: UnsafeCell::new(Data { f: ManuallyDrop::new(f) }) }
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
/// Creates a new lazy value that is already initialized.
|
| 109 |
+
#[inline]
|
| 110 |
+
#[cfg(test)]
|
| 111 |
+
pub(crate) fn preinit(value: T) -> LazyLock<T, F> {
|
| 112 |
+
let once = Once::new();
|
| 113 |
+
once.call_once(|| {});
|
| 114 |
+
LazyLock { once, data: UnsafeCell::new(Data { value: ManuallyDrop::new(value) }) }
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
/// Consumes this `LazyLock` returning the stored value.
|
| 118 |
+
///
|
| 119 |
+
/// Returns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.
|
| 120 |
+
///
|
| 121 |
+
/// # Panics
|
| 122 |
+
///
|
| 123 |
+
/// Panics if the lock is poisoned.
|
| 124 |
+
///
|
| 125 |
+
/// # Examples
|
| 126 |
+
///
|
| 127 |
+
/// ```
|
| 128 |
+
/// #![feature(lazy_cell_into_inner)]
|
| 129 |
+
///
|
| 130 |
+
/// use std::sync::LazyLock;
|
| 131 |
+
///
|
| 132 |
+
/// let hello = "Hello, World!".to_string();
|
| 133 |
+
///
|
| 134 |
+
/// let lazy = LazyLock::new(|| hello.to_uppercase());
|
| 135 |
+
///
|
| 136 |
+
/// assert_eq!(&*lazy, "HELLO, WORLD!");
|
| 137 |
+
/// assert_eq!(LazyLock::into_inner(lazy).ok(), Some("HELLO, WORLD!".to_string()));
|
| 138 |
+
/// ```
|
| 139 |
+
#[unstable(feature = "lazy_cell_into_inner", issue = "125623")]
|
| 140 |
+
pub fn into_inner(mut this: Self) -> Result<T, F> {
|
| 141 |
+
let state = this.once.state();
|
| 142 |
+
match state {
|
| 143 |
+
OnceExclusiveState::Poisoned => panic_poisoned(),
|
| 144 |
+
state => {
|
| 145 |
+
let this = ManuallyDrop::new(this);
|
| 146 |
+
let data = unsafe { ptr::read(&this.data) }.into_inner();
|
| 147 |
+
match state {
|
| 148 |
+
OnceExclusiveState::Incomplete => {
|
| 149 |
+
Err(ManuallyDrop::into_inner(unsafe { data.f }))
|
| 150 |
+
}
|
| 151 |
+
OnceExclusiveState::Complete => {
|
| 152 |
+
Ok(ManuallyDrop::into_inner(unsafe { data.value }))
|
| 153 |
+
}
|
| 154 |
+
OnceExclusiveState::Poisoned => unreachable!(),
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
/// Forces the evaluation of this lazy value and returns a mutable reference to
|
| 161 |
+
/// the result.
|
| 162 |
+
///
|
| 163 |
+
/// # Panics
|
| 164 |
+
///
|
| 165 |
+
/// If the initialization closure panics (the one that is passed to the [`new()`] method), the
|
| 166 |
+
/// panic is propagated to the caller, and the lock becomes poisoned. This will cause all future
|
| 167 |
+
/// accesses of the lock (via [`force()`] or a dereference) to panic.
|
| 168 |
+
///
|
| 169 |
+
/// [`new()`]: LazyLock::new
|
| 170 |
+
/// [`force()`]: LazyLock::force
|
| 171 |
+
///
|
| 172 |
+
/// # Examples
|
| 173 |
+
///
|
| 174 |
+
/// ```
|
| 175 |
+
/// use std::sync::LazyLock;
|
| 176 |
+
///
|
| 177 |
+
/// let mut lazy = LazyLock::new(|| 92);
|
| 178 |
+
///
|
| 179 |
+
/// let p = LazyLock::force_mut(&mut lazy);
|
| 180 |
+
/// assert_eq!(*p, 92);
|
| 181 |
+
/// *p = 44;
|
| 182 |
+
/// assert_eq!(*lazy, 44);
|
| 183 |
+
/// ```
|
| 184 |
+
#[inline]
|
| 185 |
+
#[stable(feature = "lazy_get", since = "1.94.0")]
|
| 186 |
+
pub fn force_mut(this: &mut LazyLock<T, F>) -> &mut T {
|
| 187 |
+
#[cold]
|
| 188 |
+
/// # Safety
|
| 189 |
+
/// May only be called when the state is `Incomplete`.
|
| 190 |
+
unsafe fn really_init_mut<T, F: FnOnce() -> T>(this: &mut LazyLock<T, F>) -> &mut T {
|
| 191 |
+
struct PoisonOnPanic<'a, T, F>(&'a mut LazyLock<T, F>);
|
| 192 |
+
impl<T, F> Drop for PoisonOnPanic<'_, T, F> {
|
| 193 |
+
#[inline]
|
| 194 |
+
fn drop(&mut self) {
|
| 195 |
+
self.0.once.set_state(OnceExclusiveState::Poisoned);
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
// SAFETY: We always poison if the initializer panics (then we never check the data),
|
| 200 |
+
// or set the data on success.
|
| 201 |
+
let f = unsafe { ManuallyDrop::take(&mut this.data.get_mut().f) };
|
| 202 |
+
// INVARIANT: Initiated from mutable reference, don't drop because we read it.
|
| 203 |
+
let guard = PoisonOnPanic(this);
|
| 204 |
+
let data = f();
|
| 205 |
+
guard.0.data.get_mut().value = ManuallyDrop::new(data);
|
| 206 |
+
guard.0.once.set_state(OnceExclusiveState::Complete);
|
| 207 |
+
core::mem::forget(guard);
|
| 208 |
+
// SAFETY: We put the value there above.
|
| 209 |
+
unsafe { &mut this.data.get_mut().value }
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
let state = this.once.state();
|
| 213 |
+
match state {
|
| 214 |
+
OnceExclusiveState::Poisoned => panic_poisoned(),
|
| 215 |
+
// SAFETY: The `Once` states we completed the initialization.
|
| 216 |
+
OnceExclusiveState::Complete => unsafe { &mut this.data.get_mut().value },
|
| 217 |
+
// SAFETY: The state is `Incomplete`.
|
| 218 |
+
OnceExclusiveState::Incomplete => unsafe { really_init_mut(this) },
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
/// Forces the evaluation of this lazy value and returns a reference to
|
| 223 |
+
/// result. This is equivalent to the `Deref` impl, but is explicit.
|
| 224 |
+
///
|
| 225 |
+
/// This method will block the calling thread if another initialization
|
| 226 |
+
/// routine is currently running.
|
| 227 |
+
///
|
| 228 |
+
/// # Panics
|
| 229 |
+
///
|
| 230 |
+
/// If the initialization closure panics (the one that is passed to the [`new()`] method), the
|
| 231 |
+
/// panic is propagated to the caller, and the lock becomes poisoned. This will cause all future
|
| 232 |
+
/// accesses of the lock (via [`force()`] or a dereference) to panic.
|
| 233 |
+
///
|
| 234 |
+
/// [`new()`]: LazyLock::new
|
| 235 |
+
/// [`force()`]: LazyLock::force
|
| 236 |
+
///
|
| 237 |
+
/// # Examples
|
| 238 |
+
///
|
| 239 |
+
/// ```
|
| 240 |
+
/// use std::sync::LazyLock;
|
| 241 |
+
///
|
| 242 |
+
/// let lazy = LazyLock::new(|| 92);
|
| 243 |
+
///
|
| 244 |
+
/// assert_eq!(LazyLock::force(&lazy), &92);
|
| 245 |
+
/// assert_eq!(&*lazy, &92);
|
| 246 |
+
/// ```
|
| 247 |
+
#[inline]
|
| 248 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 249 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 250 |
+
pub fn force(this: &LazyLock<T, F>) -> &T {
|
| 251 |
+
this.once.call_once_force(|state| {
|
| 252 |
+
if state.is_poisoned() {
|
| 253 |
+
panic_poisoned();
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
// SAFETY: `call_once` only runs this closure once, ever.
|
| 257 |
+
let data = unsafe { &mut *this.data.get() };
|
| 258 |
+
let f = unsafe { ManuallyDrop::take(&mut data.f) };
|
| 259 |
+
let value = f();
|
| 260 |
+
data.value = ManuallyDrop::new(value);
|
| 261 |
+
});
|
| 262 |
+
|
| 263 |
+
// SAFETY:
|
| 264 |
+
// There are four possible scenarios:
|
| 265 |
+
// * the closure was called and initialized `value`.
|
| 266 |
+
// * the closure was called and panicked, so this point is never reached.
|
| 267 |
+
// * the closure was not called, but a previous call initialized `value`.
|
| 268 |
+
// * the closure was not called because the Once is poisoned, which we handled above.
|
| 269 |
+
// So `value` has definitely been initialized and will not be modified again.
|
| 270 |
+
unsafe { &*(*this.data.get()).value }
|
| 271 |
+
}
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
impl<T, F> LazyLock<T, F> {
|
| 275 |
+
/// Returns a mutable reference to the value if initialized. Otherwise (if uninitialized or
|
| 276 |
+
/// poisoned), returns `None`.
|
| 277 |
+
///
|
| 278 |
+
/// # Examples
|
| 279 |
+
///
|
| 280 |
+
/// ```
|
| 281 |
+
/// use std::sync::LazyLock;
|
| 282 |
+
///
|
| 283 |
+
/// let mut lazy = LazyLock::new(|| 92);
|
| 284 |
+
///
|
| 285 |
+
/// assert_eq!(LazyLock::get_mut(&mut lazy), None);
|
| 286 |
+
/// let _ = LazyLock::force(&lazy);
|
| 287 |
+
/// *LazyLock::get_mut(&mut lazy).unwrap() = 44;
|
| 288 |
+
/// assert_eq!(*lazy, 44);
|
| 289 |
+
/// ```
|
| 290 |
+
#[inline]
|
| 291 |
+
#[stable(feature = "lazy_get", since = "1.94.0")]
|
| 292 |
+
pub fn get_mut(this: &mut LazyLock<T, F>) -> Option<&mut T> {
|
| 293 |
+
// `state()` does not perform an atomic load, so prefer it over `is_complete()`.
|
| 294 |
+
let state = this.once.state();
|
| 295 |
+
match state {
|
| 296 |
+
// SAFETY:
|
| 297 |
+
// The closure has been run successfully, so `value` has been initialized.
|
| 298 |
+
OnceExclusiveState::Complete => Some(unsafe { &mut this.data.get_mut().value }),
|
| 299 |
+
_ => None,
|
| 300 |
+
}
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
/// Returns a reference to the value if initialized. Otherwise (if uninitialized or poisoned),
|
| 304 |
+
/// returns `None`.
|
| 305 |
+
///
|
| 306 |
+
/// # Examples
|
| 307 |
+
///
|
| 308 |
+
/// ```
|
| 309 |
+
/// use std::sync::LazyLock;
|
| 310 |
+
///
|
| 311 |
+
/// let lazy = LazyLock::new(|| 92);
|
| 312 |
+
///
|
| 313 |
+
/// assert_eq!(LazyLock::get(&lazy), None);
|
| 314 |
+
/// let _ = LazyLock::force(&lazy);
|
| 315 |
+
/// assert_eq!(LazyLock::get(&lazy), Some(&92));
|
| 316 |
+
/// ```
|
| 317 |
+
#[inline]
|
| 318 |
+
#[stable(feature = "lazy_get", since = "1.94.0")]
|
| 319 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 320 |
+
pub fn get(this: &LazyLock<T, F>) -> Option<&T> {
|
| 321 |
+
if this.once.is_completed() {
|
| 322 |
+
// SAFETY:
|
| 323 |
+
// The closure has been run successfully, so `value` has been initialized
|
| 324 |
+
// and will not be modified again.
|
| 325 |
+
Some(unsafe { &(*this.data.get()).value })
|
| 326 |
+
} else {
|
| 327 |
+
None
|
| 328 |
+
}
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 333 |
+
impl<T, F> Drop for LazyLock<T, F> {
|
| 334 |
+
fn drop(&mut self) {
|
| 335 |
+
match self.once.state() {
|
| 336 |
+
OnceExclusiveState::Incomplete => unsafe {
|
| 337 |
+
ManuallyDrop::drop(&mut self.data.get_mut().f)
|
| 338 |
+
},
|
| 339 |
+
OnceExclusiveState::Complete => unsafe {
|
| 340 |
+
ManuallyDrop::drop(&mut self.data.get_mut().value)
|
| 341 |
+
},
|
| 342 |
+
OnceExclusiveState::Poisoned => {}
|
| 343 |
+
}
|
| 344 |
+
}
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 348 |
+
impl<T, F: FnOnce() -> T> Deref for LazyLock<T, F> {
|
| 349 |
+
type Target = T;
|
| 350 |
+
|
| 351 |
+
/// Dereferences the value.
|
| 352 |
+
///
|
| 353 |
+
/// This method will block the calling thread if another initialization
|
| 354 |
+
/// routine is currently running.
|
| 355 |
+
///
|
| 356 |
+
/// # Panics
|
| 357 |
+
///
|
| 358 |
+
/// If the initialization closure panics (the one that is passed to the [`new()`] method), the
|
| 359 |
+
/// panic is propagated to the caller, and the lock becomes poisoned. This will cause all future
|
| 360 |
+
/// accesses of the lock (via [`force()`] or a dereference) to panic.
|
| 361 |
+
///
|
| 362 |
+
/// [`new()`]: LazyLock::new
|
| 363 |
+
/// [`force()`]: LazyLock::force
|
| 364 |
+
#[inline]
|
| 365 |
+
fn deref(&self) -> &T {
|
| 366 |
+
LazyLock::force(self)
|
| 367 |
+
}
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
#[stable(feature = "lazy_deref_mut", since = "1.89.0")]
|
| 371 |
+
impl<T, F: FnOnce() -> T> DerefMut for LazyLock<T, F> {
|
| 372 |
+
/// # Panics
|
| 373 |
+
///
|
| 374 |
+
/// If the initialization closure panics (the one that is passed to the [`new()`] method), the
|
| 375 |
+
/// panic is propagated to the caller, and the lock becomes poisoned. This will cause all future
|
| 376 |
+
/// accesses of the lock (via [`force()`] or a dereference) to panic.
|
| 377 |
+
///
|
| 378 |
+
/// [`new()`]: LazyLock::new
|
| 379 |
+
/// [`force()`]: LazyLock::force
|
| 380 |
+
#[inline]
|
| 381 |
+
fn deref_mut(&mut self) -> &mut T {
|
| 382 |
+
LazyLock::force_mut(self)
|
| 383 |
+
}
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 387 |
+
impl<T: Default> Default for LazyLock<T> {
|
| 388 |
+
/// Creates a new lazy value using `Default` as the initializing function.
|
| 389 |
+
#[inline]
|
| 390 |
+
fn default() -> LazyLock<T> {
|
| 391 |
+
LazyLock::new(T::default)
|
| 392 |
+
}
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 396 |
+
impl<T: fmt::Debug, F> fmt::Debug for LazyLock<T, F> {
|
| 397 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 398 |
+
let mut d = f.debug_tuple("LazyLock");
|
| 399 |
+
match LazyLock::get(self) {
|
| 400 |
+
Some(v) => d.field(v),
|
| 401 |
+
None => d.field(&format_args!("<uninit>")),
|
| 402 |
+
};
|
| 403 |
+
d.finish()
|
| 404 |
+
}
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
#[cold]
|
| 408 |
+
#[inline(never)]
|
| 409 |
+
fn panic_poisoned() -> ! {
|
| 410 |
+
panic!("LazyLock instance has previously been poisoned")
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
// We never create a `&F` from a `&LazyLock<T, F>` so it is fine
|
| 414 |
+
// to not impl `Sync` for `F`.
|
| 415 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 416 |
+
unsafe impl<T: Sync + Send, F: Send> Sync for LazyLock<T, F> {}
|
| 417 |
+
// auto-derived `Send` impl is OK.
|
| 418 |
+
|
| 419 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 420 |
+
impl<T: RefUnwindSafe + UnwindSafe, F: UnwindSafe> RefUnwindSafe for LazyLock<T, F> {}
|
| 421 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 422 |
+
impl<T: UnwindSafe, F: UnwindSafe> UnwindSafe for LazyLock<T, F> {}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/mod.rs
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Useful synchronization primitives.
|
| 2 |
+
//!
|
| 3 |
+
//! ## The need for synchronization
|
| 4 |
+
//!
|
| 5 |
+
//! Conceptually, a Rust program is a series of operations which will
|
| 6 |
+
//! be executed on a computer. The timeline of events happening in the
|
| 7 |
+
//! program is consistent with the order of the operations in the code.
|
| 8 |
+
//!
|
| 9 |
+
//! Consider the following code, operating on some global static variables:
|
| 10 |
+
//!
|
| 11 |
+
//! ```rust
|
| 12 |
+
//! // FIXME(static_mut_refs): Do not allow `static_mut_refs` lint
|
| 13 |
+
//! #![allow(static_mut_refs)]
|
| 14 |
+
//!
|
| 15 |
+
//! static mut A: u32 = 0;
|
| 16 |
+
//! static mut B: u32 = 0;
|
| 17 |
+
//! static mut C: u32 = 0;
|
| 18 |
+
//!
|
| 19 |
+
//! fn main() {
|
| 20 |
+
//! unsafe {
|
| 21 |
+
//! A = 3;
|
| 22 |
+
//! B = 4;
|
| 23 |
+
//! A = A + B;
|
| 24 |
+
//! C = B;
|
| 25 |
+
//! println!("{A} {B} {C}");
|
| 26 |
+
//! C = A;
|
| 27 |
+
//! }
|
| 28 |
+
//! }
|
| 29 |
+
//! ```
|
| 30 |
+
//!
|
| 31 |
+
//! It appears as if some variables stored in memory are changed, an addition
|
| 32 |
+
//! is performed, result is stored in `A` and the variable `C` is
|
| 33 |
+
//! modified twice.
|
| 34 |
+
//!
|
| 35 |
+
//! When only a single thread is involved, the results are as expected:
|
| 36 |
+
//! the line `7 4 4` gets printed.
|
| 37 |
+
//!
|
| 38 |
+
//! As for what happens behind the scenes, when optimizations are enabled the
|
| 39 |
+
//! final generated machine code might look very different from the code:
|
| 40 |
+
//!
|
| 41 |
+
//! - The first store to `C` might be moved before the store to `A` or `B`,
|
| 42 |
+
//! _as if_ we had written `C = 4; A = 3; B = 4`.
|
| 43 |
+
//!
|
| 44 |
+
//! - Assignment of `A + B` to `A` might be removed, since the sum can be stored
|
| 45 |
+
//! in a temporary location until it gets printed, with the global variable
|
| 46 |
+
//! never getting updated.
|
| 47 |
+
//!
|
| 48 |
+
//! - The final result could be determined just by looking at the code
|
| 49 |
+
//! at compile time, so [constant folding] might turn the whole
|
| 50 |
+
//! block into a simple `println!("7 4 4")`.
|
| 51 |
+
//!
|
| 52 |
+
//! The compiler is allowed to perform any combination of these
|
| 53 |
+
//! optimizations, as long as the final optimized code, when executed,
|
| 54 |
+
//! produces the same results as the one without optimizations.
|
| 55 |
+
//!
|
| 56 |
+
//! Due to the [concurrency] involved in modern computers, assumptions
|
| 57 |
+
//! about the program's execution order are often wrong. Access to
|
| 58 |
+
//! global variables can lead to nondeterministic results, **even if**
|
| 59 |
+
//! compiler optimizations are disabled, and it is **still possible**
|
| 60 |
+
//! to introduce synchronization bugs.
|
| 61 |
+
//!
|
| 62 |
+
//! Note that thanks to Rust's safety guarantees, accessing global (static)
|
| 63 |
+
//! variables requires `unsafe` code, assuming we don't use any of the
|
| 64 |
+
//! synchronization primitives in this module.
|
| 65 |
+
//!
|
| 66 |
+
//! [constant folding]: https://en.wikipedia.org/wiki/Constant_folding
|
| 67 |
+
//! [concurrency]: https://en.wikipedia.org/wiki/Concurrency_(computer_science)
|
| 68 |
+
//!
|
| 69 |
+
//! ## Out-of-order execution
|
| 70 |
+
//!
|
| 71 |
+
//! Instructions can execute in a different order from the one we define, due to
|
| 72 |
+
//! various reasons:
|
| 73 |
+
//!
|
| 74 |
+
//! - The **compiler** reordering instructions: If the compiler can issue an
|
| 75 |
+
//! instruction at an earlier point, it will try to do so. For example, it
|
| 76 |
+
//! might hoist memory loads at the top of a code block, so that the CPU can
|
| 77 |
+
//! start [prefetching] the values from memory.
|
| 78 |
+
//!
|
| 79 |
+
//! In single-threaded scenarios, this can cause issues when writing
|
| 80 |
+
//! signal handlers or certain kinds of low-level code.
|
| 81 |
+
//! Use [compiler fences] to prevent this reordering.
|
| 82 |
+
//!
|
| 83 |
+
//! - A **single processor** executing instructions [out-of-order]:
|
| 84 |
+
//! Modern CPUs are capable of [superscalar] execution,
|
| 85 |
+
//! i.e., multiple instructions might be executing at the same time,
|
| 86 |
+
//! even though the machine code describes a sequential process.
|
| 87 |
+
//!
|
| 88 |
+
//! This kind of reordering is handled transparently by the CPU.
|
| 89 |
+
//!
|
| 90 |
+
//! - A **multiprocessor** system executing multiple hardware threads
|
| 91 |
+
//! at the same time: In multi-threaded scenarios, you can use two
|
| 92 |
+
//! kinds of primitives to deal with synchronization:
|
| 93 |
+
//! - [memory fences] to ensure memory accesses are made visible to
|
| 94 |
+
//! other CPUs in the right order.
|
| 95 |
+
//! - [atomic operations] to ensure simultaneous access to the same
|
| 96 |
+
//! memory location doesn't lead to undefined behavior.
|
| 97 |
+
//!
|
| 98 |
+
//! [prefetching]: https://en.wikipedia.org/wiki/Cache_prefetching
|
| 99 |
+
//! [compiler fences]: crate::sync::atomic::compiler_fence
|
| 100 |
+
//! [out-of-order]: https://en.wikipedia.org/wiki/Out-of-order_execution
|
| 101 |
+
//! [superscalar]: https://en.wikipedia.org/wiki/Superscalar_processor
|
| 102 |
+
//! [memory fences]: crate::sync::atomic::fence
|
| 103 |
+
//! [atomic operations]: crate::sync::atomic
|
| 104 |
+
//!
|
| 105 |
+
//! ## Higher-level synchronization objects
|
| 106 |
+
//!
|
| 107 |
+
//! Most of the low-level synchronization primitives are quite error-prone and
|
| 108 |
+
//! inconvenient to use, which is why the standard library also exposes some
|
| 109 |
+
//! higher-level synchronization objects.
|
| 110 |
+
//!
|
| 111 |
+
//! These abstractions can be built out of lower-level primitives.
|
| 112 |
+
//! For efficiency, the sync objects in the standard library are usually
|
| 113 |
+
//! implemented with help from the operating system's kernel, which is
|
| 114 |
+
//! able to reschedule the threads while they are blocked on acquiring
|
| 115 |
+
//! a lock.
|
| 116 |
+
//!
|
| 117 |
+
//! The following is an overview of the available synchronization
|
| 118 |
+
//! objects:
|
| 119 |
+
//!
|
| 120 |
+
//! - [`Arc`]: Atomically Reference-Counted pointer, which can be used
|
| 121 |
+
//! in multithreaded environments to prolong the lifetime of some
|
| 122 |
+
//! data until all the threads have finished using it.
|
| 123 |
+
//!
|
| 124 |
+
//! - [`Barrier`]: Ensures multiple threads will wait for each other
|
| 125 |
+
//! to reach a point in the program, before continuing execution all
|
| 126 |
+
//! together.
|
| 127 |
+
//!
|
| 128 |
+
//! - [`Condvar`]: Condition Variable, providing the ability to block
|
| 129 |
+
//! a thread while waiting for an event to occur.
|
| 130 |
+
//!
|
| 131 |
+
//! - [`mpsc`]: Multi-producer, single-consumer queues, used for
|
| 132 |
+
//! message-based communication. Can provide a lightweight
|
| 133 |
+
//! inter-thread synchronisation mechanism, at the cost of some
|
| 134 |
+
//! extra memory.
|
| 135 |
+
//!
|
| 136 |
+
//! - [`mpmc`]: Multi-producer, multi-consumer queues, used for
|
| 137 |
+
//! message-based communication. Can provide a lightweight
|
| 138 |
+
//! inter-thread synchronisation mechanism, at the cost of some
|
| 139 |
+
//! extra memory.
|
| 140 |
+
//!
|
| 141 |
+
//! - [`Mutex`]: Mutual Exclusion mechanism, which ensures that at
|
| 142 |
+
//! most one thread at a time is able to access some data.
|
| 143 |
+
//!
|
| 144 |
+
//! - [`Once`]: Used for a thread-safe, one-time global initialization routine.
|
| 145 |
+
//! Mostly useful for implementing other types like [`OnceLock`].
|
| 146 |
+
//!
|
| 147 |
+
//! - [`OnceLock`]: Used for thread-safe, one-time initialization of a
|
| 148 |
+
//! variable, with potentially different initializers based on the caller.
|
| 149 |
+
//!
|
| 150 |
+
//! - [`LazyLock`]: Used for thread-safe, one-time initialization of a
|
| 151 |
+
//! variable, using one nullary initializer function provided at creation.
|
| 152 |
+
//!
|
| 153 |
+
//! - [`RwLock`]: Provides a mutual exclusion mechanism which allows
|
| 154 |
+
//! multiple readers at the same time, while allowing only one
|
| 155 |
+
//! writer at a time. In some cases, this can be more efficient than
|
| 156 |
+
//! a mutex.
|
| 157 |
+
//!
|
| 158 |
+
//! [`Arc`]: crate::sync::Arc
|
| 159 |
+
//! [`Barrier`]: crate::sync::Barrier
|
| 160 |
+
//! [`Condvar`]: crate::sync::Condvar
|
| 161 |
+
//! [`mpmc`]: crate::sync::mpmc
|
| 162 |
+
//! [`mpsc`]: crate::sync::mpsc
|
| 163 |
+
//! [`Mutex`]: crate::sync::Mutex
|
| 164 |
+
//! [`Once`]: crate::sync::Once
|
| 165 |
+
//! [`OnceLock`]: crate::sync::OnceLock
|
| 166 |
+
//! [`RwLock`]: crate::sync::RwLock
|
| 167 |
+
|
| 168 |
+
#![stable(feature = "rust1", since = "1.0.0")]
|
| 169 |
+
|
| 170 |
+
// No formatting: this file is just re-exports, and their order is worth preserving.
|
| 171 |
+
#![cfg_attr(rustfmt, rustfmt::skip)]
|
| 172 |
+
|
| 173 |
+
// These come from `core` & `alloc` and only in one flavor: no poisoning.
|
| 174 |
+
#[unstable(feature = "exclusive_wrapper", issue = "98407")]
|
| 175 |
+
pub use core::sync::Exclusive;
|
| 176 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 177 |
+
pub use core::sync::atomic;
|
| 178 |
+
|
| 179 |
+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
|
| 180 |
+
pub use alloc_crate::sync::UniqueArc;
|
| 181 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 182 |
+
pub use alloc_crate::sync::{Arc, Weak};
|
| 183 |
+
|
| 184 |
+
#[unstable(feature = "mpmc_channel", issue = "126840")]
|
| 185 |
+
pub mod mpmc;
|
| 186 |
+
pub mod mpsc;
|
| 187 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 188 |
+
pub mod oneshot;
|
| 189 |
+
|
| 190 |
+
pub(crate) mod once; // `pub(crate)` for the `sys::sync::once` implementations and `LazyLock`.
|
| 191 |
+
|
| 192 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 193 |
+
pub use self::once::{Once, OnceState};
|
| 194 |
+
|
| 195 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 196 |
+
#[doc(inline)]
|
| 197 |
+
#[expect(deprecated)]
|
| 198 |
+
pub use self::once::ONCE_INIT;
|
| 199 |
+
|
| 200 |
+
mod barrier;
|
| 201 |
+
mod lazy_lock;
|
| 202 |
+
mod once_lock;
|
| 203 |
+
mod reentrant_lock;
|
| 204 |
+
|
| 205 |
+
// These exist only in one flavor: no poisoning.
|
| 206 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 207 |
+
pub use self::barrier::{Barrier, BarrierWaitResult};
|
| 208 |
+
#[stable(feature = "lazy_cell", since = "1.80.0")]
|
| 209 |
+
pub use self::lazy_lock::LazyLock;
|
| 210 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 211 |
+
pub use self::once_lock::OnceLock;
|
| 212 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 213 |
+
pub use self::reentrant_lock::{ReentrantLock, ReentrantLockGuard};
|
| 214 |
+
|
| 215 |
+
// Note: in the future we will change the default version in `std::sync` to the non-poisoning
|
| 216 |
+
// version over an edition.
|
| 217 |
+
// See https://github.com/rust-lang/rust/issues/134645#issuecomment-3324577500 for more details.
|
| 218 |
+
|
| 219 |
+
#[unstable(feature = "sync_nonpoison", issue = "134645")]
|
| 220 |
+
pub mod nonpoison;
|
| 221 |
+
#[unstable(feature = "sync_poison_mod", issue = "134646")]
|
| 222 |
+
pub mod poison;
|
| 223 |
+
|
| 224 |
+
// FIXME(sync_poison_mod): remove all `#[doc(inline)]` once the modules are stabilized.
|
| 225 |
+
|
| 226 |
+
// These exist only with poisoning.
|
| 227 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 228 |
+
#[doc(inline)]
|
| 229 |
+
pub use self::poison::{LockResult, PoisonError};
|
| 230 |
+
|
| 231 |
+
// These exist in both flavors: with and without poisoning.
|
| 232 |
+
// The historical default is the version with poisoning.
|
| 233 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 234 |
+
#[doc(inline)]
|
| 235 |
+
pub use self::poison::{
|
| 236 |
+
TryLockError, TryLockResult,
|
| 237 |
+
Mutex, MutexGuard,
|
| 238 |
+
RwLock, RwLockReadGuard, RwLockWriteGuard,
|
| 239 |
+
Condvar,
|
| 240 |
+
};
|
| 241 |
+
|
| 242 |
+
#[unstable(feature = "mapped_lock_guards", issue = "117108")]
|
| 243 |
+
#[doc(inline)]
|
| 244 |
+
pub use self::poison::{MappedMutexGuard, MappedRwLockReadGuard, MappedRwLockWriteGuard};
|
| 245 |
+
|
| 246 |
+
/// A type indicating whether a timed wait on a condition variable returned
|
| 247 |
+
/// due to a time out or not.
|
| 248 |
+
///
|
| 249 |
+
/// It is returned by the [`wait_timeout`] method.
|
| 250 |
+
///
|
| 251 |
+
/// [`wait_timeout`]: Condvar::wait_timeout
|
| 252 |
+
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
| 253 |
+
#[stable(feature = "wait_timeout", since = "1.5.0")]
|
| 254 |
+
pub struct WaitTimeoutResult(bool);
|
| 255 |
+
|
| 256 |
+
impl WaitTimeoutResult {
|
| 257 |
+
/// Returns `true` if the wait was known to have timed out.
|
| 258 |
+
///
|
| 259 |
+
/// # Examples
|
| 260 |
+
///
|
| 261 |
+
/// This example spawns a thread which will sleep 20 milliseconds before
|
| 262 |
+
/// updating a boolean value and then notifying the condvar.
|
| 263 |
+
///
|
| 264 |
+
/// The main thread will wait with a 10 millisecond timeout on the condvar
|
| 265 |
+
/// and will leave the loop upon timeout.
|
| 266 |
+
///
|
| 267 |
+
/// ```
|
| 268 |
+
/// use std::sync::{Arc, Condvar, Mutex};
|
| 269 |
+
/// use std::thread;
|
| 270 |
+
/// use std::time::Duration;
|
| 271 |
+
///
|
| 272 |
+
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
| 273 |
+
/// let pair2 = Arc::clone(&pair);
|
| 274 |
+
///
|
| 275 |
+
/// # let handle =
|
| 276 |
+
/// thread::spawn(move || {
|
| 277 |
+
/// let (lock, cvar) = &*pair2;
|
| 278 |
+
///
|
| 279 |
+
/// // Let's wait 20 milliseconds before notifying the condvar.
|
| 280 |
+
/// thread::sleep(Duration::from_millis(20));
|
| 281 |
+
///
|
| 282 |
+
/// let mut started = lock.lock().unwrap();
|
| 283 |
+
/// // We update the boolean value.
|
| 284 |
+
/// *started = true;
|
| 285 |
+
/// cvar.notify_one();
|
| 286 |
+
/// });
|
| 287 |
+
///
|
| 288 |
+
/// // Wait for the thread to start up.
|
| 289 |
+
/// let (lock, cvar) = &*pair;
|
| 290 |
+
/// loop {
|
| 291 |
+
/// // Let's put a timeout on the condvar's wait.
|
| 292 |
+
/// let result = cvar.wait_timeout(lock.lock().unwrap(), Duration::from_millis(10)).unwrap();
|
| 293 |
+
/// // 10 milliseconds have passed.
|
| 294 |
+
/// if result.1.timed_out() {
|
| 295 |
+
/// // timed out now and we can leave.
|
| 296 |
+
/// break
|
| 297 |
+
/// }
|
| 298 |
+
/// }
|
| 299 |
+
/// # // Prevent leaks for Miri.
|
| 300 |
+
/// # let _ = handle.join();
|
| 301 |
+
/// ```
|
| 302 |
+
#[must_use]
|
| 303 |
+
#[stable(feature = "wait_timeout", since = "1.5.0")]
|
| 304 |
+
pub fn timed_out(&self) -> bool {
|
| 305 |
+
self.0
|
| 306 |
+
}
|
| 307 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/mpsc.rs
ADDED
|
@@ -0,0 +1,1214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Multi-producer, single-consumer FIFO queue communication primitives.
|
| 2 |
+
//!
|
| 3 |
+
//! This module provides message-based communication over channels, concretely
|
| 4 |
+
//! defined among three types:
|
| 5 |
+
//!
|
| 6 |
+
//! * [`Sender`]
|
| 7 |
+
//! * [`SyncSender`]
|
| 8 |
+
//! * [`Receiver`]
|
| 9 |
+
//!
|
| 10 |
+
//! A [`Sender`] or [`SyncSender`] is used to send data to a [`Receiver`]. Both
|
| 11 |
+
//! senders are clone-able (multi-producer) such that many threads can send
|
| 12 |
+
//! simultaneously to one receiver (single-consumer).
|
| 13 |
+
//!
|
| 14 |
+
//! These channels come in two flavors:
|
| 15 |
+
//!
|
| 16 |
+
//! 1. An asynchronous, infinitely buffered channel. The [`channel`] function
|
| 17 |
+
//! will return a `(Sender, Receiver)` tuple where all sends will be
|
| 18 |
+
//! **asynchronous** (they never block). The channel conceptually has an
|
| 19 |
+
//! infinite buffer.
|
| 20 |
+
//!
|
| 21 |
+
//! 2. A synchronous, bounded channel. The [`sync_channel`] function will
|
| 22 |
+
//! return a `(SyncSender, Receiver)` tuple where the storage for pending
|
| 23 |
+
//! messages is a pre-allocated buffer of a fixed size. All sends will be
|
| 24 |
+
//! **synchronous** by blocking until there is buffer space available. Note
|
| 25 |
+
//! that a bound of 0 is allowed, causing the channel to become a "rendezvous"
|
| 26 |
+
//! channel where each sender atomically hands off a message to a receiver.
|
| 27 |
+
//!
|
| 28 |
+
//! [`send`]: Sender::send
|
| 29 |
+
//!
|
| 30 |
+
//! ## Disconnection
|
| 31 |
+
//!
|
| 32 |
+
//! The send and receive operations on channels will all return a [`Result`]
|
| 33 |
+
//! indicating whether the operation succeeded or not. An unsuccessful operation
|
| 34 |
+
//! is normally indicative of the other half of a channel having "hung up" by
|
| 35 |
+
//! being dropped in its corresponding thread.
|
| 36 |
+
//!
|
| 37 |
+
//! Once half of a channel has been deallocated, most operations can no longer
|
| 38 |
+
//! continue to make progress, so [`Err`] will be returned. Many applications
|
| 39 |
+
//! will continue to [`unwrap`] the results returned from this module,
|
| 40 |
+
//! instigating a propagation of failure among threads if one unexpectedly dies.
|
| 41 |
+
//!
|
| 42 |
+
//! [`unwrap`]: Result::unwrap
|
| 43 |
+
//!
|
| 44 |
+
//! # Examples
|
| 45 |
+
//!
|
| 46 |
+
//! Simple usage:
|
| 47 |
+
//!
|
| 48 |
+
//! ```
|
| 49 |
+
//! use std::thread;
|
| 50 |
+
//! use std::sync::mpsc::channel;
|
| 51 |
+
//!
|
| 52 |
+
//! // Create a simple streaming channel
|
| 53 |
+
//! let (tx, rx) = channel();
|
| 54 |
+
//! thread::spawn(move || {
|
| 55 |
+
//! tx.send(10).unwrap();
|
| 56 |
+
//! });
|
| 57 |
+
//! assert_eq!(rx.recv().unwrap(), 10);
|
| 58 |
+
//! ```
|
| 59 |
+
//!
|
| 60 |
+
//! Shared usage:
|
| 61 |
+
//!
|
| 62 |
+
//! ```
|
| 63 |
+
//! use std::thread;
|
| 64 |
+
//! use std::sync::mpsc::channel;
|
| 65 |
+
//!
|
| 66 |
+
//! // Create a shared channel that can be sent along from many threads
|
| 67 |
+
//! // where tx is the sending half (tx for transmission), and rx is the receiving
|
| 68 |
+
//! // half (rx for receiving).
|
| 69 |
+
//! let (tx, rx) = channel();
|
| 70 |
+
//! for i in 0..10 {
|
| 71 |
+
//! let tx = tx.clone();
|
| 72 |
+
//! thread::spawn(move || {
|
| 73 |
+
//! tx.send(i).unwrap();
|
| 74 |
+
//! });
|
| 75 |
+
//! }
|
| 76 |
+
//!
|
| 77 |
+
//! for _ in 0..10 {
|
| 78 |
+
//! let j = rx.recv().unwrap();
|
| 79 |
+
//! assert!(0 <= j && j < 10);
|
| 80 |
+
//! }
|
| 81 |
+
//! ```
|
| 82 |
+
//!
|
| 83 |
+
//! Propagating panics:
|
| 84 |
+
//!
|
| 85 |
+
//! ```
|
| 86 |
+
//! use std::sync::mpsc::channel;
|
| 87 |
+
//!
|
| 88 |
+
//! // The call to recv() will return an error because the channel has already
|
| 89 |
+
//! // hung up (or been deallocated)
|
| 90 |
+
//! let (tx, rx) = channel::<i32>();
|
| 91 |
+
//! drop(tx);
|
| 92 |
+
//! assert!(rx.recv().is_err());
|
| 93 |
+
//! ```
|
| 94 |
+
//!
|
| 95 |
+
//! Synchronous channels:
|
| 96 |
+
//!
|
| 97 |
+
//! ```
|
| 98 |
+
//! use std::thread;
|
| 99 |
+
//! use std::sync::mpsc::sync_channel;
|
| 100 |
+
//!
|
| 101 |
+
//! let (tx, rx) = sync_channel::<i32>(0);
|
| 102 |
+
//! thread::spawn(move || {
|
| 103 |
+
//! // This will wait for the parent thread to start receiving
|
| 104 |
+
//! tx.send(53).unwrap();
|
| 105 |
+
//! });
|
| 106 |
+
//! rx.recv().unwrap();
|
| 107 |
+
//! ```
|
| 108 |
+
//!
|
| 109 |
+
//! Unbounded receive loop:
|
| 110 |
+
//!
|
| 111 |
+
//! ```
|
| 112 |
+
//! use std::sync::mpsc::sync_channel;
|
| 113 |
+
//! use std::thread;
|
| 114 |
+
//!
|
| 115 |
+
//! let (tx, rx) = sync_channel(3);
|
| 116 |
+
//!
|
| 117 |
+
//! for _ in 0..3 {
|
| 118 |
+
//! // It would be the same without thread and clone here
|
| 119 |
+
//! // since there will still be one `tx` left.
|
| 120 |
+
//! let tx = tx.clone();
|
| 121 |
+
//! // cloned tx dropped within thread
|
| 122 |
+
//! thread::spawn(move || tx.send("ok").unwrap());
|
| 123 |
+
//! }
|
| 124 |
+
//!
|
| 125 |
+
//! // Drop the last sender to stop `rx` waiting for message.
|
| 126 |
+
//! // The program will not complete if we comment this out.
|
| 127 |
+
//! // **All** `tx` needs to be dropped for `rx` to have `Err`.
|
| 128 |
+
//! drop(tx);
|
| 129 |
+
//!
|
| 130 |
+
//! // Unbounded receiver waiting for all senders to complete.
|
| 131 |
+
//! while let Ok(msg) = rx.recv() {
|
| 132 |
+
//! println!("{msg}");
|
| 133 |
+
//! }
|
| 134 |
+
//!
|
| 135 |
+
//! println!("completed");
|
| 136 |
+
//! ```
|
| 137 |
+
|
| 138 |
+
#![stable(feature = "rust1", since = "1.0.0")]
|
| 139 |
+
|
| 140 |
+
// MPSC channels are built as a wrapper around MPMC channels, which
|
| 141 |
+
// were ported from the `crossbeam-channel` crate. MPMC channels are
|
| 142 |
+
// not exposed publicly, but if you are curious about the implementation,
|
| 143 |
+
// that's where everything is.
|
| 144 |
+
|
| 145 |
+
use crate::sync::mpmc;
|
| 146 |
+
use crate::time::{Duration, Instant};
|
| 147 |
+
use crate::{error, fmt};
|
| 148 |
+
|
| 149 |
+
/// The receiving half of Rust's [`channel`] (or [`sync_channel`]) type.
|
| 150 |
+
/// This half can only be owned by one thread.
|
| 151 |
+
///
|
| 152 |
+
/// Messages sent to the channel can be retrieved using [`recv`].
|
| 153 |
+
///
|
| 154 |
+
/// [`recv`]: Receiver::recv
|
| 155 |
+
///
|
| 156 |
+
/// # Examples
|
| 157 |
+
///
|
| 158 |
+
/// ```rust
|
| 159 |
+
/// use std::sync::mpsc::channel;
|
| 160 |
+
/// use std::thread;
|
| 161 |
+
/// use std::time::Duration;
|
| 162 |
+
///
|
| 163 |
+
/// let (send, recv) = channel();
|
| 164 |
+
///
|
| 165 |
+
/// thread::spawn(move || {
|
| 166 |
+
/// send.send("Hello world!").unwrap();
|
| 167 |
+
/// thread::sleep(Duration::from_secs(2)); // block for two seconds
|
| 168 |
+
/// send.send("Delayed for 2 seconds").unwrap();
|
| 169 |
+
/// });
|
| 170 |
+
///
|
| 171 |
+
/// println!("{}", recv.recv().unwrap()); // Received immediately
|
| 172 |
+
/// println!("Waiting...");
|
| 173 |
+
/// println!("{}", recv.recv().unwrap()); // Received after 2 seconds
|
| 174 |
+
/// ```
|
| 175 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 176 |
+
#[cfg_attr(not(test), rustc_diagnostic_item = "Receiver")]
|
| 177 |
+
pub struct Receiver<T> {
|
| 178 |
+
inner: mpmc::Receiver<T>,
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
// The receiver port can be sent from place to place, so long as it
|
| 182 |
+
// is not used to receive non-sendable things.
|
| 183 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 184 |
+
unsafe impl<T: Send> Send for Receiver<T> {}
|
| 185 |
+
|
| 186 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 187 |
+
impl<T> !Sync for Receiver<T> {}
|
| 188 |
+
|
| 189 |
+
/// An iterator over messages on a [`Receiver`], created by [`iter`].
|
| 190 |
+
///
|
| 191 |
+
/// This iterator will block whenever [`next`] is called,
|
| 192 |
+
/// waiting for a new message, and [`None`] will be returned
|
| 193 |
+
/// when the corresponding channel has hung up.
|
| 194 |
+
///
|
| 195 |
+
/// [`iter`]: Receiver::iter
|
| 196 |
+
/// [`next`]: Iterator::next
|
| 197 |
+
///
|
| 198 |
+
/// # Examples
|
| 199 |
+
///
|
| 200 |
+
/// ```rust
|
| 201 |
+
/// use std::sync::mpsc::channel;
|
| 202 |
+
/// use std::thread;
|
| 203 |
+
///
|
| 204 |
+
/// let (send, recv) = channel();
|
| 205 |
+
///
|
| 206 |
+
/// thread::spawn(move || {
|
| 207 |
+
/// send.send(1u8).unwrap();
|
| 208 |
+
/// send.send(2u8).unwrap();
|
| 209 |
+
/// send.send(3u8).unwrap();
|
| 210 |
+
/// });
|
| 211 |
+
///
|
| 212 |
+
/// for x in recv.iter() {
|
| 213 |
+
/// println!("Got: {x}");
|
| 214 |
+
/// }
|
| 215 |
+
/// ```
|
| 216 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 217 |
+
#[derive(Debug)]
|
| 218 |
+
pub struct Iter<'a, T: 'a> {
|
| 219 |
+
rx: &'a Receiver<T>,
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
/// An iterator that attempts to yield all pending values for a [`Receiver`],
|
| 223 |
+
/// created by [`try_iter`].
|
| 224 |
+
///
|
| 225 |
+
/// [`None`] will be returned when there are no pending values remaining or
|
| 226 |
+
/// if the corresponding channel has hung up.
|
| 227 |
+
///
|
| 228 |
+
/// This iterator will never block the caller in order to wait for data to
|
| 229 |
+
/// become available. Instead, it will return [`None`].
|
| 230 |
+
///
|
| 231 |
+
/// [`try_iter`]: Receiver::try_iter
|
| 232 |
+
///
|
| 233 |
+
/// # Examples
|
| 234 |
+
///
|
| 235 |
+
/// ```rust
|
| 236 |
+
/// use std::sync::mpsc::channel;
|
| 237 |
+
/// use std::thread;
|
| 238 |
+
/// use std::time::Duration;
|
| 239 |
+
///
|
| 240 |
+
/// let (sender, receiver) = channel();
|
| 241 |
+
///
|
| 242 |
+
/// // Nothing is in the buffer yet
|
| 243 |
+
/// assert!(receiver.try_iter().next().is_none());
|
| 244 |
+
/// println!("Nothing in the buffer...");
|
| 245 |
+
///
|
| 246 |
+
/// thread::spawn(move || {
|
| 247 |
+
/// sender.send(1).unwrap();
|
| 248 |
+
/// sender.send(2).unwrap();
|
| 249 |
+
/// sender.send(3).unwrap();
|
| 250 |
+
/// });
|
| 251 |
+
///
|
| 252 |
+
/// println!("Going to sleep...");
|
| 253 |
+
/// thread::sleep(Duration::from_secs(2)); // block for two seconds
|
| 254 |
+
///
|
| 255 |
+
/// for x in receiver.try_iter() {
|
| 256 |
+
/// println!("Got: {x}");
|
| 257 |
+
/// }
|
| 258 |
+
/// ```
|
| 259 |
+
#[stable(feature = "receiver_try_iter", since = "1.15.0")]
|
| 260 |
+
#[derive(Debug)]
|
| 261 |
+
pub struct TryIter<'a, T: 'a> {
|
| 262 |
+
rx: &'a Receiver<T>,
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
/// An owning iterator over messages on a [`Receiver`],
|
| 266 |
+
/// created by [`into_iter`].
|
| 267 |
+
///
|
| 268 |
+
/// This iterator will block whenever [`next`]
|
| 269 |
+
/// is called, waiting for a new message, and [`None`] will be
|
| 270 |
+
/// returned if the corresponding channel has hung up.
|
| 271 |
+
///
|
| 272 |
+
/// [`into_iter`]: Receiver::into_iter
|
| 273 |
+
/// [`next`]: Iterator::next
|
| 274 |
+
///
|
| 275 |
+
/// # Examples
|
| 276 |
+
///
|
| 277 |
+
/// ```rust
|
| 278 |
+
/// use std::sync::mpsc::channel;
|
| 279 |
+
/// use std::thread;
|
| 280 |
+
///
|
| 281 |
+
/// let (send, recv) = channel();
|
| 282 |
+
///
|
| 283 |
+
/// thread::spawn(move || {
|
| 284 |
+
/// send.send(1u8).unwrap();
|
| 285 |
+
/// send.send(2u8).unwrap();
|
| 286 |
+
/// send.send(3u8).unwrap();
|
| 287 |
+
/// });
|
| 288 |
+
///
|
| 289 |
+
/// for x in recv.into_iter() {
|
| 290 |
+
/// println!("Got: {x}");
|
| 291 |
+
/// }
|
| 292 |
+
/// ```
|
| 293 |
+
#[stable(feature = "receiver_into_iter", since = "1.1.0")]
|
| 294 |
+
#[derive(Debug)]
|
| 295 |
+
pub struct IntoIter<T> {
|
| 296 |
+
rx: Receiver<T>,
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
/// The sending-half of Rust's asynchronous [`channel`] type.
|
| 300 |
+
///
|
| 301 |
+
/// Messages can be sent through this channel with [`send`].
|
| 302 |
+
///
|
| 303 |
+
/// Note: all senders (the original and its clones) need to be dropped for the receiver
|
| 304 |
+
/// to stop blocking to receive messages with [`Receiver::recv`].
|
| 305 |
+
///
|
| 306 |
+
/// [`send`]: Sender::send
|
| 307 |
+
///
|
| 308 |
+
/// # Examples
|
| 309 |
+
///
|
| 310 |
+
/// ```rust
|
| 311 |
+
/// use std::sync::mpsc::channel;
|
| 312 |
+
/// use std::thread;
|
| 313 |
+
///
|
| 314 |
+
/// let (sender, receiver) = channel();
|
| 315 |
+
/// let sender2 = sender.clone();
|
| 316 |
+
///
|
| 317 |
+
/// // First thread owns sender
|
| 318 |
+
/// thread::spawn(move || {
|
| 319 |
+
/// sender.send(1).unwrap();
|
| 320 |
+
/// });
|
| 321 |
+
///
|
| 322 |
+
/// // Second thread owns sender2
|
| 323 |
+
/// thread::spawn(move || {
|
| 324 |
+
/// sender2.send(2).unwrap();
|
| 325 |
+
/// });
|
| 326 |
+
///
|
| 327 |
+
/// let msg = receiver.recv().unwrap();
|
| 328 |
+
/// let msg2 = receiver.recv().unwrap();
|
| 329 |
+
///
|
| 330 |
+
/// assert_eq!(3, msg + msg2);
|
| 331 |
+
/// ```
|
| 332 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 333 |
+
pub struct Sender<T> {
|
| 334 |
+
inner: mpmc::Sender<T>,
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
// The send port can be sent from place to place, so long as it
|
| 338 |
+
// is not used to send non-sendable things.
|
| 339 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 340 |
+
unsafe impl<T: Send> Send for Sender<T> {}
|
| 341 |
+
|
| 342 |
+
#[stable(feature = "mpsc_sender_sync", since = "1.72.0")]
|
| 343 |
+
unsafe impl<T: Send> Sync for Sender<T> {}
|
| 344 |
+
|
| 345 |
+
/// The sending-half of Rust's synchronous [`sync_channel`] type.
|
| 346 |
+
///
|
| 347 |
+
/// Messages can be sent through this channel with [`send`] or [`try_send`].
|
| 348 |
+
///
|
| 349 |
+
/// [`send`] will block if there is no space in the internal buffer.
|
| 350 |
+
///
|
| 351 |
+
/// [`send`]: SyncSender::send
|
| 352 |
+
/// [`try_send`]: SyncSender::try_send
|
| 353 |
+
///
|
| 354 |
+
/// # Examples
|
| 355 |
+
///
|
| 356 |
+
/// ```rust
|
| 357 |
+
/// use std::sync::mpsc::sync_channel;
|
| 358 |
+
/// use std::thread;
|
| 359 |
+
///
|
| 360 |
+
/// // Create a sync_channel with buffer size 2
|
| 361 |
+
/// let (sync_sender, receiver) = sync_channel(2);
|
| 362 |
+
/// let sync_sender2 = sync_sender.clone();
|
| 363 |
+
///
|
| 364 |
+
/// // First thread owns sync_sender
|
| 365 |
+
/// thread::spawn(move || {
|
| 366 |
+
/// sync_sender.send(1).unwrap();
|
| 367 |
+
/// sync_sender.send(2).unwrap();
|
| 368 |
+
/// });
|
| 369 |
+
///
|
| 370 |
+
/// // Second thread owns sync_sender2
|
| 371 |
+
/// thread::spawn(move || {
|
| 372 |
+
/// sync_sender2.send(3).unwrap();
|
| 373 |
+
/// // thread will now block since the buffer is full
|
| 374 |
+
/// println!("Thread unblocked!");
|
| 375 |
+
/// });
|
| 376 |
+
///
|
| 377 |
+
/// let mut msg;
|
| 378 |
+
///
|
| 379 |
+
/// msg = receiver.recv().unwrap();
|
| 380 |
+
/// println!("message {msg} received");
|
| 381 |
+
///
|
| 382 |
+
/// // "Thread unblocked!" will be printed now
|
| 383 |
+
///
|
| 384 |
+
/// msg = receiver.recv().unwrap();
|
| 385 |
+
/// println!("message {msg} received");
|
| 386 |
+
///
|
| 387 |
+
/// msg = receiver.recv().unwrap();
|
| 388 |
+
///
|
| 389 |
+
/// println!("message {msg} received");
|
| 390 |
+
/// ```
|
| 391 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 392 |
+
pub struct SyncSender<T> {
|
| 393 |
+
inner: mpmc::Sender<T>,
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 397 |
+
unsafe impl<T: Send> Send for SyncSender<T> {}
|
| 398 |
+
|
| 399 |
+
/// An error returned from the [`Sender::send`] or [`SyncSender::send`]
|
| 400 |
+
/// function on **channel**s.
|
| 401 |
+
///
|
| 402 |
+
/// A **send** operation can only fail if the receiving end of a channel is
|
| 403 |
+
/// disconnected, implying that the data could never be received. The error
|
| 404 |
+
/// contains the data being sent as a payload so it can be recovered.
|
| 405 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 406 |
+
#[derive(PartialEq, Eq, Clone, Copy)]
|
| 407 |
+
pub struct SendError<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
|
| 408 |
+
|
| 409 |
+
/// An error returned from the [`recv`] function on a [`Receiver`].
|
| 410 |
+
///
|
| 411 |
+
/// The [`recv`] operation can only fail if the sending half of a
|
| 412 |
+
/// [`channel`] (or [`sync_channel`]) is disconnected, implying that no further
|
| 413 |
+
/// messages will ever be received.
|
| 414 |
+
///
|
| 415 |
+
/// [`recv`]: Receiver::recv
|
| 416 |
+
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
|
| 417 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 418 |
+
pub struct RecvError;
|
| 419 |
+
|
| 420 |
+
/// This enumeration is the list of the possible reasons that [`try_recv`] could
|
| 421 |
+
/// not return data when called. This can occur with both a [`channel`] and
|
| 422 |
+
/// a [`sync_channel`].
|
| 423 |
+
///
|
| 424 |
+
/// [`try_recv`]: Receiver::try_recv
|
| 425 |
+
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
|
| 426 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 427 |
+
pub enum TryRecvError {
|
| 428 |
+
/// This **channel** is currently empty, but the **Sender**(s) have not yet
|
| 429 |
+
/// disconnected, so data may yet become available.
|
| 430 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 431 |
+
Empty,
|
| 432 |
+
|
| 433 |
+
/// The **channel**'s sending half has become disconnected, and there will
|
| 434 |
+
/// never be any more data received on it.
|
| 435 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 436 |
+
Disconnected,
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
/// This enumeration is the list of possible errors that made [`recv_timeout`]
|
| 440 |
+
/// unable to return data when called. This can occur with both a [`channel`] and
|
| 441 |
+
/// a [`sync_channel`].
|
| 442 |
+
///
|
| 443 |
+
/// [`recv_timeout`]: Receiver::recv_timeout
|
| 444 |
+
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
|
| 445 |
+
#[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
|
| 446 |
+
pub enum RecvTimeoutError {
|
| 447 |
+
/// This **channel** is currently empty, but the **Sender**(s) have not yet
|
| 448 |
+
/// disconnected, so data may yet become available.
|
| 449 |
+
#[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
|
| 450 |
+
Timeout,
|
| 451 |
+
/// The **channel**'s sending half has become disconnected, and there will
|
| 452 |
+
/// never be any more data received on it.
|
| 453 |
+
#[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
|
| 454 |
+
Disconnected,
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
/// This enumeration is the list of the possible error outcomes for the
|
| 458 |
+
/// [`try_send`] method.
|
| 459 |
+
///
|
| 460 |
+
/// [`try_send`]: SyncSender::try_send
|
| 461 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 462 |
+
#[derive(PartialEq, Eq, Clone, Copy)]
|
| 463 |
+
pub enum TrySendError<T> {
|
| 464 |
+
/// The data could not be sent on the [`sync_channel`] because it would require that
|
| 465 |
+
/// the callee block to send the data.
|
| 466 |
+
///
|
| 467 |
+
/// If this is a buffered channel, then the buffer is full at this time. If
|
| 468 |
+
/// this is not a buffered channel, then there is no [`Receiver`] available to
|
| 469 |
+
/// acquire the data.
|
| 470 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 471 |
+
Full(#[stable(feature = "rust1", since = "1.0.0")] T),
|
| 472 |
+
|
| 473 |
+
/// This [`sync_channel`]'s receiving half has disconnected, so the data could not be
|
| 474 |
+
/// sent. The data is returned back to the callee in this case.
|
| 475 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 476 |
+
Disconnected(#[stable(feature = "rust1", since = "1.0.0")] T),
|
| 477 |
+
}
|
| 478 |
+
|
| 479 |
+
/// Creates a new asynchronous channel, returning the sender/receiver halves.
|
| 480 |
+
///
|
| 481 |
+
/// All data sent on the [`Sender`] will become available on the [`Receiver`] in
|
| 482 |
+
/// the same order as it was sent, and no [`send`] will block the calling thread
|
| 483 |
+
/// (this channel has an "infinite buffer", unlike [`sync_channel`], which will
|
| 484 |
+
/// block after its buffer limit is reached). [`recv`] will block until a message
|
| 485 |
+
/// is available while there is at least one [`Sender`] alive (including clones).
|
| 486 |
+
///
|
| 487 |
+
/// The [`Sender`] can be cloned to [`send`] to the same channel multiple times, but
|
| 488 |
+
/// only one [`Receiver`] is supported.
|
| 489 |
+
///
|
| 490 |
+
/// If the [`Receiver`] is disconnected while trying to [`send`] with the
|
| 491 |
+
/// [`Sender`], the [`send`] method will return a [`SendError`]. Similarly, if the
|
| 492 |
+
/// [`Sender`] is disconnected while trying to [`recv`], the [`recv`] method will
|
| 493 |
+
/// return a [`RecvError`].
|
| 494 |
+
///
|
| 495 |
+
/// [`send`]: Sender::send
|
| 496 |
+
/// [`recv`]: Receiver::recv
|
| 497 |
+
///
|
| 498 |
+
/// # Examples
|
| 499 |
+
///
|
| 500 |
+
/// ```
|
| 501 |
+
/// use std::sync::mpsc::channel;
|
| 502 |
+
/// use std::thread;
|
| 503 |
+
///
|
| 504 |
+
/// let (sender, receiver) = channel();
|
| 505 |
+
///
|
| 506 |
+
/// // Spawn off an expensive computation
|
| 507 |
+
/// thread::spawn(move || {
|
| 508 |
+
/// # fn expensive_computation() {}
|
| 509 |
+
/// sender.send(expensive_computation()).unwrap();
|
| 510 |
+
/// });
|
| 511 |
+
///
|
| 512 |
+
/// // Do some useful work for a while
|
| 513 |
+
///
|
| 514 |
+
/// // Let's see what that answer was
|
| 515 |
+
/// println!("{:?}", receiver.recv().unwrap());
|
| 516 |
+
/// ```
|
| 517 |
+
#[must_use]
|
| 518 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 519 |
+
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
|
| 520 |
+
let (tx, rx) = mpmc::channel();
|
| 521 |
+
(Sender { inner: tx }, Receiver { inner: rx })
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
/// Creates a new synchronous, bounded channel.
|
| 525 |
+
///
|
| 526 |
+
/// All data sent on the [`SyncSender`] will become available on the [`Receiver`]
|
| 527 |
+
/// in the same order as it was sent. Like asynchronous [`channel`]s, the
|
| 528 |
+
/// [`Receiver`] will block until a message becomes available. `sync_channel`
|
| 529 |
+
/// differs greatly in the semantics of the sender, however.
|
| 530 |
+
///
|
| 531 |
+
/// This channel has an internal buffer on which messages will be queued.
|
| 532 |
+
/// `bound` specifies the buffer size. When the internal buffer becomes full,
|
| 533 |
+
/// future sends will *block* waiting for the buffer to open up. Note that a
|
| 534 |
+
/// buffer size of 0 is valid, in which case this becomes "rendezvous channel"
|
| 535 |
+
/// where each [`send`] will not return until a [`recv`] is paired with it.
|
| 536 |
+
///
|
| 537 |
+
/// The [`SyncSender`] can be cloned to [`send`] to the same channel multiple
|
| 538 |
+
/// times, but only one [`Receiver`] is supported.
|
| 539 |
+
///
|
| 540 |
+
/// Like asynchronous channels, if the [`Receiver`] is disconnected while trying
|
| 541 |
+
/// to [`send`] with the [`SyncSender`], the [`send`] method will return a
|
| 542 |
+
/// [`SendError`]. Similarly, If the [`SyncSender`] is disconnected while trying
|
| 543 |
+
/// to [`recv`], the [`recv`] method will return a [`RecvError`].
|
| 544 |
+
///
|
| 545 |
+
/// [`send`]: SyncSender::send
|
| 546 |
+
/// [`recv`]: Receiver::recv
|
| 547 |
+
///
|
| 548 |
+
/// # Examples
|
| 549 |
+
///
|
| 550 |
+
/// ```
|
| 551 |
+
/// use std::sync::mpsc::sync_channel;
|
| 552 |
+
/// use std::thread;
|
| 553 |
+
///
|
| 554 |
+
/// let (sender, receiver) = sync_channel(1);
|
| 555 |
+
///
|
| 556 |
+
/// // this returns immediately
|
| 557 |
+
/// sender.send(1).unwrap();
|
| 558 |
+
///
|
| 559 |
+
/// thread::spawn(move || {
|
| 560 |
+
/// // this will block until the previous message has been received
|
| 561 |
+
/// sender.send(2).unwrap();
|
| 562 |
+
/// });
|
| 563 |
+
///
|
| 564 |
+
/// assert_eq!(receiver.recv().unwrap(), 1);
|
| 565 |
+
/// assert_eq!(receiver.recv().unwrap(), 2);
|
| 566 |
+
/// ```
|
| 567 |
+
#[must_use]
|
| 568 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 569 |
+
pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Receiver<T>) {
|
| 570 |
+
let (tx, rx) = mpmc::sync_channel(bound);
|
| 571 |
+
(SyncSender { inner: tx }, Receiver { inner: rx })
|
| 572 |
+
}
|
| 573 |
+
|
| 574 |
+
////////////////////////////////////////////////////////////////////////////////
|
| 575 |
+
// Sender
|
| 576 |
+
////////////////////////////////////////////////////////////////////////////////
|
| 577 |
+
|
| 578 |
+
impl<T> Sender<T> {
|
| 579 |
+
/// Attempts to send a value on this channel, returning it back if it could
|
| 580 |
+
/// not be sent.
|
| 581 |
+
///
|
| 582 |
+
/// A successful send occurs when it is determined that the other end of
|
| 583 |
+
/// the channel has not hung up already. An unsuccessful send would be one
|
| 584 |
+
/// where the corresponding receiver has already been deallocated. Note
|
| 585 |
+
/// that a return value of [`Err`] means that the data will never be
|
| 586 |
+
/// received, but a return value of [`Ok`] does *not* mean that the data
|
| 587 |
+
/// will be received. It is possible for the corresponding receiver to
|
| 588 |
+
/// hang up immediately after this function returns [`Ok`].
|
| 589 |
+
///
|
| 590 |
+
/// This method will never block the current thread.
|
| 591 |
+
///
|
| 592 |
+
/// # Examples
|
| 593 |
+
///
|
| 594 |
+
/// ```
|
| 595 |
+
/// use std::sync::mpsc::channel;
|
| 596 |
+
///
|
| 597 |
+
/// let (tx, rx) = channel();
|
| 598 |
+
///
|
| 599 |
+
/// // This send is always successful
|
| 600 |
+
/// tx.send(1).unwrap();
|
| 601 |
+
///
|
| 602 |
+
/// // This send will fail because the receiver is gone
|
| 603 |
+
/// drop(rx);
|
| 604 |
+
/// assert_eq!(tx.send(1).unwrap_err().0, 1);
|
| 605 |
+
/// ```
|
| 606 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 607 |
+
pub fn send(&self, t: T) -> Result<(), SendError<T>> {
|
| 608 |
+
self.inner.send(t)
|
| 609 |
+
}
|
| 610 |
+
}
|
| 611 |
+
|
| 612 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 613 |
+
impl<T> Clone for Sender<T> {
|
| 614 |
+
/// Clone a sender to send to other threads.
|
| 615 |
+
///
|
| 616 |
+
/// Note, be aware of the lifetime of the sender because all senders
|
| 617 |
+
/// (including the original) need to be dropped in order for
|
| 618 |
+
/// [`Receiver::recv`] to stop blocking.
|
| 619 |
+
fn clone(&self) -> Sender<T> {
|
| 620 |
+
Sender { inner: self.inner.clone() }
|
| 621 |
+
}
|
| 622 |
+
}
|
| 623 |
+
|
| 624 |
+
#[stable(feature = "mpsc_debug", since = "1.8.0")]
|
| 625 |
+
impl<T> fmt::Debug for Sender<T> {
|
| 626 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 627 |
+
f.debug_struct("Sender").finish_non_exhaustive()
|
| 628 |
+
}
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
////////////////////////////////////////////////////////////////////////////////
|
| 632 |
+
// SyncSender
|
| 633 |
+
////////////////////////////////////////////////////////////////////////////////
|
| 634 |
+
|
| 635 |
+
impl<T> SyncSender<T> {
|
| 636 |
+
/// Sends a value on this synchronous channel.
|
| 637 |
+
///
|
| 638 |
+
/// This function will *block* until space in the internal buffer becomes
|
| 639 |
+
/// available or a receiver is available to hand off the message to.
|
| 640 |
+
///
|
| 641 |
+
/// Note that a successful send does *not* guarantee that the receiver will
|
| 642 |
+
/// ever see the data if there is a buffer on this channel. Items may be
|
| 643 |
+
/// enqueued in the internal buffer for the receiver to receive at a later
|
| 644 |
+
/// time. If the buffer size is 0, however, the channel becomes a rendezvous
|
| 645 |
+
/// channel and it guarantees that the receiver has indeed received
|
| 646 |
+
/// the data if this function returns success.
|
| 647 |
+
///
|
| 648 |
+
/// This function will never panic, but it may return [`Err`] if the
|
| 649 |
+
/// [`Receiver`] has disconnected and is no longer able to receive
|
| 650 |
+
/// information.
|
| 651 |
+
///
|
| 652 |
+
/// # Examples
|
| 653 |
+
///
|
| 654 |
+
/// ```rust
|
| 655 |
+
/// use std::sync::mpsc::sync_channel;
|
| 656 |
+
/// use std::thread;
|
| 657 |
+
///
|
| 658 |
+
/// // Create a rendezvous sync_channel with buffer size 0
|
| 659 |
+
/// let (sync_sender, receiver) = sync_channel(0);
|
| 660 |
+
///
|
| 661 |
+
/// thread::spawn(move || {
|
| 662 |
+
/// println!("sending message...");
|
| 663 |
+
/// sync_sender.send(1).unwrap();
|
| 664 |
+
/// // Thread is now blocked until the message is received
|
| 665 |
+
///
|
| 666 |
+
/// println!("...message received!");
|
| 667 |
+
/// });
|
| 668 |
+
///
|
| 669 |
+
/// let msg = receiver.recv().unwrap();
|
| 670 |
+
/// assert_eq!(1, msg);
|
| 671 |
+
/// ```
|
| 672 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 673 |
+
pub fn send(&self, t: T) -> Result<(), SendError<T>> {
|
| 674 |
+
self.inner.send(t)
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
/// Attempts to send a value on this channel without blocking.
|
| 678 |
+
///
|
| 679 |
+
/// This method differs from [`send`] by returning immediately if the
|
| 680 |
+
/// channel's buffer is full or no receiver is waiting to acquire some
|
| 681 |
+
/// data. Compared with [`send`], this function has two failure cases
|
| 682 |
+
/// instead of one (one for disconnection, one for a full buffer).
|
| 683 |
+
///
|
| 684 |
+
/// See [`send`] for notes about guarantees of whether the
|
| 685 |
+
/// receiver has received the data or not if this function is successful.
|
| 686 |
+
///
|
| 687 |
+
/// [`send`]: Self::send
|
| 688 |
+
///
|
| 689 |
+
/// # Examples
|
| 690 |
+
///
|
| 691 |
+
/// ```rust
|
| 692 |
+
/// use std::sync::mpsc::sync_channel;
|
| 693 |
+
/// use std::thread;
|
| 694 |
+
///
|
| 695 |
+
/// // Create a sync_channel with buffer size 1
|
| 696 |
+
/// let (sync_sender, receiver) = sync_channel(1);
|
| 697 |
+
/// let sync_sender2 = sync_sender.clone();
|
| 698 |
+
///
|
| 699 |
+
/// // First thread owns sync_sender
|
| 700 |
+
/// let handle1 = thread::spawn(move || {
|
| 701 |
+
/// sync_sender.send(1).unwrap();
|
| 702 |
+
/// sync_sender.send(2).unwrap();
|
| 703 |
+
/// // Thread blocked
|
| 704 |
+
/// });
|
| 705 |
+
///
|
| 706 |
+
/// // Second thread owns sync_sender2
|
| 707 |
+
/// let handle2 = thread::spawn(move || {
|
| 708 |
+
/// // This will return an error and send
|
| 709 |
+
/// // no message if the buffer is full
|
| 710 |
+
/// let _ = sync_sender2.try_send(3);
|
| 711 |
+
/// });
|
| 712 |
+
///
|
| 713 |
+
/// let mut msg;
|
| 714 |
+
/// msg = receiver.recv().unwrap();
|
| 715 |
+
/// println!("message {msg} received");
|
| 716 |
+
///
|
| 717 |
+
/// msg = receiver.recv().unwrap();
|
| 718 |
+
/// println!("message {msg} received");
|
| 719 |
+
///
|
| 720 |
+
/// // Third message may have never been sent
|
| 721 |
+
/// match receiver.try_recv() {
|
| 722 |
+
/// Ok(msg) => println!("message {msg} received"),
|
| 723 |
+
/// Err(_) => println!("the third message was never sent"),
|
| 724 |
+
/// }
|
| 725 |
+
///
|
| 726 |
+
/// // Wait for threads to complete
|
| 727 |
+
/// handle1.join().unwrap();
|
| 728 |
+
/// handle2.join().unwrap();
|
| 729 |
+
/// ```
|
| 730 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 731 |
+
pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
|
| 732 |
+
self.inner.try_send(t)
|
| 733 |
+
}
|
| 734 |
+
|
| 735 |
+
// Attempts to send for a value on this receiver, returning an error if the
|
| 736 |
+
// corresponding channel has hung up, or if it waits more than `timeout`.
|
| 737 |
+
//
|
| 738 |
+
// This method is currently only used for tests.
|
| 739 |
+
#[unstable(issue = "none", feature = "std_internals")]
|
| 740 |
+
#[doc(hidden)]
|
| 741 |
+
pub fn send_timeout(&self, t: T, timeout: Duration) -> Result<(), mpmc::SendTimeoutError<T>> {
|
| 742 |
+
self.inner.send_timeout(t, timeout)
|
| 743 |
+
}
|
| 744 |
+
}
|
| 745 |
+
|
| 746 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 747 |
+
impl<T> Clone for SyncSender<T> {
|
| 748 |
+
fn clone(&self) -> SyncSender<T> {
|
| 749 |
+
SyncSender { inner: self.inner.clone() }
|
| 750 |
+
}
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
#[stable(feature = "mpsc_debug", since = "1.8.0")]
|
| 754 |
+
impl<T> fmt::Debug for SyncSender<T> {
|
| 755 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 756 |
+
f.debug_struct("SyncSender").finish_non_exhaustive()
|
| 757 |
+
}
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
////////////////////////////////////////////////////////////////////////////////
|
| 761 |
+
// Receiver
|
| 762 |
+
////////////////////////////////////////////////////////////////////////////////
|
| 763 |
+
|
| 764 |
+
impl<T> Receiver<T> {
|
| 765 |
+
/// Attempts to return a pending value on this receiver without blocking.
|
| 766 |
+
///
|
| 767 |
+
/// This method will never block the caller in order to wait for data to
|
| 768 |
+
/// become available. Instead, this will always return immediately with a
|
| 769 |
+
/// possible option of pending data on the channel.
|
| 770 |
+
///
|
| 771 |
+
/// This is useful for a flavor of "optimistic check" before deciding to
|
| 772 |
+
/// block on a receiver.
|
| 773 |
+
///
|
| 774 |
+
/// Compared with [`recv`], this function has two failure cases instead of one
|
| 775 |
+
/// (one for disconnection, one for an empty buffer).
|
| 776 |
+
///
|
| 777 |
+
/// [`recv`]: Self::recv
|
| 778 |
+
///
|
| 779 |
+
/// # Examples
|
| 780 |
+
///
|
| 781 |
+
/// ```rust
|
| 782 |
+
/// use std::sync::mpsc::{Receiver, channel};
|
| 783 |
+
///
|
| 784 |
+
/// let (_, receiver): (_, Receiver<i32>) = channel();
|
| 785 |
+
///
|
| 786 |
+
/// assert!(receiver.try_recv().is_err());
|
| 787 |
+
/// ```
|
| 788 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 789 |
+
pub fn try_recv(&self) -> Result<T, TryRecvError> {
|
| 790 |
+
self.inner.try_recv()
|
| 791 |
+
}
|
| 792 |
+
|
| 793 |
+
/// Attempts to wait for a value on this receiver, returning an error if the
|
| 794 |
+
/// corresponding channel has hung up.
|
| 795 |
+
///
|
| 796 |
+
/// This function will always block the current thread if there is no data
|
| 797 |
+
/// available and it's possible for more data to be sent (at least one sender
|
| 798 |
+
/// still exists). Once a message is sent to the corresponding [`Sender`]
|
| 799 |
+
/// (or [`SyncSender`]), this receiver will wake up and return that
|
| 800 |
+
/// message.
|
| 801 |
+
///
|
| 802 |
+
/// If the corresponding [`Sender`] has disconnected, or it disconnects while
|
| 803 |
+
/// this call is blocking, this call will wake up and return [`Err`] to
|
| 804 |
+
/// indicate that no more messages can ever be received on this channel.
|
| 805 |
+
/// However, since channels are buffered, messages sent before the disconnect
|
| 806 |
+
/// will still be properly received.
|
| 807 |
+
///
|
| 808 |
+
/// # Examples
|
| 809 |
+
///
|
| 810 |
+
/// ```
|
| 811 |
+
/// use std::sync::mpsc;
|
| 812 |
+
/// use std::thread;
|
| 813 |
+
///
|
| 814 |
+
/// let (send, recv) = mpsc::channel();
|
| 815 |
+
/// let handle = thread::spawn(move || {
|
| 816 |
+
/// send.send(1u8).unwrap();
|
| 817 |
+
/// });
|
| 818 |
+
///
|
| 819 |
+
/// handle.join().unwrap();
|
| 820 |
+
///
|
| 821 |
+
/// assert_eq!(Ok(1), recv.recv());
|
| 822 |
+
/// ```
|
| 823 |
+
///
|
| 824 |
+
/// Buffering behavior:
|
| 825 |
+
///
|
| 826 |
+
/// ```
|
| 827 |
+
/// use std::sync::mpsc;
|
| 828 |
+
/// use std::thread;
|
| 829 |
+
/// use std::sync::mpsc::RecvError;
|
| 830 |
+
///
|
| 831 |
+
/// let (send, recv) = mpsc::channel();
|
| 832 |
+
/// let handle = thread::spawn(move || {
|
| 833 |
+
/// send.send(1u8).unwrap();
|
| 834 |
+
/// send.send(2).unwrap();
|
| 835 |
+
/// send.send(3).unwrap();
|
| 836 |
+
/// drop(send);
|
| 837 |
+
/// });
|
| 838 |
+
///
|
| 839 |
+
/// // wait for the thread to join so we ensure the sender is dropped
|
| 840 |
+
/// handle.join().unwrap();
|
| 841 |
+
///
|
| 842 |
+
/// assert_eq!(Ok(1), recv.recv());
|
| 843 |
+
/// assert_eq!(Ok(2), recv.recv());
|
| 844 |
+
/// assert_eq!(Ok(3), recv.recv());
|
| 845 |
+
/// assert_eq!(Err(RecvError), recv.recv());
|
| 846 |
+
/// ```
|
| 847 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 848 |
+
pub fn recv(&self) -> Result<T, RecvError> {
|
| 849 |
+
self.inner.recv()
|
| 850 |
+
}
|
| 851 |
+
|
| 852 |
+
/// Attempts to wait for a value on this receiver, returning an error if the
|
| 853 |
+
/// corresponding channel has hung up, or if it waits more than `timeout`.
|
| 854 |
+
///
|
| 855 |
+
/// This function will always block the current thread if there is no data
|
| 856 |
+
/// available and it's possible for more data to be sent (at least one sender
|
| 857 |
+
/// still exists). Once a message is sent to the corresponding [`Sender`]
|
| 858 |
+
/// (or [`SyncSender`]), this receiver will wake up and return that
|
| 859 |
+
/// message.
|
| 860 |
+
///
|
| 861 |
+
/// If the corresponding [`Sender`] has disconnected, or it disconnects while
|
| 862 |
+
/// this call is blocking, this call will wake up and return [`Err`] to
|
| 863 |
+
/// indicate that no more messages can ever be received on this channel.
|
| 864 |
+
/// However, since channels are buffered, messages sent before the disconnect
|
| 865 |
+
/// will still be properly received.
|
| 866 |
+
///
|
| 867 |
+
/// # Examples
|
| 868 |
+
///
|
| 869 |
+
/// Successfully receiving value before encountering timeout:
|
| 870 |
+
///
|
| 871 |
+
/// ```no_run
|
| 872 |
+
/// use std::thread;
|
| 873 |
+
/// use std::time::Duration;
|
| 874 |
+
/// use std::sync::mpsc;
|
| 875 |
+
///
|
| 876 |
+
/// let (send, recv) = mpsc::channel();
|
| 877 |
+
///
|
| 878 |
+
/// thread::spawn(move || {
|
| 879 |
+
/// send.send('a').unwrap();
|
| 880 |
+
/// });
|
| 881 |
+
///
|
| 882 |
+
/// assert_eq!(
|
| 883 |
+
/// recv.recv_timeout(Duration::from_millis(400)),
|
| 884 |
+
/// Ok('a')
|
| 885 |
+
/// );
|
| 886 |
+
/// ```
|
| 887 |
+
///
|
| 888 |
+
/// Receiving an error upon reaching timeout:
|
| 889 |
+
///
|
| 890 |
+
/// ```no_run
|
| 891 |
+
/// use std::thread;
|
| 892 |
+
/// use std::time::Duration;
|
| 893 |
+
/// use std::sync::mpsc;
|
| 894 |
+
///
|
| 895 |
+
/// let (send, recv) = mpsc::channel();
|
| 896 |
+
///
|
| 897 |
+
/// thread::spawn(move || {
|
| 898 |
+
/// thread::sleep(Duration::from_millis(800));
|
| 899 |
+
/// send.send('a').unwrap();
|
| 900 |
+
/// });
|
| 901 |
+
///
|
| 902 |
+
/// assert_eq!(
|
| 903 |
+
/// recv.recv_timeout(Duration::from_millis(400)),
|
| 904 |
+
/// Err(mpsc::RecvTimeoutError::Timeout)
|
| 905 |
+
/// );
|
| 906 |
+
/// ```
|
| 907 |
+
#[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
|
| 908 |
+
pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> {
|
| 909 |
+
self.inner.recv_timeout(timeout)
|
| 910 |
+
}
|
| 911 |
+
|
| 912 |
+
/// Attempts to wait for a value on this receiver, returning an error if the
|
| 913 |
+
/// corresponding channel has hung up, or if `deadline` is reached.
|
| 914 |
+
///
|
| 915 |
+
/// This function will always block the current thread if there is no data
|
| 916 |
+
/// available and it's possible for more data to be sent. Once a message is
|
| 917 |
+
/// sent to the corresponding [`Sender`] (or [`SyncSender`]), then this
|
| 918 |
+
/// receiver will wake up and return that message.
|
| 919 |
+
///
|
| 920 |
+
/// If the corresponding [`Sender`] has disconnected, or it disconnects while
|
| 921 |
+
/// this call is blocking, this call will wake up and return [`Err`] to
|
| 922 |
+
/// indicate that no more messages can ever be received on this channel.
|
| 923 |
+
/// However, since channels are buffered, messages sent before the disconnect
|
| 924 |
+
/// will still be properly received.
|
| 925 |
+
///
|
| 926 |
+
/// # Examples
|
| 927 |
+
///
|
| 928 |
+
/// Successfully receiving value before reaching deadline:
|
| 929 |
+
///
|
| 930 |
+
/// ```no_run
|
| 931 |
+
/// #![feature(deadline_api)]
|
| 932 |
+
/// use std::thread;
|
| 933 |
+
/// use std::time::{Duration, Instant};
|
| 934 |
+
/// use std::sync::mpsc;
|
| 935 |
+
///
|
| 936 |
+
/// let (send, recv) = mpsc::channel();
|
| 937 |
+
///
|
| 938 |
+
/// thread::spawn(move || {
|
| 939 |
+
/// send.send('a').unwrap();
|
| 940 |
+
/// });
|
| 941 |
+
///
|
| 942 |
+
/// assert_eq!(
|
| 943 |
+
/// recv.recv_deadline(Instant::now() + Duration::from_millis(400)),
|
| 944 |
+
/// Ok('a')
|
| 945 |
+
/// );
|
| 946 |
+
/// ```
|
| 947 |
+
///
|
| 948 |
+
/// Receiving an error upon reaching deadline:
|
| 949 |
+
///
|
| 950 |
+
/// ```no_run
|
| 951 |
+
/// #![feature(deadline_api)]
|
| 952 |
+
/// use std::thread;
|
| 953 |
+
/// use std::time::{Duration, Instant};
|
| 954 |
+
/// use std::sync::mpsc;
|
| 955 |
+
///
|
| 956 |
+
/// let (send, recv) = mpsc::channel();
|
| 957 |
+
///
|
| 958 |
+
/// thread::spawn(move || {
|
| 959 |
+
/// thread::sleep(Duration::from_millis(800));
|
| 960 |
+
/// send.send('a').unwrap();
|
| 961 |
+
/// });
|
| 962 |
+
///
|
| 963 |
+
/// assert_eq!(
|
| 964 |
+
/// recv.recv_deadline(Instant::now() + Duration::from_millis(400)),
|
| 965 |
+
/// Err(mpsc::RecvTimeoutError::Timeout)
|
| 966 |
+
/// );
|
| 967 |
+
/// ```
|
| 968 |
+
#[unstable(feature = "deadline_api", issue = "46316")]
|
| 969 |
+
pub fn recv_deadline(&self, deadline: Instant) -> Result<T, RecvTimeoutError> {
|
| 970 |
+
self.inner.recv_deadline(deadline)
|
| 971 |
+
}
|
| 972 |
+
|
| 973 |
+
/// Returns an iterator that will block waiting for messages, but never
|
| 974 |
+
/// [`panic!`]. It will return [`None`] when the channel has hung up.
|
| 975 |
+
///
|
| 976 |
+
/// # Examples
|
| 977 |
+
///
|
| 978 |
+
/// ```rust
|
| 979 |
+
/// use std::sync::mpsc::channel;
|
| 980 |
+
/// use std::thread;
|
| 981 |
+
///
|
| 982 |
+
/// let (send, recv) = channel();
|
| 983 |
+
///
|
| 984 |
+
/// thread::spawn(move || {
|
| 985 |
+
/// send.send(1).unwrap();
|
| 986 |
+
/// send.send(2).unwrap();
|
| 987 |
+
/// send.send(3).unwrap();
|
| 988 |
+
/// });
|
| 989 |
+
///
|
| 990 |
+
/// let mut iter = recv.iter();
|
| 991 |
+
/// assert_eq!(iter.next(), Some(1));
|
| 992 |
+
/// assert_eq!(iter.next(), Some(2));
|
| 993 |
+
/// assert_eq!(iter.next(), Some(3));
|
| 994 |
+
/// assert_eq!(iter.next(), None);
|
| 995 |
+
/// ```
|
| 996 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 997 |
+
pub fn iter(&self) -> Iter<'_, T> {
|
| 998 |
+
Iter { rx: self }
|
| 999 |
+
}
|
| 1000 |
+
|
| 1001 |
+
/// Returns an iterator that will attempt to yield all pending values.
|
| 1002 |
+
/// It will return `None` if there are no more pending values or if the
|
| 1003 |
+
/// channel has hung up. The iterator will never [`panic!`] or block the
|
| 1004 |
+
/// user by waiting for values.
|
| 1005 |
+
///
|
| 1006 |
+
/// # Examples
|
| 1007 |
+
///
|
| 1008 |
+
/// ```no_run
|
| 1009 |
+
/// use std::sync::mpsc::channel;
|
| 1010 |
+
/// use std::thread;
|
| 1011 |
+
/// use std::time::Duration;
|
| 1012 |
+
///
|
| 1013 |
+
/// let (sender, receiver) = channel();
|
| 1014 |
+
///
|
| 1015 |
+
/// // nothing is in the buffer yet
|
| 1016 |
+
/// assert!(receiver.try_iter().next().is_none());
|
| 1017 |
+
///
|
| 1018 |
+
/// thread::spawn(move || {
|
| 1019 |
+
/// thread::sleep(Duration::from_secs(1));
|
| 1020 |
+
/// sender.send(1).unwrap();
|
| 1021 |
+
/// sender.send(2).unwrap();
|
| 1022 |
+
/// sender.send(3).unwrap();
|
| 1023 |
+
/// });
|
| 1024 |
+
///
|
| 1025 |
+
/// // nothing is in the buffer yet
|
| 1026 |
+
/// assert!(receiver.try_iter().next().is_none());
|
| 1027 |
+
///
|
| 1028 |
+
/// // block for two seconds
|
| 1029 |
+
/// thread::sleep(Duration::from_secs(2));
|
| 1030 |
+
///
|
| 1031 |
+
/// let mut iter = receiver.try_iter();
|
| 1032 |
+
/// assert_eq!(iter.next(), Some(1));
|
| 1033 |
+
/// assert_eq!(iter.next(), Some(2));
|
| 1034 |
+
/// assert_eq!(iter.next(), Some(3));
|
| 1035 |
+
/// assert_eq!(iter.next(), None);
|
| 1036 |
+
/// ```
|
| 1037 |
+
#[stable(feature = "receiver_try_iter", since = "1.15.0")]
|
| 1038 |
+
pub fn try_iter(&self) -> TryIter<'_, T> {
|
| 1039 |
+
TryIter { rx: self }
|
| 1040 |
+
}
|
| 1041 |
+
}
|
| 1042 |
+
|
| 1043 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1044 |
+
impl<'a, T> Iterator for Iter<'a, T> {
|
| 1045 |
+
type Item = T;
|
| 1046 |
+
|
| 1047 |
+
fn next(&mut self) -> Option<T> {
|
| 1048 |
+
self.rx.recv().ok()
|
| 1049 |
+
}
|
| 1050 |
+
}
|
| 1051 |
+
|
| 1052 |
+
#[stable(feature = "receiver_try_iter", since = "1.15.0")]
|
| 1053 |
+
impl<'a, T> Iterator for TryIter<'a, T> {
|
| 1054 |
+
type Item = T;
|
| 1055 |
+
|
| 1056 |
+
fn next(&mut self) -> Option<T> {
|
| 1057 |
+
self.rx.try_recv().ok()
|
| 1058 |
+
}
|
| 1059 |
+
}
|
| 1060 |
+
|
| 1061 |
+
#[stable(feature = "receiver_into_iter", since = "1.1.0")]
|
| 1062 |
+
impl<'a, T> IntoIterator for &'a Receiver<T> {
|
| 1063 |
+
type Item = T;
|
| 1064 |
+
type IntoIter = Iter<'a, T>;
|
| 1065 |
+
|
| 1066 |
+
fn into_iter(self) -> Iter<'a, T> {
|
| 1067 |
+
self.iter()
|
| 1068 |
+
}
|
| 1069 |
+
}
|
| 1070 |
+
|
| 1071 |
+
#[stable(feature = "receiver_into_iter", since = "1.1.0")]
|
| 1072 |
+
impl<T> Iterator for IntoIter<T> {
|
| 1073 |
+
type Item = T;
|
| 1074 |
+
fn next(&mut self) -> Option<T> {
|
| 1075 |
+
self.rx.recv().ok()
|
| 1076 |
+
}
|
| 1077 |
+
}
|
| 1078 |
+
|
| 1079 |
+
#[stable(feature = "receiver_into_iter", since = "1.1.0")]
|
| 1080 |
+
impl<T> IntoIterator for Receiver<T> {
|
| 1081 |
+
type Item = T;
|
| 1082 |
+
type IntoIter = IntoIter<T>;
|
| 1083 |
+
|
| 1084 |
+
fn into_iter(self) -> IntoIter<T> {
|
| 1085 |
+
IntoIter { rx: self }
|
| 1086 |
+
}
|
| 1087 |
+
}
|
| 1088 |
+
|
| 1089 |
+
#[stable(feature = "mpsc_debug", since = "1.8.0")]
|
| 1090 |
+
impl<T> fmt::Debug for Receiver<T> {
|
| 1091 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 1092 |
+
f.debug_struct("Receiver").finish_non_exhaustive()
|
| 1093 |
+
}
|
| 1094 |
+
}
|
| 1095 |
+
|
| 1096 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1097 |
+
impl<T> fmt::Debug for SendError<T> {
|
| 1098 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 1099 |
+
f.debug_struct("SendError").finish_non_exhaustive()
|
| 1100 |
+
}
|
| 1101 |
+
}
|
| 1102 |
+
|
| 1103 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1104 |
+
impl<T> fmt::Display for SendError<T> {
|
| 1105 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 1106 |
+
"sending on a closed channel".fmt(f)
|
| 1107 |
+
}
|
| 1108 |
+
}
|
| 1109 |
+
|
| 1110 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1111 |
+
impl<T> error::Error for SendError<T> {}
|
| 1112 |
+
|
| 1113 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1114 |
+
impl<T> fmt::Debug for TrySendError<T> {
|
| 1115 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 1116 |
+
match *self {
|
| 1117 |
+
TrySendError::Full(..) => f.debug_tuple("TrySendError::Full").finish_non_exhaustive(),
|
| 1118 |
+
TrySendError::Disconnected(..) => {
|
| 1119 |
+
f.debug_tuple("TrySendError::Disconnected").finish_non_exhaustive()
|
| 1120 |
+
}
|
| 1121 |
+
}
|
| 1122 |
+
}
|
| 1123 |
+
}
|
| 1124 |
+
|
| 1125 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1126 |
+
impl<T> fmt::Display for TrySendError<T> {
|
| 1127 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 1128 |
+
match *self {
|
| 1129 |
+
TrySendError::Full(..) => "sending on a full channel".fmt(f),
|
| 1130 |
+
TrySendError::Disconnected(..) => "sending on a closed channel".fmt(f),
|
| 1131 |
+
}
|
| 1132 |
+
}
|
| 1133 |
+
}
|
| 1134 |
+
|
| 1135 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1136 |
+
impl<T> error::Error for TrySendError<T> {}
|
| 1137 |
+
|
| 1138 |
+
#[stable(feature = "mpsc_error_conversions", since = "1.24.0")]
|
| 1139 |
+
impl<T> From<SendError<T>> for TrySendError<T> {
|
| 1140 |
+
/// Converts a `SendError<T>` into a `TrySendError<T>`.
|
| 1141 |
+
///
|
| 1142 |
+
/// This conversion always returns a `TrySendError::Disconnected` containing the data in the `SendError<T>`.
|
| 1143 |
+
///
|
| 1144 |
+
/// No data is allocated on the heap.
|
| 1145 |
+
fn from(err: SendError<T>) -> TrySendError<T> {
|
| 1146 |
+
match err {
|
| 1147 |
+
SendError(t) => TrySendError::Disconnected(t),
|
| 1148 |
+
}
|
| 1149 |
+
}
|
| 1150 |
+
}
|
| 1151 |
+
|
| 1152 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1153 |
+
impl fmt::Display for RecvError {
|
| 1154 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 1155 |
+
"receiving on a closed channel".fmt(f)
|
| 1156 |
+
}
|
| 1157 |
+
}
|
| 1158 |
+
|
| 1159 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1160 |
+
impl error::Error for RecvError {}
|
| 1161 |
+
|
| 1162 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1163 |
+
impl fmt::Display for TryRecvError {
|
| 1164 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 1165 |
+
match *self {
|
| 1166 |
+
TryRecvError::Empty => "receiving on an empty channel".fmt(f),
|
| 1167 |
+
TryRecvError::Disconnected => "receiving on a closed channel".fmt(f),
|
| 1168 |
+
}
|
| 1169 |
+
}
|
| 1170 |
+
}
|
| 1171 |
+
|
| 1172 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 1173 |
+
impl error::Error for TryRecvError {}
|
| 1174 |
+
|
| 1175 |
+
#[stable(feature = "mpsc_error_conversions", since = "1.24.0")]
|
| 1176 |
+
impl From<RecvError> for TryRecvError {
|
| 1177 |
+
/// Converts a `RecvError` into a `TryRecvError`.
|
| 1178 |
+
///
|
| 1179 |
+
/// This conversion always returns `TryRecvError::Disconnected`.
|
| 1180 |
+
///
|
| 1181 |
+
/// No data is allocated on the heap.
|
| 1182 |
+
fn from(err: RecvError) -> TryRecvError {
|
| 1183 |
+
match err {
|
| 1184 |
+
RecvError => TryRecvError::Disconnected,
|
| 1185 |
+
}
|
| 1186 |
+
}
|
| 1187 |
+
}
|
| 1188 |
+
|
| 1189 |
+
#[stable(feature = "mpsc_recv_timeout_error", since = "1.15.0")]
|
| 1190 |
+
impl fmt::Display for RecvTimeoutError {
|
| 1191 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 1192 |
+
match *self {
|
| 1193 |
+
RecvTimeoutError::Timeout => "timed out waiting on channel".fmt(f),
|
| 1194 |
+
RecvTimeoutError::Disconnected => "channel is empty and sending half is closed".fmt(f),
|
| 1195 |
+
}
|
| 1196 |
+
}
|
| 1197 |
+
}
|
| 1198 |
+
|
| 1199 |
+
#[stable(feature = "mpsc_recv_timeout_error", since = "1.15.0")]
|
| 1200 |
+
impl error::Error for RecvTimeoutError {}
|
| 1201 |
+
|
| 1202 |
+
#[stable(feature = "mpsc_error_conversions", since = "1.24.0")]
|
| 1203 |
+
impl From<RecvError> for RecvTimeoutError {
|
| 1204 |
+
/// Converts a `RecvError` into a `RecvTimeoutError`.
|
| 1205 |
+
///
|
| 1206 |
+
/// This conversion always returns `RecvTimeoutError::Disconnected`.
|
| 1207 |
+
///
|
| 1208 |
+
/// No data is allocated on the heap.
|
| 1209 |
+
fn from(err: RecvError) -> RecvTimeoutError {
|
| 1210 |
+
match err {
|
| 1211 |
+
RecvError => RecvTimeoutError::Disconnected,
|
| 1212 |
+
}
|
| 1213 |
+
}
|
| 1214 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/nonpoison.rs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Non-poisoning synchronous locks.
|
| 2 |
+
//!
|
| 3 |
+
//! The difference from the locks in the [`poison`] module is that the locks in this module will not
|
| 4 |
+
//! become poisoned when a thread panics while holding a guard.
|
| 5 |
+
//!
|
| 6 |
+
//! [`poison`]: super::poison
|
| 7 |
+
|
| 8 |
+
use crate::fmt;
|
| 9 |
+
|
| 10 |
+
/// A type alias for the result of a nonblocking locking method.
|
| 11 |
+
#[unstable(feature = "sync_nonpoison", issue = "134645")]
|
| 12 |
+
pub type TryLockResult<Guard> = Result<Guard, WouldBlock>;
|
| 13 |
+
|
| 14 |
+
/// A lock could not be acquired at this time because the operation would otherwise block.
|
| 15 |
+
#[unstable(feature = "sync_nonpoison", issue = "134645")]
|
| 16 |
+
pub struct WouldBlock;
|
| 17 |
+
|
| 18 |
+
#[unstable(feature = "sync_nonpoison", issue = "134645")]
|
| 19 |
+
impl fmt::Debug for WouldBlock {
|
| 20 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 21 |
+
"WouldBlock".fmt(f)
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
#[unstable(feature = "sync_nonpoison", issue = "134645")]
|
| 26 |
+
impl fmt::Display for WouldBlock {
|
| 27 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 28 |
+
"try_lock failed because the operation would block".fmt(f)
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
#[unstable(feature = "nonpoison_condvar", issue = "134645")]
|
| 33 |
+
pub use self::condvar::Condvar;
|
| 34 |
+
#[unstable(feature = "mapped_lock_guards", issue = "117108")]
|
| 35 |
+
pub use self::mutex::MappedMutexGuard;
|
| 36 |
+
#[unstable(feature = "nonpoison_mutex", issue = "134645")]
|
| 37 |
+
pub use self::mutex::{Mutex, MutexGuard};
|
| 38 |
+
#[unstable(feature = "mapped_lock_guards", issue = "117108")]
|
| 39 |
+
pub use self::rwlock::{MappedRwLockReadGuard, MappedRwLockWriteGuard};
|
| 40 |
+
#[unstable(feature = "nonpoison_rwlock", issue = "134645")]
|
| 41 |
+
pub use self::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
| 42 |
+
|
| 43 |
+
mod condvar;
|
| 44 |
+
mod mutex;
|
| 45 |
+
mod rwlock;
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/once.rs
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! A "once initialization" primitive
|
| 2 |
+
//!
|
| 3 |
+
//! This primitive is meant to be used to run one-time initialization. An
|
| 4 |
+
//! example use case would be for initializing an FFI library.
|
| 5 |
+
|
| 6 |
+
use crate::fmt;
|
| 7 |
+
use crate::panic::{RefUnwindSafe, UnwindSafe};
|
| 8 |
+
use crate::sys::sync as sys;
|
| 9 |
+
|
| 10 |
+
/// A low-level synchronization primitive for one-time global execution.
|
| 11 |
+
///
|
| 12 |
+
/// Previously this was the only "execute once" synchronization in `std`.
|
| 13 |
+
/// Other libraries implemented novel synchronizing types with `Once`, like
|
| 14 |
+
/// [`OnceLock<T>`] or [`LazyLock<T, F>`], before those were added to `std`.
|
| 15 |
+
/// `OnceLock<T>` in particular supersedes `Once` in functionality and should
|
| 16 |
+
/// be preferred for the common case where the `Once` is associated with data.
|
| 17 |
+
///
|
| 18 |
+
/// This type can only be constructed with [`Once::new()`].
|
| 19 |
+
///
|
| 20 |
+
/// # Examples
|
| 21 |
+
///
|
| 22 |
+
/// ```
|
| 23 |
+
/// use std::sync::Once;
|
| 24 |
+
///
|
| 25 |
+
/// static START: Once = Once::new();
|
| 26 |
+
///
|
| 27 |
+
/// START.call_once(|| {
|
| 28 |
+
/// // run initialization here
|
| 29 |
+
/// });
|
| 30 |
+
/// ```
|
| 31 |
+
///
|
| 32 |
+
/// [`OnceLock<T>`]: crate::sync::OnceLock
|
| 33 |
+
/// [`LazyLock<T, F>`]: crate::sync::LazyLock
|
| 34 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 35 |
+
pub struct Once {
|
| 36 |
+
inner: sys::Once,
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
#[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
|
| 40 |
+
impl UnwindSafe for Once {}
|
| 41 |
+
|
| 42 |
+
#[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
|
| 43 |
+
impl RefUnwindSafe for Once {}
|
| 44 |
+
|
| 45 |
+
/// State yielded to [`Once::call_once_force()`]’s closure parameter. The state
|
| 46 |
+
/// can be used to query the poison status of the [`Once`].
|
| 47 |
+
#[stable(feature = "once_poison", since = "1.51.0")]
|
| 48 |
+
pub struct OnceState {
|
| 49 |
+
pub(crate) inner: sys::OnceState,
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
/// Used for the internal implementation of `sys::sync::once` on different platforms and the
|
| 53 |
+
/// [`LazyLock`](crate::sync::LazyLock) implementation.
|
| 54 |
+
pub(crate) enum OnceExclusiveState {
|
| 55 |
+
Incomplete,
|
| 56 |
+
Poisoned,
|
| 57 |
+
Complete,
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/// Initialization value for static [`Once`] values.
|
| 61 |
+
///
|
| 62 |
+
/// # Examples
|
| 63 |
+
///
|
| 64 |
+
/// ```
|
| 65 |
+
/// use std::sync::{Once, ONCE_INIT};
|
| 66 |
+
///
|
| 67 |
+
/// static START: Once = ONCE_INIT;
|
| 68 |
+
/// ```
|
| 69 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 70 |
+
#[deprecated(
|
| 71 |
+
since = "1.38.0",
|
| 72 |
+
note = "the `Once::new()` function is now preferred",
|
| 73 |
+
suggestion = "Once::new()"
|
| 74 |
+
)]
|
| 75 |
+
pub const ONCE_INIT: Once = Once::new();
|
| 76 |
+
|
| 77 |
+
impl Once {
|
| 78 |
+
/// Creates a new `Once` value.
|
| 79 |
+
#[inline]
|
| 80 |
+
#[stable(feature = "once_new", since = "1.2.0")]
|
| 81 |
+
#[rustc_const_stable(feature = "const_once_new", since = "1.32.0")]
|
| 82 |
+
#[must_use]
|
| 83 |
+
pub const fn new() -> Once {
|
| 84 |
+
Once { inner: sys::Once::new() }
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
/// Performs an initialization routine once and only once. The given closure
|
| 88 |
+
/// will be executed if this is the first time `call_once` has been called,
|
| 89 |
+
/// and otherwise the routine will *not* be invoked.
|
| 90 |
+
///
|
| 91 |
+
/// This method will block the calling thread if another initialization
|
| 92 |
+
/// routine is currently running.
|
| 93 |
+
///
|
| 94 |
+
/// When this function returns, it is guaranteed that some initialization
|
| 95 |
+
/// has run and completed (it might not be the closure specified). It is also
|
| 96 |
+
/// guaranteed that any memory writes performed by the executed closure can
|
| 97 |
+
/// be reliably observed by other threads at this point (there is a
|
| 98 |
+
/// happens-before relation between the closure and code executing after the
|
| 99 |
+
/// return).
|
| 100 |
+
///
|
| 101 |
+
/// If the given closure recursively invokes `call_once` on the same [`Once`]
|
| 102 |
+
/// instance, the exact behavior is not specified: allowed outcomes are
|
| 103 |
+
/// a panic or a deadlock.
|
| 104 |
+
///
|
| 105 |
+
/// # Examples
|
| 106 |
+
///
|
| 107 |
+
/// ```
|
| 108 |
+
/// use std::sync::Once;
|
| 109 |
+
///
|
| 110 |
+
/// static mut VAL: usize = 0;
|
| 111 |
+
/// static INIT: Once = Once::new();
|
| 112 |
+
///
|
| 113 |
+
/// // Accessing a `static mut` is unsafe much of the time, but if we do so
|
| 114 |
+
/// // in a synchronized fashion (e.g., write once or read all) then we're
|
| 115 |
+
/// // good to go!
|
| 116 |
+
/// //
|
| 117 |
+
/// // This function will only call `expensive_computation` once, and will
|
| 118 |
+
/// // otherwise always return the value returned from the first invocation.
|
| 119 |
+
/// fn get_cached_val() -> usize {
|
| 120 |
+
/// unsafe {
|
| 121 |
+
/// INIT.call_once(|| {
|
| 122 |
+
/// VAL = expensive_computation();
|
| 123 |
+
/// });
|
| 124 |
+
/// VAL
|
| 125 |
+
/// }
|
| 126 |
+
/// }
|
| 127 |
+
///
|
| 128 |
+
/// fn expensive_computation() -> usize {
|
| 129 |
+
/// // ...
|
| 130 |
+
/// # 2
|
| 131 |
+
/// }
|
| 132 |
+
/// ```
|
| 133 |
+
///
|
| 134 |
+
/// # Panics
|
| 135 |
+
///
|
| 136 |
+
/// The closure `f` will only be executed once even if this is called
|
| 137 |
+
/// concurrently amongst many threads. If that closure panics, however, then
|
| 138 |
+
/// it will *poison* this [`Once`] instance, causing all future invocations of
|
| 139 |
+
/// `call_once` to also panic.
|
| 140 |
+
///
|
| 141 |
+
/// This is similar to [poisoning with mutexes][poison], but this mechanism
|
| 142 |
+
/// is guaranteed to never skip panics within `f`.
|
| 143 |
+
///
|
| 144 |
+
/// [poison]: struct.Mutex.html#poisoning
|
| 145 |
+
#[inline]
|
| 146 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 147 |
+
#[track_caller]
|
| 148 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 149 |
+
pub fn call_once<F>(&self, f: F)
|
| 150 |
+
where
|
| 151 |
+
F: FnOnce(),
|
| 152 |
+
{
|
| 153 |
+
// Fast path check
|
| 154 |
+
if self.inner.is_completed() {
|
| 155 |
+
return;
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
let mut f = Some(f);
|
| 159 |
+
self.inner.call(false, &mut |_| f.take().unwrap()());
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
/// Performs the same function as [`call_once()`] except ignores poisoning.
|
| 163 |
+
///
|
| 164 |
+
/// Unlike [`call_once()`], if this [`Once`] has been poisoned (i.e., a previous
|
| 165 |
+
/// call to [`call_once()`] or [`call_once_force()`] caused a panic), calling
|
| 166 |
+
/// [`call_once_force()`] will still invoke the closure `f` and will _not_
|
| 167 |
+
/// result in an immediate panic. If `f` panics, the [`Once`] will remain
|
| 168 |
+
/// in a poison state. If `f` does _not_ panic, the [`Once`] will no
|
| 169 |
+
/// longer be in a poison state and all future calls to [`call_once()`] or
|
| 170 |
+
/// [`call_once_force()`] will be no-ops.
|
| 171 |
+
///
|
| 172 |
+
/// The closure `f` is yielded a [`OnceState`] structure which can be used
|
| 173 |
+
/// to query the poison status of the [`Once`].
|
| 174 |
+
///
|
| 175 |
+
/// [`call_once()`]: Once::call_once
|
| 176 |
+
/// [`call_once_force()`]: Once::call_once_force
|
| 177 |
+
///
|
| 178 |
+
/// # Examples
|
| 179 |
+
///
|
| 180 |
+
/// ```
|
| 181 |
+
/// use std::sync::Once;
|
| 182 |
+
/// use std::thread;
|
| 183 |
+
///
|
| 184 |
+
/// static INIT: Once = Once::new();
|
| 185 |
+
///
|
| 186 |
+
/// // poison the once
|
| 187 |
+
/// let handle = thread::spawn(|| {
|
| 188 |
+
/// INIT.call_once(|| panic!());
|
| 189 |
+
/// });
|
| 190 |
+
/// assert!(handle.join().is_err());
|
| 191 |
+
///
|
| 192 |
+
/// // poisoning propagates
|
| 193 |
+
/// let handle = thread::spawn(|| {
|
| 194 |
+
/// INIT.call_once(|| {});
|
| 195 |
+
/// });
|
| 196 |
+
/// assert!(handle.join().is_err());
|
| 197 |
+
///
|
| 198 |
+
/// // call_once_force will still run and reset the poisoned state
|
| 199 |
+
/// INIT.call_once_force(|state| {
|
| 200 |
+
/// assert!(state.is_poisoned());
|
| 201 |
+
/// });
|
| 202 |
+
///
|
| 203 |
+
/// // once any success happens, we stop propagating the poison
|
| 204 |
+
/// INIT.call_once(|| {});
|
| 205 |
+
/// ```
|
| 206 |
+
#[inline]
|
| 207 |
+
#[stable(feature = "once_poison", since = "1.51.0")]
|
| 208 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 209 |
+
pub fn call_once_force<F>(&self, f: F)
|
| 210 |
+
where
|
| 211 |
+
F: FnOnce(&OnceState),
|
| 212 |
+
{
|
| 213 |
+
// Fast path check
|
| 214 |
+
if self.inner.is_completed() {
|
| 215 |
+
return;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
let mut f = Some(f);
|
| 219 |
+
self.inner.call(true, &mut |p| f.take().unwrap()(p));
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
/// Returns `true` if some [`call_once()`] call has completed
|
| 223 |
+
/// successfully. Specifically, `is_completed` will return false in
|
| 224 |
+
/// the following situations:
|
| 225 |
+
/// * [`call_once()`] was not called at all,
|
| 226 |
+
/// * [`call_once()`] was called, but has not yet completed,
|
| 227 |
+
/// * the [`Once`] instance is poisoned
|
| 228 |
+
///
|
| 229 |
+
/// This function returning `false` does not mean that [`Once`] has not been
|
| 230 |
+
/// executed. For example, it may have been executed in the time between
|
| 231 |
+
/// when `is_completed` starts executing and when it returns, in which case
|
| 232 |
+
/// the `false` return value would be stale (but still permissible).
|
| 233 |
+
///
|
| 234 |
+
/// [`call_once()`]: Once::call_once
|
| 235 |
+
///
|
| 236 |
+
/// # Examples
|
| 237 |
+
///
|
| 238 |
+
/// ```
|
| 239 |
+
/// use std::sync::Once;
|
| 240 |
+
///
|
| 241 |
+
/// static INIT: Once = Once::new();
|
| 242 |
+
///
|
| 243 |
+
/// assert_eq!(INIT.is_completed(), false);
|
| 244 |
+
/// INIT.call_once(|| {
|
| 245 |
+
/// assert_eq!(INIT.is_completed(), false);
|
| 246 |
+
/// });
|
| 247 |
+
/// assert_eq!(INIT.is_completed(), true);
|
| 248 |
+
/// ```
|
| 249 |
+
///
|
| 250 |
+
/// ```
|
| 251 |
+
/// use std::sync::Once;
|
| 252 |
+
/// use std::thread;
|
| 253 |
+
///
|
| 254 |
+
/// static INIT: Once = Once::new();
|
| 255 |
+
///
|
| 256 |
+
/// assert_eq!(INIT.is_completed(), false);
|
| 257 |
+
/// let handle = thread::spawn(|| {
|
| 258 |
+
/// INIT.call_once(|| panic!());
|
| 259 |
+
/// });
|
| 260 |
+
/// assert!(handle.join().is_err());
|
| 261 |
+
/// assert_eq!(INIT.is_completed(), false);
|
| 262 |
+
/// ```
|
| 263 |
+
#[stable(feature = "once_is_completed", since = "1.43.0")]
|
| 264 |
+
#[inline]
|
| 265 |
+
pub fn is_completed(&self) -> bool {
|
| 266 |
+
self.inner.is_completed()
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
/// Blocks the current thread until initialization has completed.
|
| 270 |
+
///
|
| 271 |
+
/// # Example
|
| 272 |
+
///
|
| 273 |
+
/// ```rust
|
| 274 |
+
/// use std::sync::Once;
|
| 275 |
+
/// use std::thread;
|
| 276 |
+
///
|
| 277 |
+
/// static READY: Once = Once::new();
|
| 278 |
+
///
|
| 279 |
+
/// let thread = thread::spawn(|| {
|
| 280 |
+
/// READY.wait();
|
| 281 |
+
/// println!("everything is ready");
|
| 282 |
+
/// });
|
| 283 |
+
///
|
| 284 |
+
/// READY.call_once(|| println!("performing setup"));
|
| 285 |
+
/// ```
|
| 286 |
+
///
|
| 287 |
+
/// # Panics
|
| 288 |
+
///
|
| 289 |
+
/// If this [`Once`] has been poisoned because an initialization closure has
|
| 290 |
+
/// panicked, this method will also panic. Use [`wait_force`](Self::wait_force)
|
| 291 |
+
/// if this behavior is not desired.
|
| 292 |
+
#[stable(feature = "once_wait", since = "1.86.0")]
|
| 293 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 294 |
+
pub fn wait(&self) {
|
| 295 |
+
if !self.inner.is_completed() {
|
| 296 |
+
self.inner.wait(false);
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
/// Blocks the current thread until initialization has completed, ignoring
|
| 301 |
+
/// poisoning.
|
| 302 |
+
///
|
| 303 |
+
/// If this [`Once`] has been poisoned, this function blocks until it
|
| 304 |
+
/// becomes completed, unlike [`Once::wait()`], which panics in this case.
|
| 305 |
+
#[stable(feature = "once_wait", since = "1.86.0")]
|
| 306 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 307 |
+
pub fn wait_force(&self) {
|
| 308 |
+
if !self.inner.is_completed() {
|
| 309 |
+
self.inner.wait(true);
|
| 310 |
+
}
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
/// Returns the current state of the `Once` instance.
|
| 314 |
+
///
|
| 315 |
+
/// Since this takes a mutable reference, no initialization can currently
|
| 316 |
+
/// be running, so the state must be either "incomplete", "poisoned" or
|
| 317 |
+
/// "complete".
|
| 318 |
+
#[inline]
|
| 319 |
+
pub(crate) fn state(&mut self) -> OnceExclusiveState {
|
| 320 |
+
self.inner.state()
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
/// Sets current state of the `Once` instance.
|
| 324 |
+
///
|
| 325 |
+
/// Since this takes a mutable reference, no initialization can currently
|
| 326 |
+
/// be running, so the state must be either "incomplete", "poisoned" or
|
| 327 |
+
/// "complete".
|
| 328 |
+
#[inline]
|
| 329 |
+
pub(crate) fn set_state(&mut self, new_state: OnceExclusiveState) {
|
| 330 |
+
self.inner.set_state(new_state);
|
| 331 |
+
}
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
#[stable(feature = "std_debug", since = "1.16.0")]
|
| 335 |
+
impl fmt::Debug for Once {
|
| 336 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 337 |
+
f.debug_struct("Once").finish_non_exhaustive()
|
| 338 |
+
}
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
impl OnceState {
|
| 342 |
+
/// Returns `true` if the associated [`Once`] was poisoned prior to the
|
| 343 |
+
/// invocation of the closure passed to [`Once::call_once_force()`].
|
| 344 |
+
///
|
| 345 |
+
/// # Examples
|
| 346 |
+
///
|
| 347 |
+
/// A poisoned [`Once`]:
|
| 348 |
+
///
|
| 349 |
+
/// ```
|
| 350 |
+
/// use std::sync::Once;
|
| 351 |
+
/// use std::thread;
|
| 352 |
+
///
|
| 353 |
+
/// static INIT: Once = Once::new();
|
| 354 |
+
///
|
| 355 |
+
/// // poison the once
|
| 356 |
+
/// let handle = thread::spawn(|| {
|
| 357 |
+
/// INIT.call_once(|| panic!());
|
| 358 |
+
/// });
|
| 359 |
+
/// assert!(handle.join().is_err());
|
| 360 |
+
///
|
| 361 |
+
/// INIT.call_once_force(|state| {
|
| 362 |
+
/// assert!(state.is_poisoned());
|
| 363 |
+
/// });
|
| 364 |
+
/// ```
|
| 365 |
+
///
|
| 366 |
+
/// An unpoisoned [`Once`]:
|
| 367 |
+
///
|
| 368 |
+
/// ```
|
| 369 |
+
/// use std::sync::Once;
|
| 370 |
+
///
|
| 371 |
+
/// static INIT: Once = Once::new();
|
| 372 |
+
///
|
| 373 |
+
/// INIT.call_once_force(|state| {
|
| 374 |
+
/// assert!(!state.is_poisoned());
|
| 375 |
+
/// });
|
| 376 |
+
#[stable(feature = "once_poison", since = "1.51.0")]
|
| 377 |
+
#[inline]
|
| 378 |
+
pub fn is_poisoned(&self) -> bool {
|
| 379 |
+
self.inner.is_poisoned()
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
/// Poison the associated [`Once`] without explicitly panicking.
|
| 383 |
+
// NOTE: This is currently only exposed for `OnceLock`.
|
| 384 |
+
#[inline]
|
| 385 |
+
pub(crate) fn poison(&self) {
|
| 386 |
+
self.inner.poison();
|
| 387 |
+
}
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
#[stable(feature = "std_debug", since = "1.16.0")]
|
| 391 |
+
impl fmt::Debug for OnceState {
|
| 392 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 393 |
+
f.debug_struct("OnceState").field("poisoned", &self.is_poisoned()).finish()
|
| 394 |
+
}
|
| 395 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/once_lock.rs
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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it;
|
| 6 |
+
use crate::panic::{RefUnwindSafe, UnwindSafe};
|
| 7 |
+
use crate::sync::Once;
|
| 8 |
+
|
| 9 |
+
/// A synchronization primitive which can nominally be written to only once.
|
| 10 |
+
///
|
| 11 |
+
/// This type is a thread-safe [`OnceCell`], and can be used in statics.
|
| 12 |
+
/// In many simple cases, you can use [`LazyLock<T, F>`] instead to get the benefits of this type
|
| 13 |
+
/// with less effort: `LazyLock<T, F>` "looks like" `&T` because it initializes with `F` on deref!
|
| 14 |
+
/// Where OnceLock shines is when LazyLock is too simple to support a given case, as LazyLock
|
| 15 |
+
/// doesn't allow additional inputs to its function after you call [`LazyLock::new(|| ...)`].
|
| 16 |
+
///
|
| 17 |
+
/// A `OnceLock` can be thought of as a safe abstraction over uninitialized data that becomes
|
| 18 |
+
/// initialized once written.
|
| 19 |
+
///
|
| 20 |
+
/// Unlike [`Mutex`](crate::sync::Mutex), `OnceLock` is never poisoned on panic.
|
| 21 |
+
///
|
| 22 |
+
/// [`OnceCell`]: crate::cell::OnceCell
|
| 23 |
+
/// [`LazyLock<T, F>`]: crate::sync::LazyLock
|
| 24 |
+
/// [`LazyLock::new(|| ...)`]: crate::sync::LazyLock::new
|
| 25 |
+
///
|
| 26 |
+
/// # Examples
|
| 27 |
+
///
|
| 28 |
+
/// Writing to a `OnceLock` from a separate thread:
|
| 29 |
+
///
|
| 30 |
+
/// ```
|
| 31 |
+
/// use std::sync::OnceLock;
|
| 32 |
+
///
|
| 33 |
+
/// static CELL: OnceLock<usize> = OnceLock::new();
|
| 34 |
+
///
|
| 35 |
+
/// // `OnceLock` has not been written to yet.
|
| 36 |
+
/// assert!(CELL.get().is_none());
|
| 37 |
+
///
|
| 38 |
+
/// // Spawn a thread and write to `OnceLock`.
|
| 39 |
+
/// std::thread::spawn(|| {
|
| 40 |
+
/// let value = CELL.get_or_init(|| 12345);
|
| 41 |
+
/// assert_eq!(value, &12345);
|
| 42 |
+
/// })
|
| 43 |
+
/// .join()
|
| 44 |
+
/// .unwrap();
|
| 45 |
+
///
|
| 46 |
+
/// // `OnceLock` now contains the value.
|
| 47 |
+
/// assert_eq!(
|
| 48 |
+
/// CELL.get(),
|
| 49 |
+
/// Some(&12345),
|
| 50 |
+
/// );
|
| 51 |
+
/// ```
|
| 52 |
+
///
|
| 53 |
+
/// You can use `OnceLock` to implement a type that requires "append-only" logic:
|
| 54 |
+
///
|
| 55 |
+
/// ```
|
| 56 |
+
/// use std::sync::{OnceLock, atomic::{AtomicU32, Ordering}};
|
| 57 |
+
/// use std::thread;
|
| 58 |
+
///
|
| 59 |
+
/// struct OnceList<T> {
|
| 60 |
+
/// data: OnceLock<T>,
|
| 61 |
+
/// next: OnceLock<Box<OnceList<T>>>,
|
| 62 |
+
/// }
|
| 63 |
+
/// impl<T> OnceList<T> {
|
| 64 |
+
/// const fn new() -> OnceList<T> {
|
| 65 |
+
/// OnceList { data: OnceLock::new(), next: OnceLock::new() }
|
| 66 |
+
/// }
|
| 67 |
+
/// fn push(&self, value: T) {
|
| 68 |
+
/// // FIXME: this impl is concise, but is also slow for long lists or many threads.
|
| 69 |
+
/// // as an exercise, consider how you might improve on it while preserving the behavior
|
| 70 |
+
/// if let Err(value) = self.data.set(value) {
|
| 71 |
+
/// let next = self.next.get_or_init(|| Box::new(OnceList::new()));
|
| 72 |
+
/// next.push(value)
|
| 73 |
+
/// };
|
| 74 |
+
/// }
|
| 75 |
+
/// fn contains(&self, example: &T) -> bool
|
| 76 |
+
/// where
|
| 77 |
+
/// T: PartialEq,
|
| 78 |
+
/// {
|
| 79 |
+
/// self.data.get().map(|item| item == example).filter(|v| *v).unwrap_or_else(|| {
|
| 80 |
+
/// self.next.get().map(|next| next.contains(example)).unwrap_or(false)
|
| 81 |
+
/// })
|
| 82 |
+
/// }
|
| 83 |
+
/// }
|
| 84 |
+
///
|
| 85 |
+
/// // Let's exercise this new Sync append-only list by doing a little counting
|
| 86 |
+
/// static LIST: OnceList<u32> = OnceList::new();
|
| 87 |
+
/// static COUNTER: AtomicU32 = AtomicU32::new(0);
|
| 88 |
+
///
|
| 89 |
+
/// # const LEN: u32 = if cfg!(miri) { 50 } else { 1000 };
|
| 90 |
+
/// # /*
|
| 91 |
+
/// const LEN: u32 = 1000;
|
| 92 |
+
/// # */
|
| 93 |
+
/// thread::scope(|s| {
|
| 94 |
+
/// for _ in 0..thread::available_parallelism().unwrap().get() {
|
| 95 |
+
/// s.spawn(|| {
|
| 96 |
+
/// while let i @ 0..LEN = COUNTER.fetch_add(1, Ordering::Relaxed) {
|
| 97 |
+
/// LIST.push(i);
|
| 98 |
+
/// }
|
| 99 |
+
/// });
|
| 100 |
+
/// }
|
| 101 |
+
/// });
|
| 102 |
+
///
|
| 103 |
+
/// for i in 0..LEN {
|
| 104 |
+
/// assert!(LIST.contains(&i));
|
| 105 |
+
/// }
|
| 106 |
+
///
|
| 107 |
+
/// ```
|
| 108 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 109 |
+
pub struct OnceLock<T> {
|
| 110 |
+
// FIXME(nonpoison_once): switch to nonpoison version once it is available
|
| 111 |
+
once: Once,
|
| 112 |
+
// Whether or not the value is initialized is tracked by `once.is_completed()`.
|
| 113 |
+
value: UnsafeCell<MaybeUninit<T>>,
|
| 114 |
+
/// `PhantomData` to make sure dropck understands we're dropping T in our Drop impl.
|
| 115 |
+
///
|
| 116 |
+
/// ```compile_fail,E0597
|
| 117 |
+
/// use std::sync::OnceLock;
|
| 118 |
+
///
|
| 119 |
+
/// struct A<'a>(&'a str);
|
| 120 |
+
///
|
| 121 |
+
/// impl<'a> Drop for A<'a> {
|
| 122 |
+
/// fn drop(&mut self) {}
|
| 123 |
+
/// }
|
| 124 |
+
///
|
| 125 |
+
/// let cell = OnceLock::new();
|
| 126 |
+
/// {
|
| 127 |
+
/// let s = String::new();
|
| 128 |
+
/// let _ = cell.set(A(&s));
|
| 129 |
+
/// }
|
| 130 |
+
/// ```
|
| 131 |
+
_marker: PhantomData<T>,
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
impl<T> OnceLock<T> {
|
| 135 |
+
/// Creates a new uninitialized cell.
|
| 136 |
+
#[inline]
|
| 137 |
+
#[must_use]
|
| 138 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 139 |
+
#[rustc_const_stable(feature = "once_cell", since = "1.70.0")]
|
| 140 |
+
pub const fn new() -> OnceLock<T> {
|
| 141 |
+
OnceLock {
|
| 142 |
+
once: Once::new(),
|
| 143 |
+
value: UnsafeCell::new(MaybeUninit::uninit()),
|
| 144 |
+
_marker: PhantomData,
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
/// Gets the reference to the underlying value.
|
| 149 |
+
///
|
| 150 |
+
/// Returns `None` if the cell is uninitialized, or being initialized.
|
| 151 |
+
/// This method never blocks.
|
| 152 |
+
#[inline]
|
| 153 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 154 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 155 |
+
pub fn get(&self) -> Option<&T> {
|
| 156 |
+
if self.initialized() {
|
| 157 |
+
// Safe b/c checked initialized
|
| 158 |
+
Some(unsafe { self.get_unchecked() })
|
| 159 |
+
} else {
|
| 160 |
+
None
|
| 161 |
+
}
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
/// Gets the mutable reference to the underlying value.
|
| 165 |
+
///
|
| 166 |
+
/// Returns `None` if the cell is uninitialized.
|
| 167 |
+
///
|
| 168 |
+
/// This method never blocks. Since it borrows the `OnceLock` mutably,
|
| 169 |
+
/// it is statically guaranteed that no active borrows to the `OnceLock`
|
| 170 |
+
/// exist, including from other threads.
|
| 171 |
+
#[inline]
|
| 172 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 173 |
+
pub fn get_mut(&mut self) -> Option<&mut T> {
|
| 174 |
+
if self.initialized_mut() {
|
| 175 |
+
// Safe b/c checked initialized and we have a unique access
|
| 176 |
+
Some(unsafe { self.get_unchecked_mut() })
|
| 177 |
+
} else {
|
| 178 |
+
None
|
| 179 |
+
}
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
/// Blocks the current thread until the cell is initialized.
|
| 183 |
+
///
|
| 184 |
+
/// # Example
|
| 185 |
+
///
|
| 186 |
+
/// Waiting for a computation on another thread to finish:
|
| 187 |
+
/// ```rust
|
| 188 |
+
/// use std::thread;
|
| 189 |
+
/// use std::sync::OnceLock;
|
| 190 |
+
///
|
| 191 |
+
/// let value = OnceLock::new();
|
| 192 |
+
///
|
| 193 |
+
/// thread::scope(|s| {
|
| 194 |
+
/// s.spawn(|| value.set(1 + 1));
|
| 195 |
+
///
|
| 196 |
+
/// let result = value.wait();
|
| 197 |
+
/// assert_eq!(result, &2);
|
| 198 |
+
/// })
|
| 199 |
+
/// ```
|
| 200 |
+
#[inline]
|
| 201 |
+
#[stable(feature = "once_wait", since = "1.86.0")]
|
| 202 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 203 |
+
pub fn wait(&self) -> &T {
|
| 204 |
+
self.once.wait_force();
|
| 205 |
+
|
| 206 |
+
unsafe { self.get_unchecked() }
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
/// Initializes the contents of the cell to `value`.
|
| 210 |
+
///
|
| 211 |
+
/// May block if another thread is currently attempting to initialize the cell. The cell is
|
| 212 |
+
/// guaranteed to contain a value when `set` returns, though not necessarily the one provided.
|
| 213 |
+
///
|
| 214 |
+
/// Returns `Ok(())` if the cell was uninitialized and
|
| 215 |
+
/// `Err(value)` if the cell was already initialized.
|
| 216 |
+
///
|
| 217 |
+
/// # Examples
|
| 218 |
+
///
|
| 219 |
+
/// ```
|
| 220 |
+
/// use std::sync::OnceLock;
|
| 221 |
+
///
|
| 222 |
+
/// static CELL: OnceLock<i32> = OnceLock::new();
|
| 223 |
+
///
|
| 224 |
+
/// fn main() {
|
| 225 |
+
/// assert!(CELL.get().is_none());
|
| 226 |
+
///
|
| 227 |
+
/// std::thread::spawn(|| {
|
| 228 |
+
/// assert_eq!(CELL.set(92), Ok(()));
|
| 229 |
+
/// }).join().unwrap();
|
| 230 |
+
///
|
| 231 |
+
/// assert_eq!(CELL.set(62), Err(62));
|
| 232 |
+
/// assert_eq!(CELL.get(), Some(&92));
|
| 233 |
+
/// }
|
| 234 |
+
/// ```
|
| 235 |
+
#[inline]
|
| 236 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 237 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 238 |
+
pub fn set(&self, value: T) -> Result<(), T> {
|
| 239 |
+
match self.try_insert(value) {
|
| 240 |
+
Ok(_) => Ok(()),
|
| 241 |
+
Err((_, value)) => Err(value),
|
| 242 |
+
}
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
/// Initializes the contents of the cell to `value` if the cell was uninitialized,
|
| 246 |
+
/// then returns a reference to it.
|
| 247 |
+
///
|
| 248 |
+
/// May block if another thread is currently attempting to initialize the cell. The cell is
|
| 249 |
+
/// guaranteed to contain a value when `try_insert` returns, though not necessarily the
|
| 250 |
+
/// one provided.
|
| 251 |
+
///
|
| 252 |
+
/// Returns `Ok(&value)` if the cell was uninitialized and
|
| 253 |
+
/// `Err((¤t_value, value))` if it was already initialized.
|
| 254 |
+
///
|
| 255 |
+
/// # Examples
|
| 256 |
+
///
|
| 257 |
+
/// ```
|
| 258 |
+
/// #![feature(once_cell_try_insert)]
|
| 259 |
+
///
|
| 260 |
+
/// use std::sync::OnceLock;
|
| 261 |
+
///
|
| 262 |
+
/// static CELL: OnceLock<i32> = OnceLock::new();
|
| 263 |
+
///
|
| 264 |
+
/// fn main() {
|
| 265 |
+
/// assert!(CELL.get().is_none());
|
| 266 |
+
///
|
| 267 |
+
/// std::thread::spawn(|| {
|
| 268 |
+
/// assert_eq!(CELL.try_insert(92), Ok(&92));
|
| 269 |
+
/// }).join().unwrap();
|
| 270 |
+
///
|
| 271 |
+
/// assert_eq!(CELL.try_insert(62), Err((&92, 62)));
|
| 272 |
+
/// assert_eq!(CELL.get(), Some(&92));
|
| 273 |
+
/// }
|
| 274 |
+
/// ```
|
| 275 |
+
#[inline]
|
| 276 |
+
#[unstable(feature = "once_cell_try_insert", issue = "116693")]
|
| 277 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 278 |
+
pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
|
| 279 |
+
let mut value = Some(value);
|
| 280 |
+
let res = self.get_or_init(|| value.take().unwrap());
|
| 281 |
+
match value {
|
| 282 |
+
None => Ok(res),
|
| 283 |
+
Some(value) => Err((res, value)),
|
| 284 |
+
}
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
/// Gets the contents of the cell, initializing it to `f()` if the cell
|
| 288 |
+
/// was uninitialized.
|
| 289 |
+
///
|
| 290 |
+
/// Many threads may call `get_or_init` concurrently with different
|
| 291 |
+
/// initializing functions, but it is guaranteed that only one function
|
| 292 |
+
/// will be executed if the function doesn't panic.
|
| 293 |
+
///
|
| 294 |
+
/// # Panics
|
| 295 |
+
///
|
| 296 |
+
/// If `f()` panics, the panic is propagated to the caller, and the cell
|
| 297 |
+
/// remains uninitialized.
|
| 298 |
+
///
|
| 299 |
+
/// It is an error to reentrantly initialize the cell from `f`. The
|
| 300 |
+
/// exact outcome is unspecified. Current implementation deadlocks, but
|
| 301 |
+
/// this may be changed to a panic in the future.
|
| 302 |
+
///
|
| 303 |
+
/// # Examples
|
| 304 |
+
///
|
| 305 |
+
/// ```
|
| 306 |
+
/// use std::sync::OnceLock;
|
| 307 |
+
///
|
| 308 |
+
/// let cell = OnceLock::new();
|
| 309 |
+
/// let value = cell.get_or_init(|| 92);
|
| 310 |
+
/// assert_eq!(value, &92);
|
| 311 |
+
/// let value = cell.get_or_init(|| unreachable!());
|
| 312 |
+
/// assert_eq!(value, &92);
|
| 313 |
+
/// ```
|
| 314 |
+
#[inline]
|
| 315 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 316 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 317 |
+
pub fn get_or_init<F>(&self, f: F) -> &T
|
| 318 |
+
where
|
| 319 |
+
F: FnOnce() -> T,
|
| 320 |
+
{
|
| 321 |
+
match self.get_or_try_init(|| Ok::<T, !>(f())) {
|
| 322 |
+
Ok(val) => val,
|
| 323 |
+
}
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
/// Gets the mutable reference of the contents of the cell, initializing
|
| 327 |
+
/// it to `f()` if the cell was uninitialized.
|
| 328 |
+
///
|
| 329 |
+
/// This method never blocks. Since it borrows the `OnceLock` mutably,
|
| 330 |
+
/// it is statically guaranteed that no active borrows to the `OnceLock`
|
| 331 |
+
/// exist, including from other threads.
|
| 332 |
+
///
|
| 333 |
+
/// # Panics
|
| 334 |
+
///
|
| 335 |
+
/// If `f()` panics, the panic is propagated to the caller, and the cell
|
| 336 |
+
/// remains uninitialized.
|
| 337 |
+
///
|
| 338 |
+
/// # Examples
|
| 339 |
+
///
|
| 340 |
+
/// ```
|
| 341 |
+
/// #![feature(once_cell_get_mut)]
|
| 342 |
+
///
|
| 343 |
+
/// use std::sync::OnceLock;
|
| 344 |
+
///
|
| 345 |
+
/// let mut cell = OnceLock::new();
|
| 346 |
+
/// let value = cell.get_mut_or_init(|| 92);
|
| 347 |
+
/// assert_eq!(*value, 92);
|
| 348 |
+
///
|
| 349 |
+
/// *value += 2;
|
| 350 |
+
/// assert_eq!(*value, 94);
|
| 351 |
+
///
|
| 352 |
+
/// let value = cell.get_mut_or_init(|| unreachable!());
|
| 353 |
+
/// assert_eq!(*value, 94);
|
| 354 |
+
/// ```
|
| 355 |
+
#[inline]
|
| 356 |
+
#[unstable(feature = "once_cell_get_mut", issue = "121641")]
|
| 357 |
+
pub fn get_mut_or_init<F>(&mut self, f: F) -> &mut T
|
| 358 |
+
where
|
| 359 |
+
F: FnOnce() -> T,
|
| 360 |
+
{
|
| 361 |
+
match self.get_mut_or_try_init(|| Ok::<T, !>(f())) {
|
| 362 |
+
Ok(val) => val,
|
| 363 |
+
}
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
/// Gets the contents of the cell, initializing it to `f()` if
|
| 367 |
+
/// the cell was uninitialized. If the cell was uninitialized
|
| 368 |
+
/// and `f()` failed, an error is returned.
|
| 369 |
+
///
|
| 370 |
+
/// # Panics
|
| 371 |
+
///
|
| 372 |
+
/// If `f()` panics, the panic is propagated to the caller, and
|
| 373 |
+
/// the cell remains uninitialized.
|
| 374 |
+
///
|
| 375 |
+
/// It is an error to reentrantly initialize the cell from `f`.
|
| 376 |
+
/// The exact outcome is unspecified. Current implementation
|
| 377 |
+
/// deadlocks, but this may be changed to a panic in the future.
|
| 378 |
+
///
|
| 379 |
+
/// # Examples
|
| 380 |
+
///
|
| 381 |
+
/// ```
|
| 382 |
+
/// #![feature(once_cell_try)]
|
| 383 |
+
///
|
| 384 |
+
/// use std::sync::OnceLock;
|
| 385 |
+
///
|
| 386 |
+
/// let cell = OnceLock::new();
|
| 387 |
+
/// assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
|
| 388 |
+
/// assert!(cell.get().is_none());
|
| 389 |
+
/// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
|
| 390 |
+
/// Ok(92)
|
| 391 |
+
/// });
|
| 392 |
+
/// assert_eq!(value, Ok(&92));
|
| 393 |
+
/// assert_eq!(cell.get(), Some(&92))
|
| 394 |
+
/// ```
|
| 395 |
+
#[inline]
|
| 396 |
+
#[unstable(feature = "once_cell_try", issue = "109737")]
|
| 397 |
+
#[rustc_should_not_be_called_on_const_items]
|
| 398 |
+
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
|
| 399 |
+
where
|
| 400 |
+
F: FnOnce() -> Result<T, E>,
|
| 401 |
+
{
|
| 402 |
+
// Fast path check
|
| 403 |
+
// NOTE: We need to perform an acquire on the state in this method
|
| 404 |
+
// in order to correctly synchronize `LazyLock::force`. This is
|
| 405 |
+
// currently done by calling `self.get()`, which in turn calls
|
| 406 |
+
// `self.initialized()`, which in turn performs the acquire.
|
| 407 |
+
if let Some(value) = self.get() {
|
| 408 |
+
return Ok(value);
|
| 409 |
+
}
|
| 410 |
+
self.initialize(f)?;
|
| 411 |
+
|
| 412 |
+
// SAFETY: The inner value has been initialized
|
| 413 |
+
Ok(unsafe { self.get_unchecked() })
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
/// Gets the mutable reference of the contents of the cell, initializing
|
| 417 |
+
/// it to `f()` if the cell was uninitialized. If the cell was uninitialized
|
| 418 |
+
/// and `f()` failed, an error is returned.
|
| 419 |
+
///
|
| 420 |
+
/// This method never blocks. Since it borrows the `OnceLock` mutably,
|
| 421 |
+
/// it is statically guaranteed that no active borrows to the `OnceLock`
|
| 422 |
+
/// exist, including from other threads.
|
| 423 |
+
///
|
| 424 |
+
/// # Panics
|
| 425 |
+
///
|
| 426 |
+
/// If `f()` panics, the panic is propagated to the caller, and
|
| 427 |
+
/// the cell remains uninitialized.
|
| 428 |
+
///
|
| 429 |
+
/// # Examples
|
| 430 |
+
///
|
| 431 |
+
/// ```
|
| 432 |
+
/// #![feature(once_cell_get_mut)]
|
| 433 |
+
///
|
| 434 |
+
/// use std::sync::OnceLock;
|
| 435 |
+
///
|
| 436 |
+
/// let mut cell: OnceLock<u32> = OnceLock::new();
|
| 437 |
+
///
|
| 438 |
+
/// // Failed attempts to initialize the cell do not change its contents
|
| 439 |
+
/// assert!(cell.get_mut_or_try_init(|| "not a number!".parse()).is_err());
|
| 440 |
+
/// assert!(cell.get().is_none());
|
| 441 |
+
///
|
| 442 |
+
/// let value = cell.get_mut_or_try_init(|| "1234".parse());
|
| 443 |
+
/// assert_eq!(value, Ok(&mut 1234));
|
| 444 |
+
/// *value.unwrap() += 2;
|
| 445 |
+
/// assert_eq!(cell.get(), Some(&1236))
|
| 446 |
+
/// ```
|
| 447 |
+
#[inline]
|
| 448 |
+
#[unstable(feature = "once_cell_get_mut", issue = "121641")]
|
| 449 |
+
pub fn get_mut_or_try_init<F, E>(&mut self, f: F) -> Result<&mut T, E>
|
| 450 |
+
where
|
| 451 |
+
F: FnOnce() -> Result<T, E>,
|
| 452 |
+
{
|
| 453 |
+
if self.get_mut().is_none() {
|
| 454 |
+
self.initialize(f)?;
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
// SAFETY: The inner value has been initialized
|
| 458 |
+
Ok(unsafe { self.get_unchecked_mut() })
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
/// Consumes the `OnceLock`, returning the wrapped value. Returns
|
| 462 |
+
/// `None` if the cell was uninitialized.
|
| 463 |
+
///
|
| 464 |
+
/// # Examples
|
| 465 |
+
///
|
| 466 |
+
/// ```
|
| 467 |
+
/// use std::sync::OnceLock;
|
| 468 |
+
///
|
| 469 |
+
/// let cell: OnceLock<String> = OnceLock::new();
|
| 470 |
+
/// assert_eq!(cell.into_inner(), None);
|
| 471 |
+
///
|
| 472 |
+
/// let cell = OnceLock::new();
|
| 473 |
+
/// cell.set("hello".to_string()).unwrap();
|
| 474 |
+
/// assert_eq!(cell.into_inner(), Some("hello".to_string()));
|
| 475 |
+
/// ```
|
| 476 |
+
#[inline]
|
| 477 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 478 |
+
pub fn into_inner(mut self) -> Option<T> {
|
| 479 |
+
self.take()
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
/// Takes the value out of this `OnceLock`, moving it back to an uninitialized state.
|
| 483 |
+
///
|
| 484 |
+
/// Has no effect and returns `None` if the `OnceLock` was uninitialized.
|
| 485 |
+
///
|
| 486 |
+
/// Since this method borrows the `OnceLock` mutably, it is statically guaranteed that
|
| 487 |
+
/// no active borrows to the `OnceLock` exist, including from other threads.
|
| 488 |
+
///
|
| 489 |
+
/// # Examples
|
| 490 |
+
///
|
| 491 |
+
/// ```
|
| 492 |
+
/// use std::sync::OnceLock;
|
| 493 |
+
///
|
| 494 |
+
/// let mut cell: OnceLock<String> = OnceLock::new();
|
| 495 |
+
/// assert_eq!(cell.take(), None);
|
| 496 |
+
///
|
| 497 |
+
/// let mut cell = OnceLock::new();
|
| 498 |
+
/// cell.set("hello".to_string()).unwrap();
|
| 499 |
+
/// assert_eq!(cell.take(), Some("hello".to_string()));
|
| 500 |
+
/// assert_eq!(cell.get(), None);
|
| 501 |
+
/// ```
|
| 502 |
+
#[inline]
|
| 503 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 504 |
+
pub fn take(&mut self) -> Option<T> {
|
| 505 |
+
if self.initialized_mut() {
|
| 506 |
+
self.once = Once::new();
|
| 507 |
+
// SAFETY: `self.value` is initialized and contains a valid `T`.
|
| 508 |
+
// `self.once` is reset, so `initialized()` will be false again
|
| 509 |
+
// which prevents the value from being read twice.
|
| 510 |
+
unsafe { Some(self.value.get_mut().assume_init_read()) }
|
| 511 |
+
} else {
|
| 512 |
+
None
|
| 513 |
+
}
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
#[inline]
|
| 517 |
+
fn initialized(&self) -> bool {
|
| 518 |
+
self.once.is_completed()
|
| 519 |
+
}
|
| 520 |
+
|
| 521 |
+
#[inline]
|
| 522 |
+
fn initialized_mut(&mut self) -> bool {
|
| 523 |
+
// `state()` does not perform an atomic load, so prefer it over `is_complete()`.
|
| 524 |
+
let state = self.once.state();
|
| 525 |
+
match state {
|
| 526 |
+
OnceExclusiveState::Complete => true,
|
| 527 |
+
_ => false,
|
| 528 |
+
}
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
#[cold]
|
| 532 |
+
#[optimize(size)]
|
| 533 |
+
fn initialize<F, E>(&self, f: F) -> Result<(), E>
|
| 534 |
+
where
|
| 535 |
+
F: FnOnce() -> Result<T, E>,
|
| 536 |
+
{
|
| 537 |
+
let mut res: Result<(), E> = Ok(());
|
| 538 |
+
let slot = &self.value;
|
| 539 |
+
|
| 540 |
+
// Ignore poisoning from other threads
|
| 541 |
+
// If another thread panics, then we'll be able to run our closure
|
| 542 |
+
self.once.call_once_force(|p| {
|
| 543 |
+
match f() {
|
| 544 |
+
Ok(value) => {
|
| 545 |
+
unsafe { (&mut *slot.get()).write(value) };
|
| 546 |
+
}
|
| 547 |
+
Err(e) => {
|
| 548 |
+
res = Err(e);
|
| 549 |
+
|
| 550 |
+
// Treat the underlying `Once` as poisoned since we
|
| 551 |
+
// failed to initialize our value.
|
| 552 |
+
p.poison();
|
| 553 |
+
}
|
| 554 |
+
}
|
| 555 |
+
});
|
| 556 |
+
res
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
/// # Safety
|
| 560 |
+
///
|
| 561 |
+
/// The cell must be initialized
|
| 562 |
+
#[inline]
|
| 563 |
+
unsafe fn get_unchecked(&self) -> &T {
|
| 564 |
+
debug_assert!(self.initialized());
|
| 565 |
+
unsafe { (&*self.value.get()).assume_init_ref() }
|
| 566 |
+
}
|
| 567 |
+
|
| 568 |
+
/// # Safety
|
| 569 |
+
///
|
| 570 |
+
/// The cell must be initialized
|
| 571 |
+
#[inline]
|
| 572 |
+
unsafe fn get_unchecked_mut(&mut self) -> &mut T {
|
| 573 |
+
debug_assert!(self.initialized_mut());
|
| 574 |
+
unsafe { self.value.get_mut().assume_init_mut() }
|
| 575 |
+
}
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
// Why do we need `T: Send`?
|
| 579 |
+
// Thread A creates a `OnceLock` and shares it with
|
| 580 |
+
// scoped thread B, which fills the cell, which is
|
| 581 |
+
// then destroyed by A. That is, destructor observes
|
| 582 |
+
// a sent value.
|
| 583 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 584 |
+
unsafe impl<T: Sync + Send> Sync for OnceLock<T> {}
|
| 585 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 586 |
+
unsafe impl<T: Send> Send for OnceLock<T> {}
|
| 587 |
+
|
| 588 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 589 |
+
impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceLock<T> {}
|
| 590 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 591 |
+
impl<T: UnwindSafe> UnwindSafe for OnceLock<T> {}
|
| 592 |
+
|
| 593 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 594 |
+
#[rustc_const_unstable(feature = "const_default", issue = "143894")]
|
| 595 |
+
impl<T> const Default for OnceLock<T> {
|
| 596 |
+
/// Creates a new uninitialized cell.
|
| 597 |
+
///
|
| 598 |
+
/// # Example
|
| 599 |
+
///
|
| 600 |
+
/// ```
|
| 601 |
+
/// use std::sync::OnceLock;
|
| 602 |
+
///
|
| 603 |
+
/// fn main() {
|
| 604 |
+
/// assert_eq!(OnceLock::<()>::new(), OnceLock::default());
|
| 605 |
+
/// }
|
| 606 |
+
/// ```
|
| 607 |
+
#[inline]
|
| 608 |
+
fn default() -> OnceLock<T> {
|
| 609 |
+
OnceLock::new()
|
| 610 |
+
}
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 614 |
+
impl<T: fmt::Debug> fmt::Debug for OnceLock<T> {
|
| 615 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 616 |
+
let mut d = f.debug_tuple("OnceLock");
|
| 617 |
+
match self.get() {
|
| 618 |
+
Some(v) => d.field(v),
|
| 619 |
+
None => d.field(&format_args!("<uninit>")),
|
| 620 |
+
};
|
| 621 |
+
d.finish()
|
| 622 |
+
}
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 626 |
+
impl<T: Clone> Clone for OnceLock<T> {
|
| 627 |
+
#[inline]
|
| 628 |
+
fn clone(&self) -> OnceLock<T> {
|
| 629 |
+
let cell = Self::new();
|
| 630 |
+
if let Some(value) = self.get() {
|
| 631 |
+
match cell.set(value.clone()) {
|
| 632 |
+
Ok(()) => (),
|
| 633 |
+
Err(_) => unreachable!(),
|
| 634 |
+
}
|
| 635 |
+
}
|
| 636 |
+
cell
|
| 637 |
+
}
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 641 |
+
impl<T> From<T> for OnceLock<T> {
|
| 642 |
+
/// Creates a new cell with its contents set to `value`.
|
| 643 |
+
///
|
| 644 |
+
/// # Example
|
| 645 |
+
///
|
| 646 |
+
/// ```
|
| 647 |
+
/// use std::sync::OnceLock;
|
| 648 |
+
///
|
| 649 |
+
/// # fn main() -> Result<(), i32> {
|
| 650 |
+
/// let a = OnceLock::from(3);
|
| 651 |
+
/// let b = OnceLock::new();
|
| 652 |
+
/// b.set(3)?;
|
| 653 |
+
/// assert_eq!(a, b);
|
| 654 |
+
/// Ok(())
|
| 655 |
+
/// # }
|
| 656 |
+
/// ```
|
| 657 |
+
#[inline]
|
| 658 |
+
fn from(value: T) -> Self {
|
| 659 |
+
let cell = Self::new();
|
| 660 |
+
match cell.set(value) {
|
| 661 |
+
Ok(()) => cell,
|
| 662 |
+
Err(_) => unreachable!(),
|
| 663 |
+
}
|
| 664 |
+
}
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 668 |
+
impl<T: PartialEq> PartialEq for OnceLock<T> {
|
| 669 |
+
/// Equality for two `OnceLock`s.
|
| 670 |
+
///
|
| 671 |
+
/// Two `OnceLock`s are equal if they either both contain values and their
|
| 672 |
+
/// values are equal, or if neither contains a value.
|
| 673 |
+
///
|
| 674 |
+
/// # Examples
|
| 675 |
+
///
|
| 676 |
+
/// ```
|
| 677 |
+
/// use std::sync::OnceLock;
|
| 678 |
+
///
|
| 679 |
+
/// let five = OnceLock::new();
|
| 680 |
+
/// five.set(5).unwrap();
|
| 681 |
+
///
|
| 682 |
+
/// let also_five = OnceLock::new();
|
| 683 |
+
/// also_five.set(5).unwrap();
|
| 684 |
+
///
|
| 685 |
+
/// assert!(five == also_five);
|
| 686 |
+
///
|
| 687 |
+
/// assert!(OnceLock::<u32>::new() == OnceLock::<u32>::new());
|
| 688 |
+
/// ```
|
| 689 |
+
#[inline]
|
| 690 |
+
fn eq(&self, other: &OnceLock<T>) -> bool {
|
| 691 |
+
self.get() == other.get()
|
| 692 |
+
}
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 696 |
+
impl<T: Eq> Eq for OnceLock<T> {}
|
| 697 |
+
|
| 698 |
+
#[stable(feature = "once_cell", since = "1.70.0")]
|
| 699 |
+
unsafe impl<#[may_dangle] T> Drop for OnceLock<T> {
|
| 700 |
+
#[inline]
|
| 701 |
+
fn drop(&mut self) {
|
| 702 |
+
if self.initialized_mut() {
|
| 703 |
+
// SAFETY: The cell is initialized and being dropped, so it can't
|
| 704 |
+
// be accessed again. We also don't touch the `T` other than
|
| 705 |
+
// dropping it, which validates our usage of #[may_dangle].
|
| 706 |
+
unsafe { self.value.get_mut().assume_init_drop() };
|
| 707 |
+
}
|
| 708 |
+
}
|
| 709 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/oneshot.rs
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! A single-producer, single-consumer (oneshot) channel.
|
| 2 |
+
//!
|
| 3 |
+
//! This is an experimental module, so the API will likely change.
|
| 4 |
+
|
| 5 |
+
use crate::sync::mpmc;
|
| 6 |
+
use crate::sync::mpsc::{RecvError, SendError};
|
| 7 |
+
use crate::time::{Duration, Instant};
|
| 8 |
+
use crate::{error, fmt};
|
| 9 |
+
|
| 10 |
+
/// Creates a new oneshot channel, returning the sender/receiver halves.
|
| 11 |
+
///
|
| 12 |
+
/// # Examples
|
| 13 |
+
///
|
| 14 |
+
/// ```
|
| 15 |
+
/// #![feature(oneshot_channel)]
|
| 16 |
+
/// use std::sync::oneshot;
|
| 17 |
+
/// use std::thread;
|
| 18 |
+
///
|
| 19 |
+
/// let (sender, receiver) = oneshot::channel();
|
| 20 |
+
///
|
| 21 |
+
/// // Spawn off an expensive computation.
|
| 22 |
+
/// thread::spawn(move || {
|
| 23 |
+
/// # fn expensive_computation() -> i32 { 42 }
|
| 24 |
+
/// sender.send(expensive_computation()).unwrap();
|
| 25 |
+
/// // `sender` is consumed by `send`, so we cannot use it anymore.
|
| 26 |
+
/// });
|
| 27 |
+
///
|
| 28 |
+
/// # fn do_other_work() -> i32 { 42 }
|
| 29 |
+
/// do_other_work();
|
| 30 |
+
///
|
| 31 |
+
/// // Let's see what that answer was...
|
| 32 |
+
/// println!("{:?}", receiver.recv().unwrap());
|
| 33 |
+
/// // `receiver` is consumed by `recv`, so we cannot use it anymore.
|
| 34 |
+
/// ```
|
| 35 |
+
#[must_use]
|
| 36 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 37 |
+
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
|
| 38 |
+
// Using a `sync_channel` with capacity 1 means that the internal implementation will use the
|
| 39 |
+
// `Array`-flavored channel implementation.
|
| 40 |
+
let (sender, receiver) = mpmc::sync_channel(1);
|
| 41 |
+
(Sender { inner: sender }, Receiver { inner: receiver })
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
////////////////////////////////////////////////////////////////////////////////////////////////////
|
| 45 |
+
// Sender
|
| 46 |
+
////////////////////////////////////////////////////////////////////////////////////////////////////
|
| 47 |
+
|
| 48 |
+
/// The sending half of a oneshot channel.
|
| 49 |
+
///
|
| 50 |
+
/// # Examples
|
| 51 |
+
///
|
| 52 |
+
/// ```
|
| 53 |
+
/// #![feature(oneshot_channel)]
|
| 54 |
+
/// use std::sync::oneshot;
|
| 55 |
+
/// use std::thread;
|
| 56 |
+
///
|
| 57 |
+
/// let (sender, receiver) = oneshot::channel();
|
| 58 |
+
///
|
| 59 |
+
/// thread::spawn(move || {
|
| 60 |
+
/// sender.send("Hello from thread!").unwrap();
|
| 61 |
+
/// });
|
| 62 |
+
///
|
| 63 |
+
/// assert_eq!(receiver.recv().unwrap(), "Hello from thread!");
|
| 64 |
+
/// ```
|
| 65 |
+
///
|
| 66 |
+
/// `Sender` cannot be sent between threads if it is sending non-`Send` types.
|
| 67 |
+
///
|
| 68 |
+
/// ```compile_fail
|
| 69 |
+
/// #![feature(oneshot_channel)]
|
| 70 |
+
/// use std::sync::oneshot;
|
| 71 |
+
/// use std::thread;
|
| 72 |
+
/// use std::ptr;
|
| 73 |
+
///
|
| 74 |
+
/// let (sender, receiver) = oneshot::channel();
|
| 75 |
+
///
|
| 76 |
+
/// struct NotSend(*mut ());
|
| 77 |
+
/// thread::spawn(move || {
|
| 78 |
+
/// sender.send(NotSend(ptr::null_mut()));
|
| 79 |
+
/// });
|
| 80 |
+
///
|
| 81 |
+
/// let reply = receiver.try_recv().unwrap();
|
| 82 |
+
/// ```
|
| 83 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 84 |
+
pub struct Sender<T> {
|
| 85 |
+
/// The `oneshot` channel is simply a wrapper around a `mpmc` channel.
|
| 86 |
+
inner: mpmc::Sender<T>,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
// SAFETY: Since the only methods in which synchronization must occur take full ownership of the
|
| 90 |
+
// [`Sender`], it is perfectly safe to share a `&Sender` between threads (as it is effectively
|
| 91 |
+
// useless without ownership).
|
| 92 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 93 |
+
unsafe impl<T> Sync for Sender<T> {}
|
| 94 |
+
|
| 95 |
+
impl<T> Sender<T> {
|
| 96 |
+
/// Attempts to send a value through this channel. This can only fail if the corresponding
|
| 97 |
+
/// [`Receiver<T>`] has been dropped.
|
| 98 |
+
///
|
| 99 |
+
/// This method is non-blocking (wait-free).
|
| 100 |
+
///
|
| 101 |
+
/// # Examples
|
| 102 |
+
///
|
| 103 |
+
/// ```
|
| 104 |
+
/// #![feature(oneshot_channel)]
|
| 105 |
+
/// use std::sync::oneshot;
|
| 106 |
+
/// use std::thread;
|
| 107 |
+
///
|
| 108 |
+
/// let (tx, rx) = oneshot::channel();
|
| 109 |
+
///
|
| 110 |
+
/// thread::spawn(move || {
|
| 111 |
+
/// // Perform some computation.
|
| 112 |
+
/// let result = 2 + 2;
|
| 113 |
+
/// tx.send(result).unwrap();
|
| 114 |
+
/// });
|
| 115 |
+
///
|
| 116 |
+
/// assert_eq!(rx.recv().unwrap(), 4);
|
| 117 |
+
/// ```
|
| 118 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 119 |
+
pub fn send(self, t: T) -> Result<(), SendError<T>> {
|
| 120 |
+
self.inner.send(t)
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 125 |
+
impl<T> fmt::Debug for Sender<T> {
|
| 126 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 127 |
+
f.debug_struct("Sender").finish_non_exhaustive()
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
////////////////////////////////////////////////////////////////////////////////////////////////////
|
| 132 |
+
// Receiver
|
| 133 |
+
////////////////////////////////////////////////////////////////////////////////////////////////////
|
| 134 |
+
|
| 135 |
+
/// The receiving half of a oneshot channel.
|
| 136 |
+
///
|
| 137 |
+
/// # Examples
|
| 138 |
+
///
|
| 139 |
+
/// ```
|
| 140 |
+
/// #![feature(oneshot_channel)]
|
| 141 |
+
/// use std::sync::oneshot;
|
| 142 |
+
/// use std::thread;
|
| 143 |
+
/// use std::time::Duration;
|
| 144 |
+
///
|
| 145 |
+
/// let (sender, receiver) = oneshot::channel();
|
| 146 |
+
///
|
| 147 |
+
/// thread::spawn(move || {
|
| 148 |
+
/// thread::sleep(Duration::from_millis(100));
|
| 149 |
+
/// sender.send("Hello after delay!").unwrap();
|
| 150 |
+
/// });
|
| 151 |
+
///
|
| 152 |
+
/// println!("Waiting for message...");
|
| 153 |
+
/// println!("{}", receiver.recv().unwrap());
|
| 154 |
+
/// ```
|
| 155 |
+
///
|
| 156 |
+
/// `Receiver` cannot be sent between threads if it is receiving non-`Send` types.
|
| 157 |
+
///
|
| 158 |
+
/// ```compile_fail
|
| 159 |
+
/// # #![feature(oneshot_channel)]
|
| 160 |
+
/// # use std::sync::oneshot;
|
| 161 |
+
/// # use std::thread;
|
| 162 |
+
/// # use std::ptr;
|
| 163 |
+
/// #
|
| 164 |
+
/// let (sender, receiver) = oneshot::channel();
|
| 165 |
+
///
|
| 166 |
+
/// struct NotSend(*mut ());
|
| 167 |
+
/// sender.send(NotSend(ptr::null_mut()));
|
| 168 |
+
///
|
| 169 |
+
/// thread::spawn(move || {
|
| 170 |
+
/// let reply = receiver.try_recv().unwrap();
|
| 171 |
+
/// });
|
| 172 |
+
/// ```
|
| 173 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 174 |
+
pub struct Receiver<T> {
|
| 175 |
+
/// The `oneshot` channel is simply a wrapper around a `mpmc` channel.
|
| 176 |
+
inner: mpmc::Receiver<T>,
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
// SAFETY: Since the only methods in which synchronization must occur take full ownership of the
|
| 180 |
+
// [`Receiver`], it is perfectly safe to share a `&Receiver` between threads (as it is unable to
|
| 181 |
+
// receive any values without ownership).
|
| 182 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 183 |
+
unsafe impl<T> Sync for Receiver<T> {}
|
| 184 |
+
|
| 185 |
+
impl<T> Receiver<T> {
|
| 186 |
+
/// Receives the value from the sending end, blocking the calling thread until it gets it.
|
| 187 |
+
///
|
| 188 |
+
/// Can only fail if the corresponding [`Sender<T>`] has been dropped.
|
| 189 |
+
///
|
| 190 |
+
/// # Examples
|
| 191 |
+
///
|
| 192 |
+
/// ```
|
| 193 |
+
/// #![feature(oneshot_channel)]
|
| 194 |
+
/// use std::sync::oneshot;
|
| 195 |
+
/// use std::thread;
|
| 196 |
+
/// use std::time::Duration;
|
| 197 |
+
///
|
| 198 |
+
/// let (tx, rx) = oneshot::channel();
|
| 199 |
+
///
|
| 200 |
+
/// thread::spawn(move || {
|
| 201 |
+
/// thread::sleep(Duration::from_millis(500));
|
| 202 |
+
/// tx.send("Done!").unwrap();
|
| 203 |
+
/// });
|
| 204 |
+
///
|
| 205 |
+
/// // This will block until the message arrives.
|
| 206 |
+
/// println!("{}", rx.recv().unwrap());
|
| 207 |
+
/// ```
|
| 208 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 209 |
+
pub fn recv(self) -> Result<T, RecvError> {
|
| 210 |
+
self.inner.recv()
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
// Fallible methods.
|
| 214 |
+
|
| 215 |
+
/// Attempts to return a pending value on this receiver without blocking.
|
| 216 |
+
///
|
| 217 |
+
/// # Examples
|
| 218 |
+
///
|
| 219 |
+
/// ```
|
| 220 |
+
/// #![feature(oneshot_channel)]
|
| 221 |
+
/// use std::sync::oneshot;
|
| 222 |
+
/// use std::thread;
|
| 223 |
+
/// use std::time::Duration;
|
| 224 |
+
///
|
| 225 |
+
/// let (sender, mut receiver) = oneshot::channel();
|
| 226 |
+
///
|
| 227 |
+
/// thread::spawn(move || {
|
| 228 |
+
/// thread::sleep(Duration::from_millis(100));
|
| 229 |
+
/// sender.send(42).unwrap();
|
| 230 |
+
/// });
|
| 231 |
+
///
|
| 232 |
+
/// // Keep trying until we get the message, doing other work in the process.
|
| 233 |
+
/// loop {
|
| 234 |
+
/// match receiver.try_recv() {
|
| 235 |
+
/// Ok(value) => {
|
| 236 |
+
/// assert_eq!(value, 42);
|
| 237 |
+
/// break;
|
| 238 |
+
/// }
|
| 239 |
+
/// Err(oneshot::TryRecvError::Empty(rx)) => {
|
| 240 |
+
/// // Retake ownership of the receiver.
|
| 241 |
+
/// receiver = rx;
|
| 242 |
+
/// # fn do_other_work() { thread::sleep(Duration::from_millis(25)); }
|
| 243 |
+
/// do_other_work();
|
| 244 |
+
/// }
|
| 245 |
+
/// Err(oneshot::TryRecvError::Disconnected) => panic!("Sender disconnected"),
|
| 246 |
+
/// }
|
| 247 |
+
/// }
|
| 248 |
+
/// ```
|
| 249 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 250 |
+
pub fn try_recv(self) -> Result<T, TryRecvError<T>> {
|
| 251 |
+
self.inner.try_recv().map_err(|err| match err {
|
| 252 |
+
mpmc::TryRecvError::Empty => TryRecvError::Empty(self),
|
| 253 |
+
mpmc::TryRecvError::Disconnected => TryRecvError::Disconnected,
|
| 254 |
+
})
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
/// Attempts to wait for a value on this receiver, returning an error if the corresponding
|
| 258 |
+
/// [`Sender`] half of this channel has been dropped, or if it waits more than `timeout`.
|
| 259 |
+
///
|
| 260 |
+
/// # Examples
|
| 261 |
+
///
|
| 262 |
+
/// ```
|
| 263 |
+
/// #![feature(oneshot_channel)]
|
| 264 |
+
/// use std::sync::oneshot;
|
| 265 |
+
/// use std::thread;
|
| 266 |
+
/// use std::time::Duration;
|
| 267 |
+
///
|
| 268 |
+
/// let (sender, receiver) = oneshot::channel();
|
| 269 |
+
///
|
| 270 |
+
/// thread::spawn(move || {
|
| 271 |
+
/// thread::sleep(Duration::from_millis(500));
|
| 272 |
+
/// sender.send("Success!").unwrap();
|
| 273 |
+
/// });
|
| 274 |
+
///
|
| 275 |
+
/// // Wait up to 1 second for the message
|
| 276 |
+
/// match receiver.recv_timeout(Duration::from_secs(1)) {
|
| 277 |
+
/// Ok(msg) => println!("Received: {}", msg),
|
| 278 |
+
/// Err(oneshot::RecvTimeoutError::Timeout(_)) => println!("Timed out!"),
|
| 279 |
+
/// Err(oneshot::RecvTimeoutError::Disconnected) => println!("Sender dropped!"),
|
| 280 |
+
/// }
|
| 281 |
+
/// ```
|
| 282 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 283 |
+
pub fn recv_timeout(self, timeout: Duration) -> Result<T, RecvTimeoutError<T>> {
|
| 284 |
+
self.inner.recv_timeout(timeout).map_err(|err| match err {
|
| 285 |
+
mpmc::RecvTimeoutError::Timeout => RecvTimeoutError::Timeout(self),
|
| 286 |
+
mpmc::RecvTimeoutError::Disconnected => RecvTimeoutError::Disconnected,
|
| 287 |
+
})
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
/// Attempts to wait for a value on this receiver, returning an error if the corresponding
|
| 291 |
+
/// [`Sender`] half of this channel has been dropped, or if `deadline` is reached.
|
| 292 |
+
///
|
| 293 |
+
/// # Examples
|
| 294 |
+
///
|
| 295 |
+
/// ```
|
| 296 |
+
/// #![feature(oneshot_channel)]
|
| 297 |
+
/// use std::sync::oneshot;
|
| 298 |
+
/// use std::thread;
|
| 299 |
+
/// use std::time::{Duration, Instant};
|
| 300 |
+
///
|
| 301 |
+
/// let (sender, receiver) = oneshot::channel();
|
| 302 |
+
///
|
| 303 |
+
/// thread::spawn(move || {
|
| 304 |
+
/// thread::sleep(Duration::from_millis(100));
|
| 305 |
+
/// sender.send("Just in time!").unwrap();
|
| 306 |
+
/// });
|
| 307 |
+
///
|
| 308 |
+
/// let deadline = Instant::now() + Duration::from_millis(500);
|
| 309 |
+
/// match receiver.recv_deadline(deadline) {
|
| 310 |
+
/// Ok(msg) => println!("Received: {}", msg),
|
| 311 |
+
/// Err(oneshot::RecvTimeoutError::Timeout(_)) => println!("Missed deadline!"),
|
| 312 |
+
/// Err(oneshot::RecvTimeoutError::Disconnected) => println!("Sender dropped!"),
|
| 313 |
+
/// }
|
| 314 |
+
/// ```
|
| 315 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 316 |
+
pub fn recv_deadline(self, deadline: Instant) -> Result<T, RecvTimeoutError<T>> {
|
| 317 |
+
self.inner.recv_deadline(deadline).map_err(|err| match err {
|
| 318 |
+
mpmc::RecvTimeoutError::Timeout => RecvTimeoutError::Timeout(self),
|
| 319 |
+
mpmc::RecvTimeoutError::Disconnected => RecvTimeoutError::Disconnected,
|
| 320 |
+
})
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 325 |
+
impl<T> fmt::Debug for Receiver<T> {
|
| 326 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 327 |
+
f.debug_struct("Receiver").finish_non_exhaustive()
|
| 328 |
+
}
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
////////////////////////////////////////////////////////////////////////////////////////////////////
|
| 332 |
+
// Receiver Errors
|
| 333 |
+
////////////////////////////////////////////////////////////////////////////////////////////////////
|
| 334 |
+
|
| 335 |
+
/// An error returned from the [`try_recv`](Receiver::try_recv) method.
|
| 336 |
+
///
|
| 337 |
+
/// See the documentation for [`try_recv`] for more information on how to use this error.
|
| 338 |
+
///
|
| 339 |
+
/// [`try_recv`]: Receiver::try_recv
|
| 340 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 341 |
+
pub enum TryRecvError<T> {
|
| 342 |
+
/// The [`Sender`] has not sent a message yet, but it might in the future (as it has not yet
|
| 343 |
+
/// disconnected). This variant contains the [`Receiver`] that [`try_recv`](Receiver::try_recv)
|
| 344 |
+
/// took ownership over.
|
| 345 |
+
Empty(Receiver<T>),
|
| 346 |
+
/// The corresponding [`Sender`] half of this channel has become disconnected, and there will
|
| 347 |
+
/// never be any more data sent over the channel.
|
| 348 |
+
Disconnected,
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
/// An error returned from the [`recv_timeout`](Receiver::recv_timeout) or
|
| 352 |
+
/// [`recv_deadline`](Receiver::recv_deadline) methods.
|
| 353 |
+
///
|
| 354 |
+
/// # Examples
|
| 355 |
+
///
|
| 356 |
+
/// Usage of this error is similar to [`TryRecvError`].
|
| 357 |
+
///
|
| 358 |
+
/// ```
|
| 359 |
+
/// #![feature(oneshot_channel)]
|
| 360 |
+
/// use std::sync::oneshot::{self, RecvTimeoutError};
|
| 361 |
+
/// use std::thread;
|
| 362 |
+
/// use std::time::Duration;
|
| 363 |
+
///
|
| 364 |
+
/// let (sender, receiver) = oneshot::channel();
|
| 365 |
+
///
|
| 366 |
+
/// let send_failure = thread::spawn(move || {
|
| 367 |
+
/// // Simulate a long computation that takes longer than our timeout.
|
| 368 |
+
/// thread::sleep(Duration::from_millis(250));
|
| 369 |
+
///
|
| 370 |
+
/// // This will likely fail to send because we drop the receiver in the main thread.
|
| 371 |
+
/// sender.send("Goodbye!".to_string()).unwrap();
|
| 372 |
+
/// });
|
| 373 |
+
///
|
| 374 |
+
/// // Try to receive the message with a short timeout.
|
| 375 |
+
/// match receiver.recv_timeout(Duration::from_millis(10)) {
|
| 376 |
+
/// Ok(msg) => println!("Received: {}", msg),
|
| 377 |
+
/// Err(RecvTimeoutError::Timeout(rx)) => {
|
| 378 |
+
/// println!("Timed out waiting for message!");
|
| 379 |
+
///
|
| 380 |
+
/// // Note that you can reuse the receiver without dropping it.
|
| 381 |
+
/// drop(rx);
|
| 382 |
+
/// },
|
| 383 |
+
/// Err(RecvTimeoutError::Disconnected) => println!("Sender dropped!"),
|
| 384 |
+
/// }
|
| 385 |
+
///
|
| 386 |
+
/// send_failure.join().unwrap_err();
|
| 387 |
+
/// ```
|
| 388 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 389 |
+
pub enum RecvTimeoutError<T> {
|
| 390 |
+
/// The [`Sender`] has not sent a message yet, but it might in the future (as it has not yet
|
| 391 |
+
/// disconnected). This variant contains the [`Receiver`] that either
|
| 392 |
+
/// [`recv_timeout`](Receiver::recv_timeout) or [`recv_deadline`](Receiver::recv_deadline) took
|
| 393 |
+
/// ownership over.
|
| 394 |
+
Timeout(Receiver<T>),
|
| 395 |
+
/// The corresponding [`Sender`] half of this channel has become disconnected, and there will
|
| 396 |
+
/// never be any more data sent over the channel.
|
| 397 |
+
Disconnected,
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 401 |
+
impl<T> fmt::Debug for TryRecvError<T> {
|
| 402 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 403 |
+
f.debug_tuple("TryRecvError").finish_non_exhaustive()
|
| 404 |
+
}
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 408 |
+
impl<T> fmt::Display for TryRecvError<T> {
|
| 409 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 410 |
+
match *self {
|
| 411 |
+
TryRecvError::Empty(..) => "receiving on an empty oneshot channel".fmt(f),
|
| 412 |
+
TryRecvError::Disconnected => "receiving on a closed oneshot channel".fmt(f),
|
| 413 |
+
}
|
| 414 |
+
}
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 418 |
+
impl<T> error::Error for TryRecvError<T> {}
|
| 419 |
+
|
| 420 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 421 |
+
impl<T> From<RecvError> for TryRecvError<T> {
|
| 422 |
+
/// Converts a `RecvError` into a `TryRecvError`.
|
| 423 |
+
///
|
| 424 |
+
/// This conversion always returns `TryRecvError::Disconnected`.
|
| 425 |
+
///
|
| 426 |
+
/// No data is allocated on the heap.
|
| 427 |
+
fn from(err: RecvError) -> TryRecvError<T> {
|
| 428 |
+
match err {
|
| 429 |
+
RecvError => TryRecvError::Disconnected,
|
| 430 |
+
}
|
| 431 |
+
}
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 435 |
+
impl<T> fmt::Debug for RecvTimeoutError<T> {
|
| 436 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 437 |
+
f.debug_tuple("RecvTimeoutError").finish_non_exhaustive()
|
| 438 |
+
}
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 442 |
+
impl<T> fmt::Display for RecvTimeoutError<T> {
|
| 443 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 444 |
+
match *self {
|
| 445 |
+
RecvTimeoutError::Timeout(..) => "timed out waiting on oneshot channel".fmt(f),
|
| 446 |
+
RecvTimeoutError::Disconnected => "receiving on a closed oneshot channel".fmt(f),
|
| 447 |
+
}
|
| 448 |
+
}
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 452 |
+
impl<T> error::Error for RecvTimeoutError<T> {}
|
| 453 |
+
|
| 454 |
+
#[unstable(feature = "oneshot_channel", issue = "143674")]
|
| 455 |
+
impl<T> From<RecvError> for RecvTimeoutError<T> {
|
| 456 |
+
/// Converts a `RecvError` into a `RecvTimeoutError`.
|
| 457 |
+
///
|
| 458 |
+
/// This conversion always returns `RecvTimeoutError::Disconnected`.
|
| 459 |
+
///
|
| 460 |
+
/// No data is allocated on the heap.
|
| 461 |
+
fn from(err: RecvError) -> RecvTimeoutError<T> {
|
| 462 |
+
match err {
|
| 463 |
+
RecvError => RecvTimeoutError::Disconnected,
|
| 464 |
+
}
|
| 465 |
+
}
|
| 466 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sync/poison.rs
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Synchronization objects that employ poisoning.
|
| 2 |
+
//!
|
| 3 |
+
//! # Poisoning
|
| 4 |
+
//!
|
| 5 |
+
//! All synchronization objects in this module implement a strategy called
|
| 6 |
+
//! "poisoning" where a primitive becomes poisoned if it recognizes that some
|
| 7 |
+
//! thread has panicked while holding the exclusive access granted by the
|
| 8 |
+
//! primitive. This information is then propagated to all other threads
|
| 9 |
+
//! to signify that the data protected by this primitive is likely tainted
|
| 10 |
+
//! (some invariant is not being upheld).
|
| 11 |
+
//!
|
| 12 |
+
//! The specifics of how this "poisoned" state affects other threads and whether
|
| 13 |
+
//! the panics are recognized reliably or on a best-effort basis depend on the
|
| 14 |
+
//! primitive. See [Overview](#overview) below.
|
| 15 |
+
//!
|
| 16 |
+
//! The synchronization objects in this module have alternative implementations that do not employ
|
| 17 |
+
//! poisoning in the [`std::sync::nonpoison`] module.
|
| 18 |
+
//!
|
| 19 |
+
//! [`std::sync::nonpoison`]: crate::sync::nonpoison
|
| 20 |
+
//!
|
| 21 |
+
//! # Overview
|
| 22 |
+
//!
|
| 23 |
+
//! Below is a list of synchronization objects provided by this module
|
| 24 |
+
//! with a high-level overview for each object and a description
|
| 25 |
+
//! of how it employs "poisoning".
|
| 26 |
+
//!
|
| 27 |
+
//! - [`Condvar`]: Condition Variable, providing the ability to block
|
| 28 |
+
//! a thread while waiting for an event to occur.
|
| 29 |
+
//!
|
| 30 |
+
//! Condition variables are typically associated with
|
| 31 |
+
//! a boolean predicate (a condition) and a mutex.
|
| 32 |
+
//! This implementation is associated with [`poison::Mutex`](Mutex),
|
| 33 |
+
//! which employs poisoning.
|
| 34 |
+
//! For this reason, [`Condvar::wait()`] will return a [`LockResult`],
|
| 35 |
+
//! just like [`poison::Mutex::lock()`](Mutex::lock) does.
|
| 36 |
+
//!
|
| 37 |
+
//! - [`Mutex`]: Mutual Exclusion mechanism, which ensures that at
|
| 38 |
+
//! most one thread at a time is able to access some data.
|
| 39 |
+
//!
|
| 40 |
+
//! Panicking while holding the lock typically poisons the mutex, but it is
|
| 41 |
+
//! not guaranteed to detect this condition in all circumstances.
|
| 42 |
+
//! [`Mutex::lock()`] returns a [`LockResult`], providing a way to deal with
|
| 43 |
+
//! the poisoned state. See [`Mutex`'s documentation](Mutex#poisoning) for more.
|
| 44 |
+
//!
|
| 45 |
+
//! - [`RwLock`]: Provides a mutual exclusion mechanism which allows
|
| 46 |
+
//! multiple readers at the same time, while allowing only one
|
| 47 |
+
//! writer at a time. In some cases, this can be more efficient than
|
| 48 |
+
//! a mutex.
|
| 49 |
+
//!
|
| 50 |
+
//! This implementation, like [`Mutex`], usually becomes poisoned on a panic.
|
| 51 |
+
//! Note, however, that an `RwLock` may only be poisoned if a panic occurs
|
| 52 |
+
//! while it is locked exclusively (write mode). If a panic occurs in any reader,
|
| 53 |
+
//! then the lock will not be poisoned.
|
| 54 |
+
//!
|
| 55 |
+
//! Note that the [`Once`] type also employs poisoning, but since it has non-poisoning `force`
|
| 56 |
+
//! methods available on it, there is no separate `nonpoison` and `poison` version.
|
| 57 |
+
//!
|
| 58 |
+
//! [`Once`]: crate::sync::Once
|
| 59 |
+
|
| 60 |
+
// If we are not unwinding, `PoisonError` is uninhabited.
|
| 61 |
+
#![cfg_attr(not(panic = "unwind"), expect(unreachable_code))]
|
| 62 |
+
|
| 63 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 64 |
+
pub use self::condvar::Condvar;
|
| 65 |
+
#[unstable(feature = "mapped_lock_guards", issue = "117108")]
|
| 66 |
+
pub use self::mutex::MappedMutexGuard;
|
| 67 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 68 |
+
pub use self::mutex::{Mutex, MutexGuard};
|
| 69 |
+
#[unstable(feature = "mapped_lock_guards", issue = "117108")]
|
| 70 |
+
pub use self::rwlock::{MappedRwLockReadGuard, MappedRwLockWriteGuard};
|
| 71 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 72 |
+
pub use self::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
| 73 |
+
use crate::error::Error;
|
| 74 |
+
use crate::fmt;
|
| 75 |
+
#[cfg(panic = "unwind")]
|
| 76 |
+
use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
|
| 77 |
+
#[cfg(panic = "unwind")]
|
| 78 |
+
use crate::thread;
|
| 79 |
+
|
| 80 |
+
mod condvar;
|
| 81 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 82 |
+
mod mutex;
|
| 83 |
+
mod rwlock;
|
| 84 |
+
|
| 85 |
+
pub(crate) struct Flag {
|
| 86 |
+
#[cfg(panic = "unwind")]
|
| 87 |
+
failed: Atomic<bool>,
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// Note that the Ordering uses to access the `failed` field of `Flag` below is
|
| 91 |
+
// always `Relaxed`, and that's because this isn't actually protecting any data,
|
| 92 |
+
// it's just a flag whether we've panicked or not.
|
| 93 |
+
//
|
| 94 |
+
// The actual location that this matters is when a mutex is **locked** which is
|
| 95 |
+
// where we have external synchronization ensuring that we see memory
|
| 96 |
+
// reads/writes to this flag.
|
| 97 |
+
//
|
| 98 |
+
// As a result, if it matters, we should see the correct value for `failed` in
|
| 99 |
+
// all cases.
|
| 100 |
+
|
| 101 |
+
impl Flag {
|
| 102 |
+
#[inline]
|
| 103 |
+
pub const fn new() -> Flag {
|
| 104 |
+
Flag {
|
| 105 |
+
#[cfg(panic = "unwind")]
|
| 106 |
+
failed: AtomicBool::new(false),
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
/// Checks the flag for an unguarded borrow, where we only care about existing poison.
|
| 111 |
+
#[inline]
|
| 112 |
+
pub fn borrow(&self) -> LockResult<()> {
|
| 113 |
+
if self.get() { Err(PoisonError::new(())) } else { Ok(()) }
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
/// Checks the flag for a guarded borrow, where we may also set poison when `done`.
|
| 117 |
+
#[inline]
|
| 118 |
+
pub fn guard(&self) -> LockResult<Guard> {
|
| 119 |
+
let ret = Guard {
|
| 120 |
+
#[cfg(panic = "unwind")]
|
| 121 |
+
panicking: thread::panicking(),
|
| 122 |
+
};
|
| 123 |
+
if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) }
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
#[inline]
|
| 127 |
+
#[cfg(panic = "unwind")]
|
| 128 |
+
pub fn done(&self, guard: &Guard) {
|
| 129 |
+
if !guard.panicking && thread::panicking() {
|
| 130 |
+
self.failed.store(true, Ordering::Relaxed);
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
#[inline]
|
| 135 |
+
#[cfg(not(panic = "unwind"))]
|
| 136 |
+
pub fn done(&self, _guard: &Guard) {}
|
| 137 |
+
|
| 138 |
+
#[inline]
|
| 139 |
+
#[cfg(panic = "unwind")]
|
| 140 |
+
pub fn get(&self) -> bool {
|
| 141 |
+
self.failed.load(Ordering::Relaxed)
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
#[inline(always)]
|
| 145 |
+
#[cfg(not(panic = "unwind"))]
|
| 146 |
+
pub fn get(&self) -> bool {
|
| 147 |
+
false
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
#[inline]
|
| 151 |
+
pub fn clear(&self) {
|
| 152 |
+
#[cfg(panic = "unwind")]
|
| 153 |
+
self.failed.store(false, Ordering::Relaxed)
|
| 154 |
+
}
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
#[derive(Clone)]
|
| 158 |
+
pub(crate) struct Guard {
|
| 159 |
+
#[cfg(panic = "unwind")]
|
| 160 |
+
panicking: bool,
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
/// A type of error which can be returned whenever a lock is acquired.
|
| 164 |
+
///
|
| 165 |
+
/// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
|
| 166 |
+
/// is held. The precise semantics for when a lock is poisoned is documented on
|
| 167 |
+
/// each lock. For a lock in the poisoned state, unless the state is cleared manually,
|
| 168 |
+
/// all future acquisitions will return this error.
|
| 169 |
+
///
|
| 170 |
+
/// # Examples
|
| 171 |
+
///
|
| 172 |
+
/// ```
|
| 173 |
+
/// use std::sync::{Arc, Mutex};
|
| 174 |
+
/// use std::thread;
|
| 175 |
+
///
|
| 176 |
+
/// let mutex = Arc::new(Mutex::new(1));
|
| 177 |
+
///
|
| 178 |
+
/// // poison the mutex
|
| 179 |
+
/// let c_mutex = Arc::clone(&mutex);
|
| 180 |
+
/// let _ = thread::spawn(move || {
|
| 181 |
+
/// let mut data = c_mutex.lock().unwrap();
|
| 182 |
+
/// *data = 2;
|
| 183 |
+
/// panic!();
|
| 184 |
+
/// }).join();
|
| 185 |
+
///
|
| 186 |
+
/// match mutex.lock() {
|
| 187 |
+
/// Ok(_) => unreachable!(),
|
| 188 |
+
/// Err(p_err) => {
|
| 189 |
+
/// let data = p_err.get_ref();
|
| 190 |
+
/// println!("recovered: {data}");
|
| 191 |
+
/// }
|
| 192 |
+
/// };
|
| 193 |
+
/// ```
|
| 194 |
+
/// [`Mutex`]: crate::sync::Mutex
|
| 195 |
+
/// [`RwLock`]: crate::sync::RwLock
|
| 196 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 197 |
+
pub struct PoisonError<T> {
|
| 198 |
+
data: T,
|
| 199 |
+
#[cfg(not(panic = "unwind"))]
|
| 200 |
+
_never: !,
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
/// An enumeration of possible errors associated with a [`TryLockResult`] which
|
| 204 |
+
/// can occur while trying to acquire a lock, from the [`try_lock`] method on a
|
| 205 |
+
/// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
|
| 206 |
+
///
|
| 207 |
+
/// [`try_lock`]: crate::sync::Mutex::try_lock
|
| 208 |
+
/// [`try_read`]: crate::sync::RwLock::try_read
|
| 209 |
+
/// [`try_write`]: crate::sync::RwLock::try_write
|
| 210 |
+
/// [`Mutex`]: crate::sync::Mutex
|
| 211 |
+
/// [`RwLock`]: crate::sync::RwLock
|
| 212 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 213 |
+
pub enum TryLockError<T> {
|
| 214 |
+
/// The lock could not be acquired because another thread failed while holding
|
| 215 |
+
/// the lock.
|
| 216 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 217 |
+
Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
|
| 218 |
+
/// The lock could not be acquired at this time because the operation would
|
| 219 |
+
/// otherwise block.
|
| 220 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 221 |
+
WouldBlock,
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
/// A type alias for the result of a lock method which can be poisoned.
|
| 225 |
+
///
|
| 226 |
+
/// The [`Ok`] variant of this result indicates that the primitive was not
|
| 227 |
+
/// poisoned, and the operation result is contained within. The [`Err`] variant indicates
|
| 228 |
+
/// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
|
| 229 |
+
/// an associated value assigned by the lock method, and it can be acquired through the
|
| 230 |
+
/// [`into_inner`] method. The semantics of the associated value depends on the corresponding
|
| 231 |
+
/// lock method.
|
| 232 |
+
///
|
| 233 |
+
/// [`into_inner`]: PoisonError::into_inner
|
| 234 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 235 |
+
pub type LockResult<T> = Result<T, PoisonError<T>>;
|
| 236 |
+
|
| 237 |
+
/// A type alias for the result of a nonblocking locking method.
|
| 238 |
+
///
|
| 239 |
+
/// For more information, see [`LockResult`]. A `TryLockResult` doesn't
|
| 240 |
+
/// necessarily hold the associated guard in the [`Err`] type as the lock might not
|
| 241 |
+
/// have been acquired for other reasons.
|
| 242 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 243 |
+
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
|
| 244 |
+
|
| 245 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 246 |
+
impl<T> fmt::Debug for PoisonError<T> {
|
| 247 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 248 |
+
f.debug_struct("PoisonError").finish_non_exhaustive()
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 253 |
+
impl<T> fmt::Display for PoisonError<T> {
|
| 254 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 255 |
+
"poisoned lock: another task failed inside".fmt(f)
|
| 256 |
+
}
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 260 |
+
impl<T> Error for PoisonError<T> {}
|
| 261 |
+
|
| 262 |
+
impl<T> PoisonError<T> {
|
| 263 |
+
/// Creates a `PoisonError`.
|
| 264 |
+
///
|
| 265 |
+
/// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
|
| 266 |
+
/// or [`RwLock::read`](crate::sync::RwLock::read).
|
| 267 |
+
///
|
| 268 |
+
/// This method may panic if std was built with `panic="abort"`.
|
| 269 |
+
#[cfg(panic = "unwind")]
|
| 270 |
+
#[stable(feature = "sync_poison", since = "1.2.0")]
|
| 271 |
+
pub fn new(data: T) -> PoisonError<T> {
|
| 272 |
+
PoisonError { data }
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
/// Creates a `PoisonError`.
|
| 276 |
+
///
|
| 277 |
+
/// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
|
| 278 |
+
/// or [`RwLock::read`](crate::sync::RwLock::read).
|
| 279 |
+
///
|
| 280 |
+
/// This method may panic if std was built with `panic="abort"`.
|
| 281 |
+
#[cfg(not(panic = "unwind"))]
|
| 282 |
+
#[stable(feature = "sync_poison", since = "1.2.0")]
|
| 283 |
+
#[track_caller]
|
| 284 |
+
pub fn new(_data: T) -> PoisonError<T> {
|
| 285 |
+
panic!("PoisonError created in a libstd built with panic=\"abort\"")
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
/// Consumes this error indicating that a lock is poisoned, returning the
|
| 289 |
+
/// associated data.
|
| 290 |
+
///
|
| 291 |
+
/// # Examples
|
| 292 |
+
///
|
| 293 |
+
/// ```
|
| 294 |
+
/// use std::collections::HashSet;
|
| 295 |
+
/// use std::sync::{Arc, Mutex};
|
| 296 |
+
/// use std::thread;
|
| 297 |
+
///
|
| 298 |
+
/// let mutex = Arc::new(Mutex::new(HashSet::new()));
|
| 299 |
+
///
|
| 300 |
+
/// // poison the mutex
|
| 301 |
+
/// let c_mutex = Arc::clone(&mutex);
|
| 302 |
+
/// let _ = thread::spawn(move || {
|
| 303 |
+
/// let mut data = c_mutex.lock().unwrap();
|
| 304 |
+
/// data.insert(10);
|
| 305 |
+
/// panic!();
|
| 306 |
+
/// }).join();
|
| 307 |
+
///
|
| 308 |
+
/// let p_err = mutex.lock().unwrap_err();
|
| 309 |
+
/// let data = p_err.into_inner();
|
| 310 |
+
/// println!("recovered {} items", data.len());
|
| 311 |
+
/// ```
|
| 312 |
+
#[stable(feature = "sync_poison", since = "1.2.0")]
|
| 313 |
+
pub fn into_inner(self) -> T {
|
| 314 |
+
self.data
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
/// Reaches into this error indicating that a lock is poisoned, returning a
|
| 318 |
+
/// reference to the associated data.
|
| 319 |
+
#[stable(feature = "sync_poison", since = "1.2.0")]
|
| 320 |
+
pub fn get_ref(&self) -> &T {
|
| 321 |
+
&self.data
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
/// Reaches into this error indicating that a lock is poisoned, returning a
|
| 325 |
+
/// mutable reference to the associated data.
|
| 326 |
+
#[stable(feature = "sync_poison", since = "1.2.0")]
|
| 327 |
+
pub fn get_mut(&mut self) -> &mut T {
|
| 328 |
+
&mut self.data
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 333 |
+
impl<T> From<PoisonError<T>> for TryLockError<T> {
|
| 334 |
+
fn from(err: PoisonError<T>) -> TryLockError<T> {
|
| 335 |
+
TryLockError::Poisoned(err)
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 340 |
+
impl<T> fmt::Debug for TryLockError<T> {
|
| 341 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 342 |
+
match *self {
|
| 343 |
+
#[cfg(panic = "unwind")]
|
| 344 |
+
TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
|
| 345 |
+
#[cfg(not(panic = "unwind"))]
|
| 346 |
+
TryLockError::Poisoned(ref p) => match p._never {},
|
| 347 |
+
TryLockError::WouldBlock => "WouldBlock".fmt(f),
|
| 348 |
+
}
|
| 349 |
+
}
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 353 |
+
impl<T> fmt::Display for TryLockError<T> {
|
| 354 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 355 |
+
match *self {
|
| 356 |
+
#[cfg(panic = "unwind")]
|
| 357 |
+
TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
|
| 358 |
+
#[cfg(not(panic = "unwind"))]
|
| 359 |
+
TryLockError::Poisoned(ref p) => match p._never {},
|
| 360 |
+
TryLockError::WouldBlock => "try_lock failed because the operation would block",
|
| 361 |
+
}
|
| 362 |
+
.fmt(f)
|
| 363 |
+
}
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
#[stable(feature = "rust1", since = "1.0.0")]
|
| 367 |
+
impl<T> Error for TryLockError<T> {
|
| 368 |
+
#[allow(deprecated)]
|
| 369 |
+
fn cause(&self) -> Option<&dyn Error> {
|
| 370 |
+
match *self {
|
| 371 |
+
#[cfg(panic = "unwind")]
|
| 372 |
+
TryLockError::Poisoned(ref p) => Some(p),
|
| 373 |
+
#[cfg(not(panic = "unwind"))]
|
| 374 |
+
TryLockError::Poisoned(ref p) => match p._never {},
|
| 375 |
+
_ => None,
|
| 376 |
+
}
|
| 377 |
+
}
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
pub(crate) fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
|
| 381 |
+
where
|
| 382 |
+
F: FnOnce(T) -> U,
|
| 383 |
+
{
|
| 384 |
+
match result {
|
| 385 |
+
Ok(t) => Ok(f(t)),
|
| 386 |
+
#[cfg(panic = "unwind")]
|
| 387 |
+
Err(PoisonError { data }) => Err(PoisonError::new(f(data))),
|
| 388 |
+
}
|
| 389 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::cell::UnsafeCell;
|
| 2 |
+
use crate::fmt;
|
| 3 |
+
use crate::ops::Deref;
|
| 4 |
+
use crate::panic::{RefUnwindSafe, UnwindSafe};
|
| 5 |
+
use crate::sys::sync as sys;
|
| 6 |
+
use crate::thread::{ThreadId, current_id};
|
| 7 |
+
|
| 8 |
+
/// A re-entrant mutual exclusion lock
|
| 9 |
+
///
|
| 10 |
+
/// This lock will block *other* threads waiting for the lock to become
|
| 11 |
+
/// available. The thread which has already locked the mutex can lock it
|
| 12 |
+
/// multiple times without blocking, preventing a common source of deadlocks.
|
| 13 |
+
///
|
| 14 |
+
/// # Examples
|
| 15 |
+
///
|
| 16 |
+
/// Allow recursively calling a function needing synchronization from within
|
| 17 |
+
/// a callback (this is how [`StdoutLock`](crate::io::StdoutLock) is currently
|
| 18 |
+
/// implemented):
|
| 19 |
+
///
|
| 20 |
+
/// ```
|
| 21 |
+
/// #![feature(reentrant_lock)]
|
| 22 |
+
///
|
| 23 |
+
/// use std::cell::RefCell;
|
| 24 |
+
/// use std::sync::ReentrantLock;
|
| 25 |
+
///
|
| 26 |
+
/// pub struct Log {
|
| 27 |
+
/// data: RefCell<String>,
|
| 28 |
+
/// }
|
| 29 |
+
///
|
| 30 |
+
/// impl Log {
|
| 31 |
+
/// pub fn append(&self, msg: &str) {
|
| 32 |
+
/// self.data.borrow_mut().push_str(msg);
|
| 33 |
+
/// }
|
| 34 |
+
/// }
|
| 35 |
+
///
|
| 36 |
+
/// static LOG: ReentrantLock<Log> = ReentrantLock::new(Log { data: RefCell::new(String::new()) });
|
| 37 |
+
///
|
| 38 |
+
/// pub fn with_log<R>(f: impl FnOnce(&Log) -> R) -> R {
|
| 39 |
+
/// let log = LOG.lock();
|
| 40 |
+
/// f(&*log)
|
| 41 |
+
/// }
|
| 42 |
+
///
|
| 43 |
+
/// with_log(|log| {
|
| 44 |
+
/// log.append("Hello");
|
| 45 |
+
/// with_log(|log| log.append(" there!"));
|
| 46 |
+
/// });
|
| 47 |
+
/// ```
|
| 48 |
+
///
|
| 49 |
+
// # Implementation details
|
| 50 |
+
//
|
| 51 |
+
// The 'owner' field tracks which thread has locked the mutex.
|
| 52 |
+
//
|
| 53 |
+
// We use thread::current_id() as the thread identifier, which is just the
|
| 54 |
+
// current thread's ThreadId, so it's unique across the process lifetime.
|
| 55 |
+
//
|
| 56 |
+
// If `owner` is set to the identifier of the current thread,
|
| 57 |
+
// we assume the mutex is already locked and instead of locking it again,
|
| 58 |
+
// we increment `lock_count`.
|
| 59 |
+
//
|
| 60 |
+
// When unlocking, we decrement `lock_count`, and only unlock the mutex when
|
| 61 |
+
// it reaches zero.
|
| 62 |
+
//
|
| 63 |
+
// `lock_count` is protected by the mutex and only accessed by the thread that has
|
| 64 |
+
// locked the mutex, so needs no synchronization.
|
| 65 |
+
//
|
| 66 |
+
// `owner` can be checked by other threads that want to see if they already
|
| 67 |
+
// hold the lock, so needs to be atomic. If it compares equal, we're on the
|
| 68 |
+
// same thread that holds the mutex and memory access can use relaxed ordering
|
| 69 |
+
// since we're not dealing with multiple threads. If it's not equal,
|
| 70 |
+
// synchronization is left to the mutex, making relaxed memory ordering for
|
| 71 |
+
// the `owner` field fine in all cases.
|
| 72 |
+
//
|
| 73 |
+
// On systems without 64 bit atomics we also store the address of a TLS variable
|
| 74 |
+
// along the 64-bit TID. We then first check that address against the address
|
| 75 |
+
// of that variable on the current thread, and only if they compare equal do we
|
| 76 |
+
// compare the actual TIDs. Because we only ever read the TID on the same thread
|
| 77 |
+
// that it was written on (or a thread sharing the TLS block with that writer thread),
|
| 78 |
+
// we don't need to further synchronize the TID accesses, so they can be regular 64-bit
|
| 79 |
+
// non-atomic accesses.
|
| 80 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 81 |
+
pub struct ReentrantLock<T: ?Sized> {
|
| 82 |
+
mutex: sys::Mutex,
|
| 83 |
+
owner: Tid,
|
| 84 |
+
lock_count: UnsafeCell<u32>,
|
| 85 |
+
data: T,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
cfg_select!(
|
| 89 |
+
target_has_atomic = "64" => {
|
| 90 |
+
use crate::sync::atomic::{Atomic, AtomicU64, Ordering::Relaxed};
|
| 91 |
+
|
| 92 |
+
struct Tid(Atomic<u64>);
|
| 93 |
+
|
| 94 |
+
impl Tid {
|
| 95 |
+
const fn new() -> Self {
|
| 96 |
+
Self(AtomicU64::new(0))
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
#[inline]
|
| 100 |
+
fn contains(&self, owner: ThreadId) -> bool {
|
| 101 |
+
owner.as_u64().get() == self.0.load(Relaxed)
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
#[inline]
|
| 105 |
+
// This is just unsafe to match the API of the Tid type below.
|
| 106 |
+
unsafe fn set(&self, tid: Option<ThreadId>) {
|
| 107 |
+
let value = tid.map_or(0, |tid| tid.as_u64().get());
|
| 108 |
+
self.0.store(value, Relaxed);
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
_ => {
|
| 113 |
+
/// Returns the address of a TLS variable. This is guaranteed to
|
| 114 |
+
/// be unique across all currently alive threads.
|
| 115 |
+
fn tls_addr() -> usize {
|
| 116 |
+
thread_local! { static X: u8 = const { 0u8 } };
|
| 117 |
+
|
| 118 |
+
X.with(|p| <*const u8>::addr(p))
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
use crate::sync::atomic::{
|
| 122 |
+
Atomic,
|
| 123 |
+
AtomicUsize,
|
| 124 |
+
Ordering,
|
| 125 |
+
};
|
| 126 |
+
|
| 127 |
+
struct Tid {
|
| 128 |
+
// When a thread calls `set()`, this value gets updated to
|
| 129 |
+
// the address of a thread local on that thread. This is
|
| 130 |
+
// used as a first check in `contains()`; if the `tls_addr`
|
| 131 |
+
// doesn't match the TLS address of the current thread, then
|
| 132 |
+
// the ThreadId also can't match. Only if the TLS addresses do
|
| 133 |
+
// match do we read out the actual TID.
|
| 134 |
+
// Note also that we can use relaxed atomic operations here, because
|
| 135 |
+
// we only ever read from the tid if `tls_addr` matches the current
|
| 136 |
+
// TLS address. In that case, either the tid has been set by
|
| 137 |
+
// the current thread, or by a thread that has terminated before
|
| 138 |
+
// the current thread's `tls_addr` was allocated. In either case, no further
|
| 139 |
+
// synchronization is needed (as per <https://github.com/rust-lang/miri/issues/3450>)
|
| 140 |
+
tls_addr: Atomic<usize>,
|
| 141 |
+
tid: UnsafeCell<u64>,
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
unsafe impl Send for Tid {}
|
| 145 |
+
unsafe impl Sync for Tid {}
|
| 146 |
+
|
| 147 |
+
impl Tid {
|
| 148 |
+
const fn new() -> Self {
|
| 149 |
+
Self { tls_addr: AtomicUsize::new(0), tid: UnsafeCell::new(0) }
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
#[inline]
|
| 153 |
+
// NOTE: This assumes that `owner` is the ID of the current
|
| 154 |
+
// thread, and may spuriously return `false` if that's not the case.
|
| 155 |
+
fn contains(&self, owner: ThreadId) -> bool {
|
| 156 |
+
// We must call `tls_addr()` *before* doing the load to ensure that if we reuse an
|
| 157 |
+
// earlier thread's address, the `tls_addr.load()` below happens-after everything
|
| 158 |
+
// that thread did.
|
| 159 |
+
let tls_addr = tls_addr();
|
| 160 |
+
// SAFETY: See the comments in the struct definition.
|
| 161 |
+
self.tls_addr.load(Ordering::Relaxed) == tls_addr
|
| 162 |
+
&& unsafe { *self.tid.get() } == owner.as_u64().get()
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
#[inline]
|
| 166 |
+
// This may only be called by one thread at a time, and can lead to
|
| 167 |
+
// race conditions otherwise.
|
| 168 |
+
unsafe fn set(&self, tid: Option<ThreadId>) {
|
| 169 |
+
// It's important that we set `self.tls_addr` to 0 if the tid is
|
| 170 |
+
// cleared. Otherwise, there might be race conditions between
|
| 171 |
+
// `set()` and `get()`.
|
| 172 |
+
let tls_addr = if tid.is_some() { tls_addr() } else { 0 };
|
| 173 |
+
let value = tid.map_or(0, |tid| tid.as_u64().get());
|
| 174 |
+
self.tls_addr.store(tls_addr, Ordering::Relaxed);
|
| 175 |
+
unsafe { *self.tid.get() = value };
|
| 176 |
+
}
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
);
|
| 180 |
+
|
| 181 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 182 |
+
unsafe impl<T: Send + ?Sized> Send for ReentrantLock<T> {}
|
| 183 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 184 |
+
unsafe impl<T: Send + ?Sized> Sync for ReentrantLock<T> {}
|
| 185 |
+
|
| 186 |
+
// Because of the `UnsafeCell`, these traits are not implemented automatically
|
| 187 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 188 |
+
impl<T: UnwindSafe + ?Sized> UnwindSafe for ReentrantLock<T> {}
|
| 189 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 190 |
+
impl<T: RefUnwindSafe + ?Sized> RefUnwindSafe for ReentrantLock<T> {}
|
| 191 |
+
|
| 192 |
+
/// An RAII implementation of a "scoped lock" of a re-entrant lock. When this
|
| 193 |
+
/// structure is dropped (falls out of scope), the lock will be unlocked.
|
| 194 |
+
///
|
| 195 |
+
/// The data protected by the mutex can be accessed through this guard via its
|
| 196 |
+
/// [`Deref`] implementation.
|
| 197 |
+
///
|
| 198 |
+
/// This structure is created by the [`lock`](ReentrantLock::lock) method on
|
| 199 |
+
/// [`ReentrantLock`].
|
| 200 |
+
///
|
| 201 |
+
/// # Mutability
|
| 202 |
+
///
|
| 203 |
+
/// Unlike [`MutexGuard`](super::MutexGuard), `ReentrantLockGuard` does not
|
| 204 |
+
/// implement [`DerefMut`](crate::ops::DerefMut), because implementation of
|
| 205 |
+
/// the trait would violate Rust’s reference aliasing rules. Use interior
|
| 206 |
+
/// mutability (usually [`RefCell`](crate::cell::RefCell)) in order to mutate
|
| 207 |
+
/// the guarded data.
|
| 208 |
+
#[must_use = "if unused the ReentrantLock will immediately unlock"]
|
| 209 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 210 |
+
pub struct ReentrantLockGuard<'a, T: ?Sized + 'a> {
|
| 211 |
+
lock: &'a ReentrantLock<T>,
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 215 |
+
impl<T: ?Sized> !Send for ReentrantLockGuard<'_, T> {}
|
| 216 |
+
|
| 217 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 218 |
+
unsafe impl<T: ?Sized + Sync> Sync for ReentrantLockGuard<'_, T> {}
|
| 219 |
+
|
| 220 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 221 |
+
impl<T> ReentrantLock<T> {
|
| 222 |
+
/// Creates a new re-entrant lock in an unlocked state ready for use.
|
| 223 |
+
///
|
| 224 |
+
/// # Examples
|
| 225 |
+
///
|
| 226 |
+
/// ```
|
| 227 |
+
/// #![feature(reentrant_lock)]
|
| 228 |
+
/// use std::sync::ReentrantLock;
|
| 229 |
+
///
|
| 230 |
+
/// let lock = ReentrantLock::new(0);
|
| 231 |
+
/// ```
|
| 232 |
+
pub const fn new(t: T) -> ReentrantLock<T> {
|
| 233 |
+
ReentrantLock {
|
| 234 |
+
mutex: sys::Mutex::new(),
|
| 235 |
+
owner: Tid::new(),
|
| 236 |
+
lock_count: UnsafeCell::new(0),
|
| 237 |
+
data: t,
|
| 238 |
+
}
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
/// Consumes this lock, returning the underlying data.
|
| 242 |
+
///
|
| 243 |
+
/// # Examples
|
| 244 |
+
///
|
| 245 |
+
/// ```
|
| 246 |
+
/// #![feature(reentrant_lock)]
|
| 247 |
+
///
|
| 248 |
+
/// use std::sync::ReentrantLock;
|
| 249 |
+
///
|
| 250 |
+
/// let lock = ReentrantLock::new(0);
|
| 251 |
+
/// assert_eq!(lock.into_inner(), 0);
|
| 252 |
+
/// ```
|
| 253 |
+
pub fn into_inner(self) -> T {
|
| 254 |
+
self.data
|
| 255 |
+
}
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 259 |
+
impl<T: ?Sized> ReentrantLock<T> {
|
| 260 |
+
/// Acquires the lock, blocking the current thread until it is able to do
|
| 261 |
+
/// so.
|
| 262 |
+
///
|
| 263 |
+
/// This function will block the caller until it is available to acquire
|
| 264 |
+
/// the lock. Upon returning, the thread is the only thread with the lock
|
| 265 |
+
/// held. When the thread calling this method already holds the lock, the
|
| 266 |
+
/// call succeeds without blocking.
|
| 267 |
+
///
|
| 268 |
+
/// # Examples
|
| 269 |
+
///
|
| 270 |
+
/// ```
|
| 271 |
+
/// #![feature(reentrant_lock)]
|
| 272 |
+
/// use std::cell::Cell;
|
| 273 |
+
/// use std::sync::{Arc, ReentrantLock};
|
| 274 |
+
/// use std::thread;
|
| 275 |
+
///
|
| 276 |
+
/// let lock = Arc::new(ReentrantLock::new(Cell::new(0)));
|
| 277 |
+
/// let c_lock = Arc::clone(&lock);
|
| 278 |
+
///
|
| 279 |
+
/// thread::spawn(move || {
|
| 280 |
+
/// c_lock.lock().set(10);
|
| 281 |
+
/// }).join().expect("thread::spawn failed");
|
| 282 |
+
/// assert_eq!(lock.lock().get(), 10);
|
| 283 |
+
/// ```
|
| 284 |
+
pub fn lock(&self) -> ReentrantLockGuard<'_, T> {
|
| 285 |
+
let this_thread = current_id();
|
| 286 |
+
// Safety: We only touch lock_count when we own the inner mutex.
|
| 287 |
+
// Additionally, we only call `self.owner.set()` while holding
|
| 288 |
+
// the inner mutex, so no two threads can call it concurrently.
|
| 289 |
+
unsafe {
|
| 290 |
+
if self.owner.contains(this_thread) {
|
| 291 |
+
self.increment_lock_count().expect("lock count overflow in reentrant mutex");
|
| 292 |
+
} else {
|
| 293 |
+
self.mutex.lock();
|
| 294 |
+
self.owner.set(Some(this_thread));
|
| 295 |
+
debug_assert_eq!(*self.lock_count.get(), 0);
|
| 296 |
+
*self.lock_count.get() = 1;
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
ReentrantLockGuard { lock: self }
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
/// Returns a mutable reference to the underlying data.
|
| 303 |
+
///
|
| 304 |
+
/// Since this call borrows the `ReentrantLock` mutably, no actual locking
|
| 305 |
+
/// needs to take place -- the mutable borrow statically guarantees no locks
|
| 306 |
+
/// exist.
|
| 307 |
+
///
|
| 308 |
+
/// # Examples
|
| 309 |
+
///
|
| 310 |
+
/// ```
|
| 311 |
+
/// #![feature(reentrant_lock)]
|
| 312 |
+
/// use std::sync::ReentrantLock;
|
| 313 |
+
///
|
| 314 |
+
/// let mut lock = ReentrantLock::new(0);
|
| 315 |
+
/// *lock.get_mut() = 10;
|
| 316 |
+
/// assert_eq!(*lock.lock(), 10);
|
| 317 |
+
/// ```
|
| 318 |
+
pub fn get_mut(&mut self) -> &mut T {
|
| 319 |
+
&mut self.data
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
/// Attempts to acquire this lock.
|
| 323 |
+
///
|
| 324 |
+
/// If the lock could not be acquired at this time, then `None` is returned.
|
| 325 |
+
/// Otherwise, an RAII guard is returned.
|
| 326 |
+
///
|
| 327 |
+
/// This function does not block.
|
| 328 |
+
// FIXME maybe make it a public part of the API?
|
| 329 |
+
#[unstable(issue = "none", feature = "std_internals")]
|
| 330 |
+
#[doc(hidden)]
|
| 331 |
+
pub fn try_lock(&self) -> Option<ReentrantLockGuard<'_, T>> {
|
| 332 |
+
let this_thread = current_id();
|
| 333 |
+
// Safety: We only touch lock_count when we own the inner mutex.
|
| 334 |
+
// Additionally, we only call `self.owner.set()` while holding
|
| 335 |
+
// the inner mutex, so no two threads can call it concurrently.
|
| 336 |
+
unsafe {
|
| 337 |
+
if self.owner.contains(this_thread) {
|
| 338 |
+
self.increment_lock_count()?;
|
| 339 |
+
Some(ReentrantLockGuard { lock: self })
|
| 340 |
+
} else if self.mutex.try_lock() {
|
| 341 |
+
self.owner.set(Some(this_thread));
|
| 342 |
+
debug_assert_eq!(*self.lock_count.get(), 0);
|
| 343 |
+
*self.lock_count.get() = 1;
|
| 344 |
+
Some(ReentrantLockGuard { lock: self })
|
| 345 |
+
} else {
|
| 346 |
+
None
|
| 347 |
+
}
|
| 348 |
+
}
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
/// Returns a raw pointer to the underlying data.
|
| 352 |
+
///
|
| 353 |
+
/// The returned pointer is always non-null and properly aligned, but it is
|
| 354 |
+
/// the user's responsibility to ensure that any reads through it are
|
| 355 |
+
/// properly synchronized to avoid data races, and that it is not read
|
| 356 |
+
/// through after the lock is dropped.
|
| 357 |
+
#[unstable(feature = "reentrant_lock_data_ptr", issue = "140368")]
|
| 358 |
+
pub const fn data_ptr(&self) -> *const T {
|
| 359 |
+
&raw const self.data
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
unsafe fn increment_lock_count(&self) -> Option<()> {
|
| 363 |
+
unsafe {
|
| 364 |
+
*self.lock_count.get() = (*self.lock_count.get()).checked_add(1)?;
|
| 365 |
+
}
|
| 366 |
+
Some(())
|
| 367 |
+
}
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 371 |
+
impl<T: fmt::Debug + ?Sized> fmt::Debug for ReentrantLock<T> {
|
| 372 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 373 |
+
let mut d = f.debug_struct("ReentrantLock");
|
| 374 |
+
match self.try_lock() {
|
| 375 |
+
Some(v) => d.field("data", &&*v),
|
| 376 |
+
None => d.field("data", &format_args!("<locked>")),
|
| 377 |
+
};
|
| 378 |
+
d.finish_non_exhaustive()
|
| 379 |
+
}
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 383 |
+
impl<T: Default> Default for ReentrantLock<T> {
|
| 384 |
+
fn default() -> Self {
|
| 385 |
+
Self::new(T::default())
|
| 386 |
+
}
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 390 |
+
impl<T> From<T> for ReentrantLock<T> {
|
| 391 |
+
fn from(t: T) -> Self {
|
| 392 |
+
Self::new(t)
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 397 |
+
impl<T: ?Sized> Deref for ReentrantLockGuard<'_, T> {
|
| 398 |
+
type Target = T;
|
| 399 |
+
|
| 400 |
+
fn deref(&self) -> &T {
|
| 401 |
+
&self.lock.data
|
| 402 |
+
}
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 406 |
+
impl<T: fmt::Debug + ?Sized> fmt::Debug for ReentrantLockGuard<'_, T> {
|
| 407 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 408 |
+
(**self).fmt(f)
|
| 409 |
+
}
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 413 |
+
impl<T: fmt::Display + ?Sized> fmt::Display for ReentrantLockGuard<'_, T> {
|
| 414 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 415 |
+
(**self).fmt(f)
|
| 416 |
+
}
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
#[unstable(feature = "reentrant_lock", issue = "121440")]
|
| 420 |
+
impl<T: ?Sized> Drop for ReentrantLockGuard<'_, T> {
|
| 421 |
+
#[inline]
|
| 422 |
+
fn drop(&mut self) {
|
| 423 |
+
// Safety: We own the lock.
|
| 424 |
+
unsafe {
|
| 425 |
+
*self.lock.lock_count.get() -= 1;
|
| 426 |
+
if *self.lock.lock_count.get() == 0 {
|
| 427 |
+
self.lock.owner.set(None);
|
| 428 |
+
self.lock.mutex.unlock();
|
| 429 |
+
}
|
| 430 |
+
}
|
| 431 |
+
}
|
| 432 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/hermit.rs
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 2 |
+
|
| 3 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 4 |
+
unsafe impl GlobalAlloc for System {
|
| 5 |
+
#[inline]
|
| 6 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 7 |
+
let size = layout.size();
|
| 8 |
+
let align = layout.align();
|
| 9 |
+
unsafe { hermit_abi::malloc(size, align) }
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
#[inline]
|
| 13 |
+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
| 14 |
+
let size = layout.size();
|
| 15 |
+
let align = layout.align();
|
| 16 |
+
unsafe {
|
| 17 |
+
hermit_abi::free(ptr, size, align);
|
| 18 |
+
}
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
#[inline]
|
| 22 |
+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
| 23 |
+
let size = layout.size();
|
| 24 |
+
let align = layout.align();
|
| 25 |
+
unsafe { hermit_abi::realloc(ptr, size, align, new_size) }
|
| 26 |
+
}
|
| 27 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/mod.rs
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#![forbid(unsafe_op_in_unsafe_fn)]
|
| 2 |
+
|
| 3 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 4 |
+
use crate::ptr;
|
| 5 |
+
|
| 6 |
+
// The minimum alignment guaranteed by the architecture. This value is used to
|
| 7 |
+
// add fast paths for low alignment values.
|
| 8 |
+
#[allow(dead_code)]
|
| 9 |
+
const MIN_ALIGN: usize = if cfg!(any(
|
| 10 |
+
all(target_arch = "riscv32", any(target_os = "espidf", target_os = "zkvm")),
|
| 11 |
+
all(target_arch = "xtensa", target_os = "espidf"),
|
| 12 |
+
)) {
|
| 13 |
+
// The allocator on the esp-idf and zkvm platforms guarantees 4 byte alignment.
|
| 14 |
+
4
|
| 15 |
+
} else if cfg!(any(
|
| 16 |
+
target_arch = "x86",
|
| 17 |
+
target_arch = "arm",
|
| 18 |
+
target_arch = "m68k",
|
| 19 |
+
target_arch = "csky",
|
| 20 |
+
target_arch = "loongarch32",
|
| 21 |
+
target_arch = "mips",
|
| 22 |
+
target_arch = "mips32r6",
|
| 23 |
+
target_arch = "powerpc",
|
| 24 |
+
target_arch = "powerpc64",
|
| 25 |
+
target_arch = "sparc",
|
| 26 |
+
target_arch = "wasm32",
|
| 27 |
+
target_arch = "hexagon",
|
| 28 |
+
target_arch = "riscv32",
|
| 29 |
+
target_arch = "xtensa",
|
| 30 |
+
)) {
|
| 31 |
+
8
|
| 32 |
+
} else if cfg!(any(
|
| 33 |
+
target_arch = "x86_64",
|
| 34 |
+
target_arch = "aarch64",
|
| 35 |
+
target_arch = "arm64ec",
|
| 36 |
+
target_arch = "loongarch64",
|
| 37 |
+
target_arch = "mips64",
|
| 38 |
+
target_arch = "mips64r6",
|
| 39 |
+
target_arch = "s390x",
|
| 40 |
+
target_arch = "sparc64",
|
| 41 |
+
target_arch = "riscv64",
|
| 42 |
+
target_arch = "wasm64",
|
| 43 |
+
)) {
|
| 44 |
+
16
|
| 45 |
+
} else {
|
| 46 |
+
panic!("add a value for MIN_ALIGN")
|
| 47 |
+
};
|
| 48 |
+
|
| 49 |
+
#[allow(dead_code)]
|
| 50 |
+
unsafe fn realloc_fallback(
|
| 51 |
+
alloc: &System,
|
| 52 |
+
ptr: *mut u8,
|
| 53 |
+
old_layout: Layout,
|
| 54 |
+
new_size: usize,
|
| 55 |
+
) -> *mut u8 {
|
| 56 |
+
// SAFETY: Docs for GlobalAlloc::realloc require this to be valid
|
| 57 |
+
unsafe {
|
| 58 |
+
let new_layout = Layout::from_size_align_unchecked(new_size, old_layout.align());
|
| 59 |
+
|
| 60 |
+
let new_ptr = GlobalAlloc::alloc(alloc, new_layout);
|
| 61 |
+
if !new_ptr.is_null() {
|
| 62 |
+
let size = usize::min(old_layout.size(), new_size);
|
| 63 |
+
ptr::copy_nonoverlapping(ptr, new_ptr, size);
|
| 64 |
+
GlobalAlloc::dealloc(alloc, ptr, old_layout);
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
new_ptr
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
cfg_select! {
|
| 72 |
+
any(
|
| 73 |
+
target_family = "unix",
|
| 74 |
+
target_os = "wasi",
|
| 75 |
+
target_os = "teeos",
|
| 76 |
+
target_os = "trusty",
|
| 77 |
+
) => {
|
| 78 |
+
mod unix;
|
| 79 |
+
}
|
| 80 |
+
target_os = "windows" => {
|
| 81 |
+
mod windows;
|
| 82 |
+
}
|
| 83 |
+
target_os = "hermit" => {
|
| 84 |
+
mod hermit;
|
| 85 |
+
}
|
| 86 |
+
target_os = "motor" => {
|
| 87 |
+
mod motor;
|
| 88 |
+
}
|
| 89 |
+
all(target_vendor = "fortanix", target_env = "sgx") => {
|
| 90 |
+
mod sgx;
|
| 91 |
+
}
|
| 92 |
+
target_os = "solid_asp3" => {
|
| 93 |
+
mod solid;
|
| 94 |
+
}
|
| 95 |
+
target_os = "uefi" => {
|
| 96 |
+
mod uefi;
|
| 97 |
+
}
|
| 98 |
+
target_os = "vexos" => {
|
| 99 |
+
mod vexos;
|
| 100 |
+
}
|
| 101 |
+
target_family = "wasm" => {
|
| 102 |
+
mod wasm;
|
| 103 |
+
}
|
| 104 |
+
target_os = "xous" => {
|
| 105 |
+
mod xous;
|
| 106 |
+
}
|
| 107 |
+
target_os = "zkvm" => {
|
| 108 |
+
mod zkvm;
|
| 109 |
+
}
|
| 110 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/motor.rs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 2 |
+
|
| 3 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 4 |
+
unsafe impl GlobalAlloc for System {
|
| 5 |
+
#[inline]
|
| 6 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 7 |
+
// SAFETY: same requirements as in GlobalAlloc::alloc.
|
| 8 |
+
moto_rt::alloc::alloc(layout)
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
#[inline]
|
| 12 |
+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
| 13 |
+
// SAFETY: same requirements as in GlobalAlloc::alloc_zeroed.
|
| 14 |
+
moto_rt::alloc::alloc_zeroed(layout)
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
#[inline]
|
| 18 |
+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
| 19 |
+
// SAFETY: same requirements as in GlobalAlloc::dealloc.
|
| 20 |
+
unsafe { moto_rt::alloc::dealloc(ptr, layout) }
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
#[inline]
|
| 24 |
+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
| 25 |
+
// SAFETY: same requirements as in GlobalAlloc::realloc.
|
| 26 |
+
unsafe { moto_rt::alloc::realloc(ptr, layout, new_size) }
|
| 27 |
+
}
|
| 28 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/sgx.rs
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 2 |
+
use crate::ptr;
|
| 3 |
+
use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
|
| 4 |
+
use crate::sys::pal::abi::mem as sgx_mem;
|
| 5 |
+
use crate::sys::pal::waitqueue::SpinMutex;
|
| 6 |
+
|
| 7 |
+
// Using a SpinMutex because we never want to exit the enclave waiting for the
|
| 8 |
+
// allocator.
|
| 9 |
+
//
|
| 10 |
+
// The current allocator here is the `dlmalloc` crate which we've got included
|
| 11 |
+
// in the rust-lang/rust repository as a submodule. The crate is a port of
|
| 12 |
+
// dlmalloc.c from C to Rust.
|
| 13 |
+
//
|
| 14 |
+
// Specifying linkage/symbol name is solely to ensure a single instance between this crate and its unit tests
|
| 15 |
+
#[cfg_attr(test, linkage = "available_externally")]
|
| 16 |
+
#[unsafe(export_name = "_ZN16__rust_internals3std3sys5alloc3sgx8DLMALLOCE")]
|
| 17 |
+
static DLMALLOC: SpinMutex<dlmalloc::Dlmalloc<Sgx>> =
|
| 18 |
+
SpinMutex::new(dlmalloc::Dlmalloc::new_with_allocator(Sgx {}));
|
| 19 |
+
|
| 20 |
+
struct Sgx;
|
| 21 |
+
|
| 22 |
+
unsafe impl dlmalloc::Allocator for Sgx {
|
| 23 |
+
/// Allocs system resources
|
| 24 |
+
fn alloc(&self, _size: usize) -> (*mut u8, usize, u32) {
|
| 25 |
+
static INIT: Atomic<bool> = AtomicBool::new(false);
|
| 26 |
+
|
| 27 |
+
// No ordering requirement since this function is protected by the global lock.
|
| 28 |
+
if !INIT.swap(true, Ordering::Relaxed) {
|
| 29 |
+
(sgx_mem::heap_base() as _, sgx_mem::heap_size(), 0)
|
| 30 |
+
} else {
|
| 31 |
+
(ptr::null_mut(), 0, 0)
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
fn remap(&self, _ptr: *mut u8, _oldsize: usize, _newsize: usize, _can_move: bool) -> *mut u8 {
|
| 36 |
+
ptr::null_mut()
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
fn free_part(&self, _ptr: *mut u8, _oldsize: usize, _newsize: usize) -> bool {
|
| 40 |
+
false
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
fn free(&self, _ptr: *mut u8, _size: usize) -> bool {
|
| 44 |
+
return false;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
fn can_release_part(&self, _flags: u32) -> bool {
|
| 48 |
+
false
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
fn allocates_zeros(&self) -> bool {
|
| 52 |
+
false
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
fn page_size(&self) -> usize {
|
| 56 |
+
0x1000
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 61 |
+
unsafe impl GlobalAlloc for System {
|
| 62 |
+
#[inline]
|
| 63 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 64 |
+
// SAFETY: the caller must uphold the safety contract for `malloc`
|
| 65 |
+
unsafe { DLMALLOC.lock().malloc(layout.size(), layout.align()) }
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
#[inline]
|
| 69 |
+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
| 70 |
+
// SAFETY: the caller must uphold the safety contract for `malloc`
|
| 71 |
+
unsafe { DLMALLOC.lock().calloc(layout.size(), layout.align()) }
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
#[inline]
|
| 75 |
+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
| 76 |
+
// SAFETY: the caller must uphold the safety contract for `malloc`
|
| 77 |
+
unsafe { DLMALLOC.lock().free(ptr, layout.size(), layout.align()) }
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
#[inline]
|
| 81 |
+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
| 82 |
+
// SAFETY: the caller must uphold the safety contract for `malloc`
|
| 83 |
+
unsafe { DLMALLOC.lock().realloc(ptr, layout.size(), layout.align(), new_size) }
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
// The following functions are needed by libunwind. These symbols are named
|
| 88 |
+
// in pre-link args for the target specification, so keep that in sync.
|
| 89 |
+
#[cfg(not(test))]
|
| 90 |
+
#[unsafe(no_mangle)]
|
| 91 |
+
pub unsafe extern "C" fn __rust_c_alloc(size: usize, align: usize) -> *mut u8 {
|
| 92 |
+
unsafe { crate::alloc::alloc(Layout::from_size_align_unchecked(size, align)) }
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
#[cfg(not(test))]
|
| 96 |
+
#[unsafe(no_mangle)]
|
| 97 |
+
pub unsafe extern "C" fn __rust_c_dealloc(ptr: *mut u8, size: usize, align: usize) {
|
| 98 |
+
unsafe { crate::alloc::dealloc(ptr, Layout::from_size_align_unchecked(size, align)) }
|
| 99 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/solid.rs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use super::{MIN_ALIGN, realloc_fallback};
|
| 2 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 3 |
+
|
| 4 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 5 |
+
unsafe impl GlobalAlloc for System {
|
| 6 |
+
#[inline]
|
| 7 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 8 |
+
if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
|
| 9 |
+
unsafe { libc::malloc(layout.size()) as *mut u8 }
|
| 10 |
+
} else {
|
| 11 |
+
unsafe { libc::memalign(layout.align(), layout.size()) as *mut u8 }
|
| 12 |
+
}
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
#[inline]
|
| 16 |
+
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
|
| 17 |
+
unsafe { libc::free(ptr as *mut libc::c_void) }
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
#[inline]
|
| 21 |
+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
| 22 |
+
unsafe {
|
| 23 |
+
if layout.align() <= MIN_ALIGN && layout.align() <= new_size {
|
| 24 |
+
libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8
|
| 25 |
+
} else {
|
| 26 |
+
realloc_fallback(self, ptr, layout, new_size)
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/uefi.rs
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Global Allocator for UEFI.
|
| 2 |
+
//! Uses [r-efi-alloc](https://crates.io/crates/r-efi-alloc)
|
| 3 |
+
|
| 4 |
+
use r_efi::protocols::loaded_image;
|
| 5 |
+
|
| 6 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 7 |
+
use crate::sync::OnceLock;
|
| 8 |
+
use crate::sys::pal::helpers;
|
| 9 |
+
|
| 10 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 11 |
+
unsafe impl GlobalAlloc for System {
|
| 12 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 13 |
+
static EFI_MEMORY_TYPE: OnceLock<u32> = OnceLock::new();
|
| 14 |
+
|
| 15 |
+
// Return null pointer if boot services are not available
|
| 16 |
+
if crate::os::uefi::env::boot_services().is_none() {
|
| 17 |
+
return crate::ptr::null_mut();
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
// If boot services is valid then SystemTable is not null.
|
| 21 |
+
let system_table = crate::os::uefi::env::system_table().as_ptr().cast();
|
| 22 |
+
|
| 23 |
+
// Each loaded image has an image handle that supports `EFI_LOADED_IMAGE_PROTOCOL`. Thus, this
|
| 24 |
+
// will never fail.
|
| 25 |
+
let mem_type = EFI_MEMORY_TYPE.get_or_init(|| {
|
| 26 |
+
let protocol = helpers::image_handle_protocol::<loaded_image::Protocol>(
|
| 27 |
+
loaded_image::PROTOCOL_GUID,
|
| 28 |
+
)
|
| 29 |
+
.unwrap();
|
| 30 |
+
// Gives allocations the memory type that the data sections were loaded as.
|
| 31 |
+
unsafe { (*protocol.as_ptr()).image_data_type }
|
| 32 |
+
});
|
| 33 |
+
|
| 34 |
+
// The caller must ensure non-0 layout
|
| 35 |
+
unsafe { r_efi_alloc::raw::alloc(system_table, layout, *mem_type) }
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
| 39 |
+
// Do nothing if boot services are not available
|
| 40 |
+
if crate::os::uefi::env::boot_services().is_none() {
|
| 41 |
+
return;
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
// If boot services is valid then SystemTable is not null.
|
| 45 |
+
let system_table = crate::os::uefi::env::system_table().as_ptr().cast();
|
| 46 |
+
// The caller must ensure non-0 layout
|
| 47 |
+
unsafe { r_efi_alloc::raw::dealloc(system_table, ptr, layout) }
|
| 48 |
+
}
|
| 49 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/unix.rs
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use super::{MIN_ALIGN, realloc_fallback};
|
| 2 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 3 |
+
use crate::ptr;
|
| 4 |
+
|
| 5 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 6 |
+
unsafe impl GlobalAlloc for System {
|
| 7 |
+
#[inline]
|
| 8 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 9 |
+
// jemalloc provides alignment less than MIN_ALIGN for small allocations.
|
| 10 |
+
// So only rely on MIN_ALIGN if size >= align.
|
| 11 |
+
// Also see <https://github.com/rust-lang/rust/issues/45955> and
|
| 12 |
+
// <https://github.com/rust-lang/rust/issues/62251#issuecomment-507580914>.
|
| 13 |
+
if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
|
| 14 |
+
unsafe { libc::malloc(layout.size()) as *mut u8 }
|
| 15 |
+
} else {
|
| 16 |
+
// `posix_memalign` returns a non-aligned value if supplied a very
|
| 17 |
+
// large alignment on older versions of Apple's platforms (unknown
|
| 18 |
+
// exactly which version range, but the issue is definitely
|
| 19 |
+
// present in macOS 10.14 and iOS 13.3).
|
| 20 |
+
//
|
| 21 |
+
// <https://github.com/rust-lang/rust/issues/30170>
|
| 22 |
+
#[cfg(target_vendor = "apple")]
|
| 23 |
+
{
|
| 24 |
+
if layout.align() > (1 << 31) {
|
| 25 |
+
return ptr::null_mut();
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
unsafe { aligned_malloc(&layout) }
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
#[inline]
|
| 33 |
+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
| 34 |
+
// See the comment above in `alloc` for why this check looks the way it does.
|
| 35 |
+
if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
|
| 36 |
+
unsafe { libc::calloc(layout.size(), 1) as *mut u8 }
|
| 37 |
+
} else {
|
| 38 |
+
let ptr = unsafe { self.alloc(layout) };
|
| 39 |
+
if !ptr.is_null() {
|
| 40 |
+
unsafe { ptr::write_bytes(ptr, 0, layout.size()) };
|
| 41 |
+
}
|
| 42 |
+
ptr
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
#[inline]
|
| 47 |
+
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
|
| 48 |
+
unsafe { libc::free(ptr as *mut libc::c_void) }
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
#[inline]
|
| 52 |
+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
| 53 |
+
if layout.align() <= MIN_ALIGN && layout.align() <= new_size {
|
| 54 |
+
unsafe { libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 }
|
| 55 |
+
} else {
|
| 56 |
+
unsafe { realloc_fallback(self, ptr, layout, new_size) }
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
cfg_select! {
|
| 62 |
+
// We use posix_memalign wherever possible, but some targets have very incomplete POSIX coverage
|
| 63 |
+
// so we need a fallback for those.
|
| 64 |
+
any(target_os = "horizon", target_os = "vita") => {
|
| 65 |
+
#[inline]
|
| 66 |
+
unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
|
| 67 |
+
unsafe { libc::memalign(layout.align(), layout.size()) as *mut u8 }
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
_ => {
|
| 71 |
+
#[inline]
|
| 72 |
+
#[cfg_attr(target_os = "vxworks", allow(unused_unsafe))]
|
| 73 |
+
unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
|
| 74 |
+
let mut out = ptr::null_mut();
|
| 75 |
+
// We prefer posix_memalign over aligned_alloc since it is more widely available, and
|
| 76 |
+
// since with aligned_alloc, implementations are making almost arbitrary choices for
|
| 77 |
+
// which alignments are "supported", making it hard to use. For instance, some
|
| 78 |
+
// implementations require the size to be a multiple of the alignment (wasi emmalloc),
|
| 79 |
+
// while others require the alignment to be at least the pointer size (Illumos, macOS).
|
| 80 |
+
// posix_memalign only has one, clear requirement: that the alignment be a multiple of
|
| 81 |
+
// `sizeof(void*)`. Since these are all powers of 2, we can just use max.
|
| 82 |
+
let align = layout.align().max(size_of::<usize>());
|
| 83 |
+
let ret = unsafe { libc::posix_memalign(&mut out, align, layout.size()) };
|
| 84 |
+
if ret != 0 { ptr::null_mut() } else { out as *mut u8 }
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/vexos.rs
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// FIXME(static_mut_refs): Do not allow `static_mut_refs` lint
|
| 2 |
+
#![allow(static_mut_refs)]
|
| 3 |
+
|
| 4 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 5 |
+
use crate::ptr;
|
| 6 |
+
use crate::sync::atomic::{AtomicBool, Ordering};
|
| 7 |
+
|
| 8 |
+
// Symbols for heap section boundaries defined in the target's linkerscript
|
| 9 |
+
unsafe extern "C" {
|
| 10 |
+
static mut __heap_start: u8;
|
| 11 |
+
static mut __heap_end: u8;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
static mut DLMALLOC: dlmalloc::Dlmalloc<Vexos> = dlmalloc::Dlmalloc::new_with_allocator(Vexos);
|
| 15 |
+
|
| 16 |
+
struct Vexos;
|
| 17 |
+
|
| 18 |
+
unsafe impl dlmalloc::Allocator for Vexos {
|
| 19 |
+
/// Allocs system resources
|
| 20 |
+
fn alloc(&self, _size: usize) -> (*mut u8, usize, u32) {
|
| 21 |
+
static INIT: AtomicBool = AtomicBool::new(false);
|
| 22 |
+
|
| 23 |
+
if !INIT.swap(true, Ordering::Relaxed) {
|
| 24 |
+
// This target has no growable heap, as user memory has a fixed
|
| 25 |
+
// size/location and VEXos does not manage allocation for us.
|
| 26 |
+
unsafe {
|
| 27 |
+
(
|
| 28 |
+
(&raw mut __heap_start).cast::<u8>(),
|
| 29 |
+
(&raw const __heap_end).offset_from_unsigned(&raw const __heap_start),
|
| 30 |
+
0,
|
| 31 |
+
)
|
| 32 |
+
}
|
| 33 |
+
} else {
|
| 34 |
+
(ptr::null_mut(), 0, 0)
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
fn remap(&self, _ptr: *mut u8, _oldsize: usize, _newsize: usize, _can_move: bool) -> *mut u8 {
|
| 39 |
+
ptr::null_mut()
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
fn free_part(&self, _ptr: *mut u8, _oldsize: usize, _newsize: usize) -> bool {
|
| 43 |
+
false
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
fn free(&self, _ptr: *mut u8, _size: usize) -> bool {
|
| 47 |
+
return false;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
fn can_release_part(&self, _flags: u32) -> bool {
|
| 51 |
+
false
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
fn allocates_zeros(&self) -> bool {
|
| 55 |
+
false
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
fn page_size(&self) -> usize {
|
| 59 |
+
0x1000
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 64 |
+
unsafe impl GlobalAlloc for System {
|
| 65 |
+
#[inline]
|
| 66 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 67 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because we are a single-threaded target, which
|
| 68 |
+
// guarantees unique and non-reentrant access to the allocator. As such, no allocator lock is used.
|
| 69 |
+
// Calling malloc() is safe because preconditions on this function match the trait method preconditions.
|
| 70 |
+
unsafe { DLMALLOC.malloc(layout.size(), layout.align()) }
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
#[inline]
|
| 74 |
+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
| 75 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because we are a single-threaded target, which
|
| 76 |
+
// guarantees unique and non-reentrant access to the allocator. As such, no allocator lock is used.
|
| 77 |
+
// Calling calloc() is safe because preconditions on this function match the trait method preconditions.
|
| 78 |
+
unsafe { DLMALLOC.calloc(layout.size(), layout.align()) }
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
#[inline]
|
| 82 |
+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
| 83 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because we are a single-threaded target, which
|
| 84 |
+
// guarantees unique and non-reentrant access to the allocator. As such, no allocator lock is used.
|
| 85 |
+
// Calling free() is safe because preconditions on this function match the trait method preconditions.
|
| 86 |
+
unsafe { DLMALLOC.free(ptr, layout.size(), layout.align()) }
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
#[inline]
|
| 90 |
+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
| 91 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because we are a single-threaded target, which
|
| 92 |
+
// guarantees unique and non-reentrant access to the allocator. As such, no allocator lock is used.
|
| 93 |
+
// Calling realloc() is safe because preconditions on this function match the trait method preconditions.
|
| 94 |
+
unsafe { DLMALLOC.realloc(ptr, layout.size(), layout.align(), new_size) }
|
| 95 |
+
}
|
| 96 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/wasm.rs
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! This is an implementation of a global allocator on wasm targets when
|
| 2 |
+
//! emscripten or wasi is not in use. In that situation there's no actual runtime
|
| 3 |
+
//! for us to lean on for allocation, so instead we provide our own!
|
| 4 |
+
//!
|
| 5 |
+
//! The wasm instruction set has two instructions for getting the current
|
| 6 |
+
//! amount of memory and growing the amount of memory. These instructions are the
|
| 7 |
+
//! foundation on which we're able to build an allocator, so we do so! Note that
|
| 8 |
+
//! the instructions are also pretty "global" and this is the "global" allocator
|
| 9 |
+
//! after all!
|
| 10 |
+
//!
|
| 11 |
+
//! The current allocator here is the `dlmalloc` crate which we've got included
|
| 12 |
+
//! in the rust-lang/rust repository as a submodule. The crate is a port of
|
| 13 |
+
//! dlmalloc.c from C to Rust and is basically just so we can have "pure Rust"
|
| 14 |
+
//! for now which is currently technically required (can't link with C yet).
|
| 15 |
+
//!
|
| 16 |
+
//! The crate itself provides a global allocator which on wasm has no
|
| 17 |
+
//! synchronization as there are no threads!
|
| 18 |
+
|
| 19 |
+
use core::cell::SyncUnsafeCell;
|
| 20 |
+
|
| 21 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 22 |
+
|
| 23 |
+
struct SyncDlmalloc(dlmalloc::Dlmalloc);
|
| 24 |
+
unsafe impl Sync for SyncDlmalloc {}
|
| 25 |
+
|
| 26 |
+
static DLMALLOC: SyncUnsafeCell<SyncDlmalloc> =
|
| 27 |
+
SyncUnsafeCell::new(SyncDlmalloc(dlmalloc::Dlmalloc::new()));
|
| 28 |
+
|
| 29 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 30 |
+
unsafe impl GlobalAlloc for System {
|
| 31 |
+
#[inline]
|
| 32 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 33 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
|
| 34 |
+
// Calling malloc() is safe because preconditions on this function match the trait method preconditions.
|
| 35 |
+
let _lock = lock::lock();
|
| 36 |
+
unsafe { (*DLMALLOC.get()).0.malloc(layout.size(), layout.align()) }
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
#[inline]
|
| 40 |
+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
| 41 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
|
| 42 |
+
// Calling calloc() is safe because preconditions on this function match the trait method preconditions.
|
| 43 |
+
let _lock = lock::lock();
|
| 44 |
+
unsafe { (*DLMALLOC.get()).0.calloc(layout.size(), layout.align()) }
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
#[inline]
|
| 48 |
+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
| 49 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
|
| 50 |
+
// Calling free() is safe because preconditions on this function match the trait method preconditions.
|
| 51 |
+
let _lock = lock::lock();
|
| 52 |
+
unsafe { (*DLMALLOC.get()).0.free(ptr, layout.size(), layout.align()) }
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
#[inline]
|
| 56 |
+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
| 57 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
|
| 58 |
+
// Calling realloc() is safe because preconditions on this function match the trait method preconditions.
|
| 59 |
+
let _lock = lock::lock();
|
| 60 |
+
unsafe { (*DLMALLOC.get()).0.realloc(ptr, layout.size(), layout.align(), new_size) }
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
#[cfg(target_feature = "atomics")]
|
| 65 |
+
mod lock {
|
| 66 |
+
use crate::sync::atomic::Ordering::{Acquire, Release};
|
| 67 |
+
use crate::sync::atomic::{Atomic, AtomicI32};
|
| 68 |
+
|
| 69 |
+
static LOCKED: Atomic<i32> = AtomicI32::new(0);
|
| 70 |
+
|
| 71 |
+
pub struct DropLock;
|
| 72 |
+
|
| 73 |
+
pub fn lock() -> DropLock {
|
| 74 |
+
loop {
|
| 75 |
+
if LOCKED.swap(1, Acquire) == 0 {
|
| 76 |
+
return DropLock;
|
| 77 |
+
}
|
| 78 |
+
// Ok so here's where things get a little depressing. At this point
|
| 79 |
+
// in time we need to synchronously acquire a lock, but we're
|
| 80 |
+
// contending with some other thread. Typically we'd execute some
|
| 81 |
+
// form of `i32.atomic.wait` like so:
|
| 82 |
+
//
|
| 83 |
+
// unsafe {
|
| 84 |
+
// let r = core::arch::wasm32::i32_atomic_wait(
|
| 85 |
+
// LOCKED.as_mut_ptr(),
|
| 86 |
+
// 1, // expected value
|
| 87 |
+
// -1, // timeout
|
| 88 |
+
// );
|
| 89 |
+
// debug_assert!(r == 0 || r == 1);
|
| 90 |
+
// }
|
| 91 |
+
//
|
| 92 |
+
// Unfortunately though in doing so we would cause issues for the
|
| 93 |
+
// main thread. The main thread in a web browser *cannot ever
|
| 94 |
+
// block*, no exceptions. This means that the main thread can't
|
| 95 |
+
// actually execute the `i32.atomic.wait` instruction.
|
| 96 |
+
//
|
| 97 |
+
// As a result if we want to work within the context of browsers we
|
| 98 |
+
// need to figure out some sort of allocation scheme for the main
|
| 99 |
+
// thread where when there's contention on the global malloc lock we
|
| 100 |
+
// do... something.
|
| 101 |
+
//
|
| 102 |
+
// Possible ideas include:
|
| 103 |
+
//
|
| 104 |
+
// 1. Attempt to acquire the global lock. If it fails, fall back to
|
| 105 |
+
// memory allocation via `memory.grow`. Later just ... somehow
|
| 106 |
+
// ... inject this raw page back into the main allocator as it
|
| 107 |
+
// gets sliced up over time. This strategy has the downside of
|
| 108 |
+
// forcing allocation of a page to happen whenever the main
|
| 109 |
+
// thread contents with other threads, which is unfortunate.
|
| 110 |
+
//
|
| 111 |
+
// 2. Maintain a form of "two level" allocator scheme where the main
|
| 112 |
+
// thread has its own allocator. Somehow this allocator would
|
| 113 |
+
// also be balanced with a global allocator, not only to have
|
| 114 |
+
// allocations cross between threads but also to ensure that the
|
| 115 |
+
// two allocators stay "balanced" in terms of free'd memory and
|
| 116 |
+
// such. This, however, seems significantly complicated.
|
| 117 |
+
//
|
| 118 |
+
// Out of a lack of other ideas, the current strategy implemented
|
| 119 |
+
// here is to simply spin. Typical spin loop algorithms have some
|
| 120 |
+
// form of "hint" here to the CPU that it's what we're doing to
|
| 121 |
+
// ensure that the CPU doesn't get too hot, but wasm doesn't have
|
| 122 |
+
// such an instruction.
|
| 123 |
+
//
|
| 124 |
+
// To be clear, spinning here is not a great solution.
|
| 125 |
+
// Another thread with the lock may take quite a long time to wake
|
| 126 |
+
// up. For example it could be in `memory.grow` or it could be
|
| 127 |
+
// evicted from the CPU for a timeslice like 10ms. For these periods
|
| 128 |
+
// of time our thread will "helpfully" sit here and eat CPU time
|
| 129 |
+
// until it itself is evicted or the lock holder finishes. This
|
| 130 |
+
// means we're just burning and wasting CPU time to no one's
|
| 131 |
+
// benefit.
|
| 132 |
+
//
|
| 133 |
+
// Spinning does have the nice properties, though, of being
|
| 134 |
+
// semantically correct, being fair to all threads for memory
|
| 135 |
+
// allocation, and being simple enough to implement.
|
| 136 |
+
//
|
| 137 |
+
// This will surely (hopefully) be replaced in the future with a
|
| 138 |
+
// real memory allocator that can handle the restriction of the main
|
| 139 |
+
// thread.
|
| 140 |
+
//
|
| 141 |
+
//
|
| 142 |
+
// FIXME: We can also possibly add an optimization here to detect
|
| 143 |
+
// when a thread is the main thread or not and block on all
|
| 144 |
+
// non-main-thread threads. Currently, however, we have no way
|
| 145 |
+
// of knowing which wasm thread is on the browser main thread, but
|
| 146 |
+
// if we could figure out we could at least somewhat mitigate the
|
| 147 |
+
// cost of this spinning.
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
impl Drop for DropLock {
|
| 152 |
+
fn drop(&mut self) {
|
| 153 |
+
let r = LOCKED.swap(0, Release);
|
| 154 |
+
debug_assert_eq!(r, 1);
|
| 155 |
+
|
| 156 |
+
// Note that due to the above logic we don't actually need to wake
|
| 157 |
+
// anyone up, but if we did it'd likely look something like this:
|
| 158 |
+
//
|
| 159 |
+
// unsafe {
|
| 160 |
+
// core::arch::wasm32::atomic_notify(
|
| 161 |
+
// LOCKED.as_mut_ptr(),
|
| 162 |
+
// 1, // only one thread
|
| 163 |
+
// );
|
| 164 |
+
// }
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
#[cfg(not(target_feature = "atomics"))]
|
| 170 |
+
mod lock {
|
| 171 |
+
#[inline]
|
| 172 |
+
pub fn lock() {} // no atomics, no threads, that's easy!
|
| 173 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/windows.rs
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 6 |
+
use crate::sys::c;
|
| 7 |
+
|
| 8 |
+
#[cfg(test)]
|
| 9 |
+
mod tests;
|
| 10 |
+
|
| 11 |
+
// Heap memory management on Windows is done by using the system Heap API (heapapi.h)
|
| 12 |
+
// See https://docs.microsoft.com/windows/win32/api/heapapi/
|
| 13 |
+
|
| 14 |
+
// Flag to indicate that the memory returned by `HeapAlloc` should be zeroed.
|
| 15 |
+
const HEAP_ZERO_MEMORY: u32 = 0x00000008;
|
| 16 |
+
|
| 17 |
+
// Get a handle to the default heap of the current process, or null if the operation fails.
|
| 18 |
+
//
|
| 19 |
+
// SAFETY: Successful calls to this function within the same process are assumed to
|
| 20 |
+
// always return the same handle, which remains valid for the entire lifetime of the process.
|
| 21 |
+
//
|
| 22 |
+
// See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-getprocessheap
|
| 23 |
+
windows_link::link!("kernel32.dll" "system" fn GetProcessHeap() -> c::HANDLE);
|
| 24 |
+
|
| 25 |
+
// Allocate a block of `dwBytes` bytes of memory from a given heap `hHeap`.
|
| 26 |
+
// The allocated memory may be uninitialized, or zeroed if `dwFlags` is
|
| 27 |
+
// set to `HEAP_ZERO_MEMORY`.
|
| 28 |
+
//
|
| 29 |
+
// Returns a pointer to the newly-allocated memory or null if the operation fails.
|
| 30 |
+
// The returned pointer will be aligned to at least `MIN_ALIGN`.
|
| 31 |
+
//
|
| 32 |
+
// SAFETY:
|
| 33 |
+
// - `hHeap` must be a non-null handle returned by `GetProcessHeap`.
|
| 34 |
+
// - `dwFlags` must be set to either zero or `HEAP_ZERO_MEMORY`.
|
| 35 |
+
//
|
| 36 |
+
// Note that `dwBytes` is allowed to be zero, contrary to some other allocators.
|
| 37 |
+
//
|
| 38 |
+
// See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heapalloc
|
| 39 |
+
windows_link::link!("kernel32.dll" "system" fn HeapAlloc(hheap: c::HANDLE, dwflags: u32, dwbytes: usize) -> *mut c_void);
|
| 40 |
+
|
| 41 |
+
// Reallocate a block of memory behind a given pointer `lpMem` from a given heap `hHeap`,
|
| 42 |
+
// to a block of at least `dwBytes` bytes, either shrinking the block in place,
|
| 43 |
+
// or allocating at a new location, copying memory, and freeing the original location.
|
| 44 |
+
//
|
| 45 |
+
// Returns a pointer to the reallocated memory or null if the operation fails.
|
| 46 |
+
// The returned pointer will be aligned to at least `MIN_ALIGN`.
|
| 47 |
+
// If the operation fails the given block will never have been freed.
|
| 48 |
+
//
|
| 49 |
+
// SAFETY:
|
| 50 |
+
// - `hHeap` must be a non-null handle returned by `GetProcessHeap`.
|
| 51 |
+
// - `dwFlags` must be set to zero.
|
| 52 |
+
// - `lpMem` must be a non-null pointer to an allocated block returned by `HeapAlloc` or
|
| 53 |
+
// `HeapReAlloc`, that has not already been freed.
|
| 54 |
+
// If the block was successfully reallocated at a new location, pointers pointing to
|
| 55 |
+
// the freed memory, such as `lpMem`, must not be dereferenced ever again.
|
| 56 |
+
//
|
| 57 |
+
// Note that `dwBytes` is allowed to be zero, contrary to some other allocators.
|
| 58 |
+
//
|
| 59 |
+
// See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heaprealloc
|
| 60 |
+
windows_link::link!("kernel32.dll" "system" fn HeapReAlloc(
|
| 61 |
+
hheap: c::HANDLE,
|
| 62 |
+
dwflags : u32,
|
| 63 |
+
lpmem: *const c_void,
|
| 64 |
+
dwbytes: usize
|
| 65 |
+
) -> *mut c_void);
|
| 66 |
+
|
| 67 |
+
// Free a block of memory behind a given pointer `lpMem` from a given heap `hHeap`.
|
| 68 |
+
// Returns a nonzero value if the operation is successful, and zero if the operation fails.
|
| 69 |
+
//
|
| 70 |
+
// SAFETY:
|
| 71 |
+
// - `hHeap` must be a non-null handle returned by `GetProcessHeap`.
|
| 72 |
+
// - `dwFlags` must be set to zero.
|
| 73 |
+
// - `lpMem` must be a pointer to an allocated block returned by `HeapAlloc` or `HeapReAlloc`,
|
| 74 |
+
// that has not already been freed.
|
| 75 |
+
// If the block was successfully freed, pointers pointing to the freed memory, such as `lpMem`,
|
| 76 |
+
// must not be dereferenced ever again.
|
| 77 |
+
//
|
| 78 |
+
// Note that `lpMem` is allowed to be null, which will not cause the operation to fail.
|
| 79 |
+
//
|
| 80 |
+
// See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heapfree
|
| 81 |
+
windows_link::link!("kernel32.dll" "system" fn HeapFree(hheap: c::HANDLE, dwflags: u32, lpmem: *const c_void) -> c::BOOL);
|
| 82 |
+
|
| 83 |
+
fn get_process_heap() -> *mut c_void {
|
| 84 |
+
// SAFETY: GetProcessHeap simply returns a valid handle or NULL so is always safe to call.
|
| 85 |
+
unsafe { GetProcessHeap() }
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
#[inline(never)]
|
| 89 |
+
fn process_heap_alloc(
|
| 90 |
+
_heap: MaybeUninit<c::HANDLE>, // We pass this argument to match the ABI of `HeapAlloc`,
|
| 91 |
+
flags: u32,
|
| 92 |
+
bytes: usize,
|
| 93 |
+
) -> *mut c_void {
|
| 94 |
+
let heap = get_process_heap();
|
| 95 |
+
if core::intrinsics::unlikely(heap.is_null()) {
|
| 96 |
+
return ptr::null_mut();
|
| 97 |
+
}
|
| 98 |
+
// SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`.
|
| 99 |
+
unsafe { HeapAlloc(heap, flags, bytes) }
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
// Header containing a pointer to the start of an allocated block.
|
| 103 |
+
// SAFETY: Size and alignment must be <= `MIN_ALIGN`.
|
| 104 |
+
#[repr(C)]
|
| 105 |
+
struct Header(*mut u8);
|
| 106 |
+
|
| 107 |
+
// Allocate a block of optionally zeroed memory for a given `layout`.
|
| 108 |
+
// SAFETY: Returns a pointer satisfying the guarantees of `System` about allocated pointers,
|
| 109 |
+
// or null if the operation fails. If this returns non-null `HEAP` will have been successfully
|
| 110 |
+
// initialized.
|
| 111 |
+
#[inline]
|
| 112 |
+
unsafe fn allocate(layout: Layout, zeroed: bool) -> *mut u8 {
|
| 113 |
+
// Allocated memory will be either zeroed or uninitialized.
|
| 114 |
+
let flags = if zeroed { HEAP_ZERO_MEMORY } else { 0 };
|
| 115 |
+
|
| 116 |
+
if layout.align() <= MIN_ALIGN {
|
| 117 |
+
// The returned pointer points to the start of an allocated block.
|
| 118 |
+
process_heap_alloc(MaybeUninit::uninit(), flags, layout.size()) as *mut u8
|
| 119 |
+
} else {
|
| 120 |
+
// Allocate extra padding in order to be able to satisfy the alignment.
|
| 121 |
+
let total = layout.align() + layout.size();
|
| 122 |
+
|
| 123 |
+
let ptr = process_heap_alloc(MaybeUninit::uninit(), flags, total) as *mut u8;
|
| 124 |
+
if ptr.is_null() {
|
| 125 |
+
// Allocation has failed.
|
| 126 |
+
return ptr::null_mut();
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
// Create a correctly aligned pointer offset from the start of the allocated block,
|
| 130 |
+
// and write a header before it.
|
| 131 |
+
|
| 132 |
+
let offset = layout.align() - (ptr.addr() & (layout.align() - 1));
|
| 133 |
+
// SAFETY: `MIN_ALIGN` <= `offset` <= `layout.align()` and the size of the allocated
|
| 134 |
+
// block is `layout.align() + layout.size()`. `aligned` will thus be a correctly aligned
|
| 135 |
+
// pointer inside the allocated block with at least `layout.size()` bytes after it and at
|
| 136 |
+
// least `MIN_ALIGN` bytes of padding before it.
|
| 137 |
+
let aligned = unsafe { ptr.add(offset) };
|
| 138 |
+
// SAFETY: Because the size and alignment of a header is <= `MIN_ALIGN` and `aligned`
|
| 139 |
+
// is aligned to at least `MIN_ALIGN` and has at least `MIN_ALIGN` bytes of padding before
|
| 140 |
+
// it, it is safe to write a header directly before it.
|
| 141 |
+
unsafe { ptr::write((aligned as *mut Header).sub(1), Header(ptr)) };
|
| 142 |
+
|
| 143 |
+
// SAFETY: The returned pointer does not point to the start of an allocated block,
|
| 144 |
+
// but there is a header readable directly before it containing the location of the start
|
| 145 |
+
// of the block.
|
| 146 |
+
aligned
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
// All pointers returned by this allocator have, in addition to the guarantees of `GlobalAlloc`, the
|
| 151 |
+
// following properties:
|
| 152 |
+
//
|
| 153 |
+
// If the pointer was allocated or reallocated with a `layout` specifying an alignment <= `MIN_ALIGN`
|
| 154 |
+
// the pointer will be aligned to at least `MIN_ALIGN` and point to the start of the allocated block.
|
| 155 |
+
//
|
| 156 |
+
// If the pointer was allocated or reallocated with a `layout` specifying an alignment > `MIN_ALIGN`
|
| 157 |
+
// the pointer will be aligned to the specified alignment and not point to the start of the allocated block.
|
| 158 |
+
// Instead there will be a header readable directly before the returned pointer, containing the actual
|
| 159 |
+
// location of the start of the block.
|
| 160 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 161 |
+
unsafe impl GlobalAlloc for System {
|
| 162 |
+
#[inline]
|
| 163 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 164 |
+
// SAFETY: Pointers returned by `allocate` satisfy the guarantees of `System`
|
| 165 |
+
let zeroed = false;
|
| 166 |
+
unsafe { allocate(layout, zeroed) }
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
#[inline]
|
| 170 |
+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
| 171 |
+
// SAFETY: Pointers returned by `allocate` satisfy the guarantees of `System`
|
| 172 |
+
let zeroed = true;
|
| 173 |
+
unsafe { allocate(layout, zeroed) }
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
#[inline]
|
| 177 |
+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
| 178 |
+
let block = {
|
| 179 |
+
if layout.align() <= MIN_ALIGN {
|
| 180 |
+
ptr
|
| 181 |
+
} else {
|
| 182 |
+
// The location of the start of the block is stored in the padding before `ptr`.
|
| 183 |
+
|
| 184 |
+
// SAFETY: Because of the contract of `System`, `ptr` is guaranteed to be non-null
|
| 185 |
+
// and have a header readable directly before it.
|
| 186 |
+
unsafe { ptr::read((ptr as *mut Header).sub(1)).0 }
|
| 187 |
+
}
|
| 188 |
+
};
|
| 189 |
+
|
| 190 |
+
// because `ptr` has been successfully allocated with this allocator,
|
| 191 |
+
// there must be a valid process heap.
|
| 192 |
+
let heap = get_process_heap();
|
| 193 |
+
|
| 194 |
+
// SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`,
|
| 195 |
+
// `block` is a pointer to the start of an allocated block.
|
| 196 |
+
unsafe { HeapFree(heap, 0, block.cast::<c_void>()) };
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
#[inline]
|
| 200 |
+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
| 201 |
+
if layout.align() <= MIN_ALIGN {
|
| 202 |
+
// because `ptr` has been successfully allocated with this allocator,
|
| 203 |
+
// there must be a valid process heap.
|
| 204 |
+
let heap = get_process_heap();
|
| 205 |
+
|
| 206 |
+
// SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`,
|
| 207 |
+
// `ptr` is a pointer to the start of an allocated block.
|
| 208 |
+
// The returned pointer points to the start of an allocated block.
|
| 209 |
+
unsafe { HeapReAlloc(heap, 0, ptr.cast::<c_void>(), new_size).cast::<u8>() }
|
| 210 |
+
} else {
|
| 211 |
+
// SAFETY: `realloc_fallback` is implemented using `dealloc` and `alloc`, which will
|
| 212 |
+
// correctly handle `ptr` and return a pointer satisfying the guarantees of `System`
|
| 213 |
+
unsafe { realloc_fallback(self, ptr, layout, new_size) }
|
| 214 |
+
}
|
| 215 |
+
}
|
| 216 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/xous.rs
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// FIXME(static_mut_refs): Do not allow `static_mut_refs` lint
|
| 2 |
+
#![allow(static_mut_refs)]
|
| 3 |
+
|
| 4 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 5 |
+
|
| 6 |
+
#[cfg(not(test))]
|
| 7 |
+
#[unsafe(export_name = "_ZN16__rust_internals3std3sys4xous5alloc8DLMALLOCE")]
|
| 8 |
+
static mut DLMALLOC: dlmalloc::Dlmalloc = dlmalloc::Dlmalloc::new();
|
| 9 |
+
|
| 10 |
+
#[cfg(test)]
|
| 11 |
+
unsafe extern "Rust" {
|
| 12 |
+
#[link_name = "_ZN16__rust_internals3std3sys4xous5alloc8DLMALLOCE"]
|
| 13 |
+
static mut DLMALLOC: dlmalloc::Dlmalloc;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 17 |
+
unsafe impl GlobalAlloc for System {
|
| 18 |
+
#[inline]
|
| 19 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 20 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
|
| 21 |
+
// Calling malloc() is safe because preconditions on this function match the trait method preconditions.
|
| 22 |
+
let _lock = lock::lock();
|
| 23 |
+
unsafe { DLMALLOC.malloc(layout.size(), layout.align()) }
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
#[inline]
|
| 27 |
+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
| 28 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
|
| 29 |
+
// Calling calloc() is safe because preconditions on this function match the trait method preconditions.
|
| 30 |
+
let _lock = lock::lock();
|
| 31 |
+
unsafe { DLMALLOC.calloc(layout.size(), layout.align()) }
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
#[inline]
|
| 35 |
+
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
| 36 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
|
| 37 |
+
// Calling free() is safe because preconditions on this function match the trait method preconditions.
|
| 38 |
+
let _lock = lock::lock();
|
| 39 |
+
unsafe { DLMALLOC.free(ptr, layout.size(), layout.align()) }
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
#[inline]
|
| 43 |
+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
| 44 |
+
// SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
|
| 45 |
+
// Calling realloc() is safe because preconditions on this function match the trait method preconditions.
|
| 46 |
+
let _lock = lock::lock();
|
| 47 |
+
unsafe { DLMALLOC.realloc(ptr, layout.size(), layout.align(), new_size) }
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
mod lock {
|
| 52 |
+
use crate::sync::atomic::Ordering::{Acquire, Release};
|
| 53 |
+
use crate::sync::atomic::{Atomic, AtomicI32};
|
| 54 |
+
|
| 55 |
+
static LOCKED: Atomic<i32> = AtomicI32::new(0);
|
| 56 |
+
|
| 57 |
+
pub struct DropLock;
|
| 58 |
+
|
| 59 |
+
pub fn lock() -> DropLock {
|
| 60 |
+
loop {
|
| 61 |
+
if LOCKED.swap(1, Acquire) == 0 {
|
| 62 |
+
return DropLock;
|
| 63 |
+
}
|
| 64 |
+
crate::os::xous::ffi::do_yield();
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
impl Drop for DropLock {
|
| 69 |
+
fn drop(&mut self) {
|
| 70 |
+
let r = LOCKED.swap(0, Release);
|
| 71 |
+
debug_assert_eq!(r, 1);
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/alloc/zkvm.rs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::alloc::{GlobalAlloc, Layout, System};
|
| 2 |
+
use crate::sys::pal::abi;
|
| 3 |
+
|
| 4 |
+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
|
| 5 |
+
unsafe impl GlobalAlloc for System {
|
| 6 |
+
#[inline]
|
| 7 |
+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
| 8 |
+
unsafe { abi::sys_alloc_aligned(layout.size(), layout.align()) }
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
#[inline]
|
| 12 |
+
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {
|
| 13 |
+
// this allocator never deallocates memory
|
| 14 |
+
}
|
| 15 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/common.rs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::ffi::OsString;
|
| 2 |
+
use crate::num::NonZero;
|
| 3 |
+
use crate::ops::Try;
|
| 4 |
+
use crate::{array, fmt, vec};
|
| 5 |
+
|
| 6 |
+
pub struct Args {
|
| 7 |
+
iter: vec::IntoIter<OsString>,
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
impl !Send for Args {}
|
| 11 |
+
impl !Sync for Args {}
|
| 12 |
+
|
| 13 |
+
impl Args {
|
| 14 |
+
#[inline]
|
| 15 |
+
pub fn new(args: Vec<OsString>) -> Self {
|
| 16 |
+
Args { iter: args.into_iter() }
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
impl fmt::Debug for Args {
|
| 21 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 22 |
+
self.iter.as_slice().fmt(f)
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
impl Iterator for Args {
|
| 27 |
+
type Item = OsString;
|
| 28 |
+
|
| 29 |
+
#[inline]
|
| 30 |
+
fn next(&mut self) -> Option<OsString> {
|
| 31 |
+
self.iter.next()
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
#[inline]
|
| 35 |
+
fn next_chunk<const N: usize>(
|
| 36 |
+
&mut self,
|
| 37 |
+
) -> Result<[OsString; N], array::IntoIter<OsString, N>> {
|
| 38 |
+
self.iter.next_chunk()
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
#[inline]
|
| 42 |
+
fn size_hint(&self) -> (usize, Option<usize>) {
|
| 43 |
+
self.iter.size_hint()
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
#[inline]
|
| 47 |
+
fn count(self) -> usize {
|
| 48 |
+
self.iter.len()
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
#[inline]
|
| 52 |
+
fn last(self) -> Option<OsString> {
|
| 53 |
+
self.iter.last()
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
#[inline]
|
| 57 |
+
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
|
| 58 |
+
self.iter.advance_by(n)
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
#[inline]
|
| 62 |
+
fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
|
| 63 |
+
where
|
| 64 |
+
F: FnMut(B, Self::Item) -> R,
|
| 65 |
+
R: Try<Output = B>,
|
| 66 |
+
{
|
| 67 |
+
self.iter.try_fold(init, f)
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
#[inline]
|
| 71 |
+
fn fold<B, F>(self, init: B, f: F) -> B
|
| 72 |
+
where
|
| 73 |
+
F: FnMut(B, Self::Item) -> B,
|
| 74 |
+
{
|
| 75 |
+
self.iter.fold(init, f)
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
impl DoubleEndedIterator for Args {
|
| 80 |
+
#[inline]
|
| 81 |
+
fn next_back(&mut self) -> Option<OsString> {
|
| 82 |
+
self.iter.next_back()
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
#[inline]
|
| 86 |
+
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
|
| 87 |
+
self.iter.advance_back_by(n)
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
impl ExactSizeIterator for Args {
|
| 92 |
+
#[inline]
|
| 93 |
+
fn len(&self) -> usize {
|
| 94 |
+
self.iter.len()
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
#[inline]
|
| 98 |
+
fn is_empty(&self) -> bool {
|
| 99 |
+
self.iter.is_empty()
|
| 100 |
+
}
|
| 101 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/mod.rs
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Platform-dependent command line arguments abstraction.
|
| 2 |
+
|
| 3 |
+
#![forbid(unsafe_op_in_unsafe_fn)]
|
| 4 |
+
|
| 5 |
+
#[cfg(any(
|
| 6 |
+
all(target_family = "unix", not(any(target_os = "espidf", target_os = "vita"))),
|
| 7 |
+
target_family = "windows",
|
| 8 |
+
target_os = "hermit",
|
| 9 |
+
target_os = "motor",
|
| 10 |
+
target_os = "uefi",
|
| 11 |
+
target_os = "wasi",
|
| 12 |
+
target_os = "xous",
|
| 13 |
+
))]
|
| 14 |
+
mod common;
|
| 15 |
+
|
| 16 |
+
cfg_select! {
|
| 17 |
+
any(
|
| 18 |
+
all(target_family = "unix", not(any(target_os = "espidf", target_os = "vita"))),
|
| 19 |
+
target_os = "hermit",
|
| 20 |
+
) => {
|
| 21 |
+
mod unix;
|
| 22 |
+
pub use unix::*;
|
| 23 |
+
}
|
| 24 |
+
target_family = "windows" => {
|
| 25 |
+
mod windows;
|
| 26 |
+
pub use windows::*;
|
| 27 |
+
}
|
| 28 |
+
all(target_vendor = "fortanix", target_env = "sgx") => {
|
| 29 |
+
mod sgx;
|
| 30 |
+
pub use sgx::*;
|
| 31 |
+
}
|
| 32 |
+
target_os = "motor" => {
|
| 33 |
+
mod motor;
|
| 34 |
+
pub use motor::*;
|
| 35 |
+
}
|
| 36 |
+
target_os = "uefi" => {
|
| 37 |
+
mod uefi;
|
| 38 |
+
pub use uefi::*;
|
| 39 |
+
}
|
| 40 |
+
all(target_os = "wasi", target_env = "p1") => {
|
| 41 |
+
mod wasip1;
|
| 42 |
+
pub use wasip1::*;
|
| 43 |
+
}
|
| 44 |
+
all(target_os = "wasi", any(target_env = "p2", target_env = "p3")) => {
|
| 45 |
+
mod wasip2;
|
| 46 |
+
pub use wasip2::*;
|
| 47 |
+
}
|
| 48 |
+
target_os = "xous" => {
|
| 49 |
+
mod xous;
|
| 50 |
+
pub use xous::*;
|
| 51 |
+
}
|
| 52 |
+
target_os = "zkvm" => {
|
| 53 |
+
mod zkvm;
|
| 54 |
+
pub use zkvm::*;
|
| 55 |
+
}
|
| 56 |
+
_ => {
|
| 57 |
+
mod unsupported;
|
| 58 |
+
pub use unsupported::*;
|
| 59 |
+
}
|
| 60 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/motor.rs
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pub use super::common::Args;
|
| 2 |
+
use crate::ffi::OsString;
|
| 3 |
+
|
| 4 |
+
pub fn args() -> Args {
|
| 5 |
+
let motor_args: Vec<String> = moto_rt::process::args();
|
| 6 |
+
let mut rust_args = Vec::new();
|
| 7 |
+
|
| 8 |
+
for arg in motor_args {
|
| 9 |
+
rust_args.push(OsString::from(arg));
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
Args::new(rust_args)
|
| 13 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/sgx.rs
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#![allow(fuzzy_provenance_casts)] // FIXME: this module systematically confuses pointers and integers
|
| 2 |
+
|
| 3 |
+
use crate::ffi::OsString;
|
| 4 |
+
use crate::num::NonZero;
|
| 5 |
+
use crate::ops::Try;
|
| 6 |
+
use crate::sync::atomic::{Atomic, AtomicUsize, Ordering};
|
| 7 |
+
use crate::sys::FromInner;
|
| 8 |
+
use crate::sys::os_str::Buf;
|
| 9 |
+
use crate::sys::pal::abi::usercalls::alloc;
|
| 10 |
+
use crate::sys::pal::abi::usercalls::raw::ByteBuffer;
|
| 11 |
+
use crate::{fmt, slice};
|
| 12 |
+
|
| 13 |
+
// Specifying linkage/symbol name is solely to ensure a single instance between this crate and its unit tests
|
| 14 |
+
#[cfg_attr(test, linkage = "available_externally")]
|
| 15 |
+
#[unsafe(export_name = "_ZN16__rust_internals3std3sys3sgx4args4ARGSE")]
|
| 16 |
+
static ARGS: Atomic<usize> = AtomicUsize::new(0);
|
| 17 |
+
type ArgsStore = Vec<OsString>;
|
| 18 |
+
|
| 19 |
+
#[cfg_attr(test, allow(dead_code))]
|
| 20 |
+
pub unsafe fn init(argc: isize, argv: *const *const u8) {
|
| 21 |
+
if argc != 0 {
|
| 22 |
+
let args = unsafe { alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _) };
|
| 23 |
+
let args = args
|
| 24 |
+
.iter()
|
| 25 |
+
.map(|a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }))
|
| 26 |
+
.collect::<ArgsStore>();
|
| 27 |
+
ARGS.store(Box::into_raw(Box::new(args)) as _, Ordering::Relaxed);
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
pub fn args() -> Args {
|
| 32 |
+
let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() };
|
| 33 |
+
let slice = args.map(|args| args.as_slice()).unwrap_or(&[]);
|
| 34 |
+
Args { iter: slice.iter() }
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
pub struct Args {
|
| 38 |
+
iter: slice::Iter<'static, OsString>,
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
impl fmt::Debug for Args {
|
| 42 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 43 |
+
self.iter.as_slice().fmt(f)
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
impl Iterator for Args {
|
| 48 |
+
type Item = OsString;
|
| 49 |
+
|
| 50 |
+
fn next(&mut self) -> Option<OsString> {
|
| 51 |
+
self.iter.next().cloned()
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
#[inline]
|
| 55 |
+
fn size_hint(&self) -> (usize, Option<usize>) {
|
| 56 |
+
self.iter.size_hint()
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
#[inline]
|
| 60 |
+
fn count(self) -> usize {
|
| 61 |
+
self.iter.len()
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
fn last(self) -> Option<OsString> {
|
| 65 |
+
self.iter.last().cloned()
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
#[inline]
|
| 69 |
+
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
|
| 70 |
+
self.iter.advance_by(n)
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
|
| 74 |
+
where
|
| 75 |
+
F: FnMut(B, Self::Item) -> R,
|
| 76 |
+
R: Try<Output = B>,
|
| 77 |
+
{
|
| 78 |
+
self.iter.by_ref().cloned().try_fold(init, f)
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
fn fold<B, F>(self, init: B, f: F) -> B
|
| 82 |
+
where
|
| 83 |
+
F: FnMut(B, Self::Item) -> B,
|
| 84 |
+
{
|
| 85 |
+
self.iter.cloned().fold(init, f)
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
impl DoubleEndedIterator for Args {
|
| 90 |
+
fn next_back(&mut self) -> Option<OsString> {
|
| 91 |
+
self.iter.next_back().cloned()
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
#[inline]
|
| 95 |
+
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
|
| 96 |
+
self.iter.advance_back_by(n)
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
impl ExactSizeIterator for Args {
|
| 101 |
+
#[inline]
|
| 102 |
+
fn len(&self) -> usize {
|
| 103 |
+
self.iter.len()
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
#[inline]
|
| 107 |
+
fn is_empty(&self) -> bool {
|
| 108 |
+
self.iter.is_empty()
|
| 109 |
+
}
|
| 110 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/uefi.rs
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use r_efi::protocols::loaded_image;
|
| 2 |
+
|
| 3 |
+
pub use super::common::Args;
|
| 4 |
+
use crate::env::current_exe;
|
| 5 |
+
use crate::ffi::OsString;
|
| 6 |
+
use crate::iter::Iterator;
|
| 7 |
+
use crate::sys::pal::helpers;
|
| 8 |
+
|
| 9 |
+
pub fn args() -> Args {
|
| 10 |
+
let lazy_current_exe = || Vec::from([current_exe().map(Into::into).unwrap_or_default()]);
|
| 11 |
+
|
| 12 |
+
// Each loaded image has an image handle that supports `EFI_LOADED_IMAGE_PROTOCOL`. Thus, this
|
| 13 |
+
// will never fail.
|
| 14 |
+
let protocol =
|
| 15 |
+
helpers::image_handle_protocol::<loaded_image::Protocol>(loaded_image::PROTOCOL_GUID)
|
| 16 |
+
.unwrap();
|
| 17 |
+
|
| 18 |
+
let lp_size = unsafe { (*protocol.as_ptr()).load_options_size } as usize;
|
| 19 |
+
// Break if we are sure that it cannot be UTF-16
|
| 20 |
+
if lp_size < size_of::<u16>() || lp_size % size_of::<u16>() != 0 {
|
| 21 |
+
return Args::new(lazy_current_exe());
|
| 22 |
+
}
|
| 23 |
+
let lp_size = lp_size / size_of::<u16>();
|
| 24 |
+
|
| 25 |
+
let lp_cmd_line = unsafe { (*protocol.as_ptr()).load_options as *const u16 };
|
| 26 |
+
if !lp_cmd_line.is_aligned() {
|
| 27 |
+
return Args::new(lazy_current_exe());
|
| 28 |
+
}
|
| 29 |
+
let lp_cmd_line = unsafe { crate::slice::from_raw_parts(lp_cmd_line, lp_size) };
|
| 30 |
+
|
| 31 |
+
Args::new(parse_lp_cmd_line(lp_cmd_line).unwrap_or_else(lazy_current_exe))
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
/// Implements the UEFI command-line argument parsing algorithm.
|
| 35 |
+
///
|
| 36 |
+
/// This implementation is based on what is defined in Section 3.4 of
|
| 37 |
+
/// [UEFI Shell Specification](https://uefi.org/sites/default/files/resources/UEFI_Shell_Spec_2_0.pdf)
|
| 38 |
+
///
|
| 39 |
+
/// Returns None in the following cases:
|
| 40 |
+
/// - Invalid UTF-16 (unpaired surrogate)
|
| 41 |
+
/// - Empty/improper arguments
|
| 42 |
+
fn parse_lp_cmd_line(code_units: &[u16]) -> Option<Vec<OsString>> {
|
| 43 |
+
const QUOTE: char = '"';
|
| 44 |
+
const SPACE: char = ' ';
|
| 45 |
+
const CARET: char = '^';
|
| 46 |
+
const NULL: char = '\0';
|
| 47 |
+
|
| 48 |
+
let mut ret_val = Vec::new();
|
| 49 |
+
let mut code_units_iter = char::decode_utf16(code_units.iter().cloned()).peekable();
|
| 50 |
+
|
| 51 |
+
// The executable name at the beginning is special.
|
| 52 |
+
let mut in_quotes = false;
|
| 53 |
+
let mut cur = String::new();
|
| 54 |
+
while let Some(w) = code_units_iter.next() {
|
| 55 |
+
let w = w.ok()?;
|
| 56 |
+
match w {
|
| 57 |
+
// break on NULL
|
| 58 |
+
NULL => break,
|
| 59 |
+
// A quote mark always toggles `in_quotes` no matter what because
|
| 60 |
+
// there are no escape characters when parsing the executable name.
|
| 61 |
+
QUOTE => in_quotes = !in_quotes,
|
| 62 |
+
// If not `in_quotes` then whitespace ends argv[0].
|
| 63 |
+
SPACE if !in_quotes => break,
|
| 64 |
+
// In all other cases the code unit is taken literally.
|
| 65 |
+
_ => cur.push(w),
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
// If exe name is missing, the cli args are invalid
|
| 70 |
+
if cur.is_empty() {
|
| 71 |
+
return None;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
ret_val.push(OsString::from(cur));
|
| 75 |
+
// Skip whitespace.
|
| 76 |
+
while code_units_iter.next_if_eq(&Ok(SPACE)).is_some() {}
|
| 77 |
+
|
| 78 |
+
// Parse the arguments according to these rules:
|
| 79 |
+
// * All code units are taken literally except space, quote and caret.
|
| 80 |
+
// * When not `in_quotes`, space separate arguments. Consecutive spaces are
|
| 81 |
+
// treated as a single separator.
|
| 82 |
+
// * A space `in_quotes` is taken literally.
|
| 83 |
+
// * A quote toggles `in_quotes` mode unless it's escaped. An escaped quote is taken literally.
|
| 84 |
+
// * A quote can be escaped if preceded by caret.
|
| 85 |
+
// * A caret can be escaped if preceded by caret.
|
| 86 |
+
let mut cur = String::new();
|
| 87 |
+
let mut in_quotes = false;
|
| 88 |
+
while let Some(w) = code_units_iter.next() {
|
| 89 |
+
let w = w.ok()?;
|
| 90 |
+
match w {
|
| 91 |
+
// break on NULL
|
| 92 |
+
NULL => break,
|
| 93 |
+
// If not `in_quotes`, a space or tab ends the argument.
|
| 94 |
+
SPACE if !in_quotes => {
|
| 95 |
+
ret_val.push(OsString::from(&cur[..]));
|
| 96 |
+
cur.truncate(0);
|
| 97 |
+
|
| 98 |
+
// Skip whitespace.
|
| 99 |
+
while code_units_iter.next_if_eq(&Ok(SPACE)).is_some() {}
|
| 100 |
+
}
|
| 101 |
+
// Caret can escape quotes or carets
|
| 102 |
+
CARET if in_quotes => {
|
| 103 |
+
if let Some(x) = code_units_iter.next() {
|
| 104 |
+
cur.push(x.ok()?);
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
// If quote then flip `in_quotes`
|
| 108 |
+
QUOTE => in_quotes = !in_quotes,
|
| 109 |
+
// Everything else is always taken literally.
|
| 110 |
+
_ => cur.push(w),
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
// Push the final argument, if any.
|
| 114 |
+
if !cur.is_empty() || in_quotes {
|
| 115 |
+
ret_val.push(OsString::from(cur));
|
| 116 |
+
}
|
| 117 |
+
Some(ret_val)
|
| 118 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/unix.rs
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Global initialization and retrieval of command line arguments.
|
| 2 |
+
//!
|
| 3 |
+
//! On some platforms these are stored during runtime startup,
|
| 4 |
+
//! and on some they are retrieved from the system on demand.
|
| 5 |
+
|
| 6 |
+
#![allow(dead_code)] // runtime init functions not used during testing
|
| 7 |
+
|
| 8 |
+
pub use super::common::Args;
|
| 9 |
+
use crate::ffi::CStr;
|
| 10 |
+
#[cfg(target_os = "hermit")]
|
| 11 |
+
use crate::os::hermit::ffi::OsStringExt;
|
| 12 |
+
#[cfg(not(target_os = "hermit"))]
|
| 13 |
+
use crate::os::unix::ffi::OsStringExt;
|
| 14 |
+
|
| 15 |
+
/// One-time global initialization.
|
| 16 |
+
pub unsafe fn init(argc: isize, argv: *const *const u8) {
|
| 17 |
+
unsafe { imp::init(argc, argv) }
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
/// Returns the command line arguments
|
| 21 |
+
pub fn args() -> Args {
|
| 22 |
+
let (argc, argv) = imp::argc_argv();
|
| 23 |
+
|
| 24 |
+
let mut vec = Vec::with_capacity(argc as usize);
|
| 25 |
+
|
| 26 |
+
for i in 0..argc {
|
| 27 |
+
// SAFETY: `argv` is non-null if `argc` is positive, and it is
|
| 28 |
+
// guaranteed to be at least as long as `argc`, so reading from it
|
| 29 |
+
// should be safe.
|
| 30 |
+
let ptr = unsafe { argv.offset(i).read() };
|
| 31 |
+
|
| 32 |
+
// Some C commandline parsers (e.g. GLib and Qt) are replacing already
|
| 33 |
+
// handled arguments in `argv` with `NULL` and move them to the end.
|
| 34 |
+
//
|
| 35 |
+
// Since they can't directly ensure updates to `argc` as well, this
|
| 36 |
+
// means that `argc` might be bigger than the actual number of
|
| 37 |
+
// non-`NULL` pointers in `argv` at this point.
|
| 38 |
+
//
|
| 39 |
+
// To handle this we simply stop iterating at the first `NULL`
|
| 40 |
+
// argument. `argv` is also guaranteed to be `NULL`-terminated so any
|
| 41 |
+
// non-`NULL` arguments after the first `NULL` can safely be ignored.
|
| 42 |
+
if ptr.is_null() {
|
| 43 |
+
// NOTE: On Apple platforms, `-[NSProcessInfo arguments]` does not
|
| 44 |
+
// stop iterating here, but instead `continue`, always iterating
|
| 45 |
+
// up until it reached `argc`.
|
| 46 |
+
//
|
| 47 |
+
// This difference will only matter in very specific circumstances
|
| 48 |
+
// where `argc`/`argv` have been modified, but in unexpected ways,
|
| 49 |
+
// so it likely doesn't really matter which option we choose.
|
| 50 |
+
// See the following PR for further discussion:
|
| 51 |
+
// <https://github.com/rust-lang/rust/pull/125225>
|
| 52 |
+
break;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
// SAFETY: Just checked that the pointer is not NULL, and arguments
|
| 56 |
+
// are otherwise guaranteed to be valid C strings.
|
| 57 |
+
let cstr = unsafe { CStr::from_ptr(ptr) };
|
| 58 |
+
vec.push(OsStringExt::from_vec(cstr.to_bytes().to_vec()));
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
Args::new(vec)
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
#[cfg(any(
|
| 65 |
+
target_os = "linux",
|
| 66 |
+
target_os = "android",
|
| 67 |
+
target_os = "freebsd",
|
| 68 |
+
target_os = "dragonfly",
|
| 69 |
+
target_os = "netbsd",
|
| 70 |
+
target_os = "openbsd",
|
| 71 |
+
target_os = "cygwin",
|
| 72 |
+
target_os = "solaris",
|
| 73 |
+
target_os = "illumos",
|
| 74 |
+
target_os = "emscripten",
|
| 75 |
+
target_os = "haiku",
|
| 76 |
+
target_os = "hermit",
|
| 77 |
+
target_os = "l4re",
|
| 78 |
+
target_os = "fuchsia",
|
| 79 |
+
target_os = "redox",
|
| 80 |
+
target_os = "vxworks",
|
| 81 |
+
target_os = "horizon",
|
| 82 |
+
target_os = "aix",
|
| 83 |
+
target_os = "nto",
|
| 84 |
+
target_os = "hurd",
|
| 85 |
+
target_os = "rtems",
|
| 86 |
+
target_os = "nuttx",
|
| 87 |
+
))]
|
| 88 |
+
mod imp {
|
| 89 |
+
use crate::ffi::c_char;
|
| 90 |
+
use crate::ptr;
|
| 91 |
+
use crate::sync::atomic::{Atomic, AtomicIsize, AtomicPtr, Ordering};
|
| 92 |
+
|
| 93 |
+
// The system-provided argc and argv, which we store in static memory
|
| 94 |
+
// here so that we can defer the work of parsing them until its actually
|
| 95 |
+
// needed.
|
| 96 |
+
//
|
| 97 |
+
// Note that we never mutate argv/argc, the argv array, or the argv
|
| 98 |
+
// strings, which allows the code in this file to be very simple.
|
| 99 |
+
static ARGC: Atomic<isize> = AtomicIsize::new(0);
|
| 100 |
+
static ARGV: Atomic<*mut *const u8> = AtomicPtr::new(ptr::null_mut());
|
| 101 |
+
|
| 102 |
+
unsafe fn really_init(argc: isize, argv: *const *const u8) {
|
| 103 |
+
// These don't need to be ordered with each other or other stores,
|
| 104 |
+
// because they only hold the unmodified system-provided argv/argc.
|
| 105 |
+
ARGC.store(argc, Ordering::Relaxed);
|
| 106 |
+
ARGV.store(argv as *mut _, Ordering::Relaxed);
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
#[inline(always)]
|
| 110 |
+
pub unsafe fn init(argc: isize, argv: *const *const u8) {
|
| 111 |
+
// on GNU/Linux if we are main then we will init argv and argc twice, it "duplicates work"
|
| 112 |
+
// BUT edge-cases are real: only using .init_array can break most emulators, dlopen, etc.
|
| 113 |
+
unsafe { really_init(argc, argv) };
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
/// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension.
|
| 117 |
+
/// This allows `std::env::args` to work even in a `cdylib`, as it does on macOS and Windows.
|
| 118 |
+
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
| 119 |
+
#[used]
|
| 120 |
+
#[unsafe(link_section = ".init_array.00099")]
|
| 121 |
+
static ARGV_INIT_ARRAY: extern "C" fn(
|
| 122 |
+
crate::os::raw::c_int,
|
| 123 |
+
*const *const u8,
|
| 124 |
+
*const *const u8,
|
| 125 |
+
) = {
|
| 126 |
+
extern "C" fn init_wrapper(
|
| 127 |
+
argc: crate::os::raw::c_int,
|
| 128 |
+
argv: *const *const u8,
|
| 129 |
+
_envp: *const *const u8,
|
| 130 |
+
) {
|
| 131 |
+
unsafe { really_init(argc as isize, argv) };
|
| 132 |
+
}
|
| 133 |
+
init_wrapper
|
| 134 |
+
};
|
| 135 |
+
|
| 136 |
+
pub fn argc_argv() -> (isize, *const *const c_char) {
|
| 137 |
+
// Load ARGC and ARGV, which hold the unmodified system-provided
|
| 138 |
+
// argc/argv, so we can read the pointed-to memory without atomics or
|
| 139 |
+
// synchronization.
|
| 140 |
+
//
|
| 141 |
+
// If either ARGC or ARGV is still zero or null, then either there
|
| 142 |
+
// really are no arguments, or someone is asking for `args()` before
|
| 143 |
+
// initialization has completed, and we return an empty list.
|
| 144 |
+
let argv = ARGV.load(Ordering::Relaxed);
|
| 145 |
+
let argc = if argv.is_null() { 0 } else { ARGC.load(Ordering::Relaxed) };
|
| 146 |
+
|
| 147 |
+
// Cast from `*mut *const u8` to `*const *const c_char`
|
| 148 |
+
(argc, argv.cast())
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
// Use `_NSGetArgc` and `_NSGetArgv` on Apple platforms.
|
| 153 |
+
//
|
| 154 |
+
// Even though these have underscores in their names, they've been available
|
| 155 |
+
// since the first versions of both macOS and iOS, and are declared in
|
| 156 |
+
// the header `crt_externs.h`.
|
| 157 |
+
//
|
| 158 |
+
// NOTE: This header was added to the iOS 13.0 SDK, which has been the source
|
| 159 |
+
// of a great deal of confusion in the past about the availability of these
|
| 160 |
+
// APIs.
|
| 161 |
+
//
|
| 162 |
+
// NOTE(madsmtm): This has not strictly been verified to not cause App Store
|
| 163 |
+
// rejections; if this is found to be the case, the previous implementation
|
| 164 |
+
// of this used `[[NSProcessInfo processInfo] arguments]`.
|
| 165 |
+
#[cfg(target_vendor = "apple")]
|
| 166 |
+
mod imp {
|
| 167 |
+
use crate::ffi::c_char;
|
| 168 |
+
|
| 169 |
+
pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
|
| 170 |
+
// No need to initialize anything in here, `libdyld.dylib` has already
|
| 171 |
+
// done the work for us.
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
pub fn argc_argv() -> (isize, *const *const c_char) {
|
| 175 |
+
// SAFETY: The returned pointer points to a static initialized early
|
| 176 |
+
// in the program lifetime by `libdyld.dylib`, and as such is always
|
| 177 |
+
// valid.
|
| 178 |
+
//
|
| 179 |
+
// NOTE: Similar to `_NSGetEnviron`, there technically isn't anything
|
| 180 |
+
// protecting us against concurrent modifications to this, and there
|
| 181 |
+
// doesn't exist a lock that we can take. Instead, it is generally
|
| 182 |
+
// expected that it's only modified in `main` / before other code
|
| 183 |
+
// runs, so reading this here should be fine.
|
| 184 |
+
let argc = unsafe { libc::_NSGetArgc().read() };
|
| 185 |
+
// SAFETY: Same as above.
|
| 186 |
+
let argv = unsafe { libc::_NSGetArgv().read() };
|
| 187 |
+
|
| 188 |
+
// Cast from `*mut *mut c_char` to `*const *const c_char`
|
| 189 |
+
(argc as isize, argv.cast())
|
| 190 |
+
}
|
| 191 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/unsupported.rs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::ffi::OsString;
|
| 2 |
+
use crate::fmt;
|
| 3 |
+
|
| 4 |
+
pub struct Args {}
|
| 5 |
+
|
| 6 |
+
pub fn args() -> Args {
|
| 7 |
+
Args {}
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
impl fmt::Debug for Args {
|
| 11 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 12 |
+
f.debug_list().finish()
|
| 13 |
+
}
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
impl Iterator for Args {
|
| 17 |
+
type Item = OsString;
|
| 18 |
+
|
| 19 |
+
#[inline]
|
| 20 |
+
fn next(&mut self) -> Option<OsString> {
|
| 21 |
+
None
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
#[inline]
|
| 25 |
+
fn size_hint(&self) -> (usize, Option<usize>) {
|
| 26 |
+
(0, Some(0))
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
impl DoubleEndedIterator for Args {
|
| 31 |
+
#[inline]
|
| 32 |
+
fn next_back(&mut self) -> Option<OsString> {
|
| 33 |
+
None
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
impl ExactSizeIterator for Args {
|
| 38 |
+
#[inline]
|
| 39 |
+
fn len(&self) -> usize {
|
| 40 |
+
0
|
| 41 |
+
}
|
| 42 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/wasip1.rs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#![forbid(unsafe_op_in_unsafe_fn)]
|
| 2 |
+
|
| 3 |
+
pub use super::common::Args;
|
| 4 |
+
use crate::ffi::{CStr, OsStr, OsString};
|
| 5 |
+
use crate::os::wasi::ffi::OsStrExt;
|
| 6 |
+
|
| 7 |
+
/// Returns the command line arguments
|
| 8 |
+
pub fn args() -> Args {
|
| 9 |
+
Args::new(maybe_args().unwrap_or(Vec::new()))
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
fn maybe_args() -> Option<Vec<OsString>> {
|
| 13 |
+
unsafe {
|
| 14 |
+
let (argc, buf_size) = wasi::args_sizes_get().ok()?;
|
| 15 |
+
let mut argv = Vec::with_capacity(argc);
|
| 16 |
+
let mut buf = Vec::with_capacity(buf_size);
|
| 17 |
+
wasi::args_get(argv.as_mut_ptr(), buf.as_mut_ptr()).ok()?;
|
| 18 |
+
argv.set_len(argc);
|
| 19 |
+
let mut ret = Vec::with_capacity(argc);
|
| 20 |
+
for ptr in argv {
|
| 21 |
+
let s = CStr::from_ptr(ptr.cast());
|
| 22 |
+
ret.push(OsStr::from_bytes(s.to_bytes()).to_owned());
|
| 23 |
+
}
|
| 24 |
+
Some(ret)
|
| 25 |
+
}
|
| 26 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/wasip2.rs
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pub use super::common::Args;
|
| 2 |
+
|
| 3 |
+
/// Returns the command line arguments
|
| 4 |
+
pub fn args() -> Args {
|
| 5 |
+
Args::new(wasip2::cli::environment::get_arguments().into_iter().map(|arg| arg.into()).collect())
|
| 6 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/windows.rs
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! The Windows command line is just a string
|
| 2 |
+
//! <https://docs.microsoft.com/en-us/archive/blogs/larryosterman/the-windows-command-line-is-just-a-string>
|
| 3 |
+
//!
|
| 4 |
+
//! This module implements the parsing necessary to turn that string into a list of arguments.
|
| 5 |
+
|
| 6 |
+
#[cfg(test)]
|
| 7 |
+
mod tests;
|
| 8 |
+
|
| 9 |
+
pub use super::common::Args;
|
| 10 |
+
use crate::ffi::{OsStr, OsString};
|
| 11 |
+
use crate::num::NonZero;
|
| 12 |
+
use crate::os::windows::prelude::*;
|
| 13 |
+
use crate::path::{Path, PathBuf};
|
| 14 |
+
use crate::sys::helpers::WStrUnits;
|
| 15 |
+
use crate::sys::pal::os::current_exe;
|
| 16 |
+
use crate::sys::pal::{ensure_no_nuls, fill_utf16_buf};
|
| 17 |
+
use crate::sys::path::get_long_path;
|
| 18 |
+
use crate::sys::{AsInner, c, to_u16s};
|
| 19 |
+
use crate::{io, iter, ptr};
|
| 20 |
+
|
| 21 |
+
pub fn args() -> Args {
|
| 22 |
+
// SAFETY: `GetCommandLineW` returns a pointer to a null terminated UTF-16
|
| 23 |
+
// string so it's safe for `WStrUnits` to use.
|
| 24 |
+
unsafe {
|
| 25 |
+
let lp_cmd_line = c::GetCommandLineW();
|
| 26 |
+
let parsed_args_list = parse_lp_cmd_line(WStrUnits::new(lp_cmd_line), || {
|
| 27 |
+
current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new())
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
Args::new(parsed_args_list)
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
/// Implements the Windows command-line argument parsing algorithm.
|
| 35 |
+
///
|
| 36 |
+
/// Microsoft's documentation for the Windows CLI argument format can be found at
|
| 37 |
+
/// <https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-160#parsing-c-command-line-arguments>
|
| 38 |
+
///
|
| 39 |
+
/// A more in-depth explanation is here:
|
| 40 |
+
/// <https://daviddeley.com/autohotkey/parameters/parameters.htm#WIN>
|
| 41 |
+
///
|
| 42 |
+
/// Windows includes a function to do command line parsing in shell32.dll.
|
| 43 |
+
/// However, this is not used for two reasons:
|
| 44 |
+
///
|
| 45 |
+
/// 1. Linking with that DLL causes the process to be registered as a GUI application.
|
| 46 |
+
/// GUI applications add a bunch of overhead, even if no windows are drawn. See
|
| 47 |
+
/// <https://randomascii.wordpress.com/2018/12/03/a-not-called-function-can-cause-a-5x-slowdown/>.
|
| 48 |
+
///
|
| 49 |
+
/// 2. It does not follow the modern C/C++ argv rules outlined in the first two links above.
|
| 50 |
+
///
|
| 51 |
+
/// This function was tested for equivalence to the C/C++ parsing rules using an
|
| 52 |
+
/// extensive test suite available at
|
| 53 |
+
/// <https://github.com/ChrisDenton/winarg/tree/std>.
|
| 54 |
+
fn parse_lp_cmd_line<'a, F: Fn() -> OsString>(
|
| 55 |
+
lp_cmd_line: Option<WStrUnits<'a>>,
|
| 56 |
+
exe_name: F,
|
| 57 |
+
) -> Vec<OsString> {
|
| 58 |
+
const BACKSLASH: NonZero<u16> = NonZero::new(b'\\' as u16).unwrap();
|
| 59 |
+
const QUOTE: NonZero<u16> = NonZero::new(b'"' as u16).unwrap();
|
| 60 |
+
const TAB: NonZero<u16> = NonZero::new(b'\t' as u16).unwrap();
|
| 61 |
+
const SPACE: NonZero<u16> = NonZero::new(b' ' as u16).unwrap();
|
| 62 |
+
|
| 63 |
+
let mut ret_val = Vec::new();
|
| 64 |
+
// If the cmd line pointer is null or it points to an empty string then
|
| 65 |
+
// return the name of the executable as argv[0].
|
| 66 |
+
if lp_cmd_line.as_ref().and_then(|cmd| cmd.peek()).is_none() {
|
| 67 |
+
ret_val.push(exe_name());
|
| 68 |
+
return ret_val;
|
| 69 |
+
}
|
| 70 |
+
let mut code_units = lp_cmd_line.unwrap();
|
| 71 |
+
|
| 72 |
+
// The executable name at the beginning is special.
|
| 73 |
+
let mut in_quotes = false;
|
| 74 |
+
let mut cur = Vec::new();
|
| 75 |
+
for w in &mut code_units {
|
| 76 |
+
match w {
|
| 77 |
+
// A quote mark always toggles `in_quotes` no matter what because
|
| 78 |
+
// there are no escape characters when parsing the executable name.
|
| 79 |
+
QUOTE => in_quotes = !in_quotes,
|
| 80 |
+
// If not `in_quotes` then whitespace ends argv[0].
|
| 81 |
+
SPACE | TAB if !in_quotes => break,
|
| 82 |
+
// In all other cases the code unit is taken literally.
|
| 83 |
+
_ => cur.push(w.get()),
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
// Skip whitespace.
|
| 87 |
+
code_units.advance_while(|w| w == SPACE || w == TAB);
|
| 88 |
+
ret_val.push(OsString::from_wide(&cur));
|
| 89 |
+
|
| 90 |
+
// Parse the arguments according to these rules:
|
| 91 |
+
// * All code units are taken literally except space, tab, quote and backslash.
|
| 92 |
+
// * When not `in_quotes`, space and tab separate arguments. Consecutive spaces and tabs are
|
| 93 |
+
// treated as a single separator.
|
| 94 |
+
// * A space or tab `in_quotes` is taken literally.
|
| 95 |
+
// * A quote toggles `in_quotes` mode unless it's escaped. An escaped quote is taken literally.
|
| 96 |
+
// * A quote can be escaped if preceded by an odd number of backslashes.
|
| 97 |
+
// * If any number of backslashes is immediately followed by a quote then the number of
|
| 98 |
+
// backslashes is halved (rounding down).
|
| 99 |
+
// * Backslashes not followed by a quote are all taken literally.
|
| 100 |
+
// * If `in_quotes` then a quote can also be escaped using another quote
|
| 101 |
+
// (i.e. two consecutive quotes become one literal quote).
|
| 102 |
+
let mut cur = Vec::new();
|
| 103 |
+
let mut in_quotes = false;
|
| 104 |
+
while let Some(w) = code_units.next() {
|
| 105 |
+
match w {
|
| 106 |
+
// If not `in_quotes`, a space or tab ends the argument.
|
| 107 |
+
SPACE | TAB if !in_quotes => {
|
| 108 |
+
ret_val.push(OsString::from_wide(&cur[..]));
|
| 109 |
+
cur.truncate(0);
|
| 110 |
+
|
| 111 |
+
// Skip whitespace.
|
| 112 |
+
code_units.advance_while(|w| w == SPACE || w == TAB);
|
| 113 |
+
}
|
| 114 |
+
// Backslashes can escape quotes or backslashes but only if consecutive backslashes are followed by a quote.
|
| 115 |
+
BACKSLASH => {
|
| 116 |
+
let backslash_count = code_units.advance_while(|w| w == BACKSLASH) + 1;
|
| 117 |
+
if code_units.peek() == Some(QUOTE) {
|
| 118 |
+
cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count / 2));
|
| 119 |
+
// The quote is escaped if there are an odd number of backslashes.
|
| 120 |
+
if backslash_count % 2 == 1 {
|
| 121 |
+
code_units.next();
|
| 122 |
+
cur.push(QUOTE.get());
|
| 123 |
+
}
|
| 124 |
+
} else {
|
| 125 |
+
// If there is no quote on the end then there is no escaping.
|
| 126 |
+
cur.extend(iter::repeat(BACKSLASH.get()).take(backslash_count));
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
// If `in_quotes` and not backslash escaped (see above) then a quote either
|
| 130 |
+
// unsets `in_quote` or is escaped by another quote.
|
| 131 |
+
QUOTE if in_quotes => match code_units.peek() {
|
| 132 |
+
// Two consecutive quotes when `in_quotes` produces one literal quote.
|
| 133 |
+
Some(QUOTE) => {
|
| 134 |
+
cur.push(QUOTE.get());
|
| 135 |
+
code_units.next();
|
| 136 |
+
}
|
| 137 |
+
// Otherwise set `in_quotes`.
|
| 138 |
+
Some(_) => in_quotes = false,
|
| 139 |
+
// The end of the command line.
|
| 140 |
+
// Push `cur` even if empty, which we do by breaking while `in_quotes` is still set.
|
| 141 |
+
None => break,
|
| 142 |
+
},
|
| 143 |
+
// If not `in_quotes` and not BACKSLASH escaped (see above) then a quote sets `in_quote`.
|
| 144 |
+
QUOTE => in_quotes = true,
|
| 145 |
+
// Everything else is always taken literally.
|
| 146 |
+
_ => cur.push(w.get()),
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
// Push the final argument, if any.
|
| 150 |
+
if !cur.is_empty() || in_quotes {
|
| 151 |
+
ret_val.push(OsString::from_wide(&cur[..]));
|
| 152 |
+
}
|
| 153 |
+
ret_val
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
#[derive(Debug)]
|
| 157 |
+
pub(crate) enum Arg {
|
| 158 |
+
/// Add quotes (if needed)
|
| 159 |
+
Regular(OsString),
|
| 160 |
+
/// Append raw string without quoting
|
| 161 |
+
Raw(OsString),
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
enum Quote {
|
| 165 |
+
// Every arg is quoted
|
| 166 |
+
Always,
|
| 167 |
+
// Whitespace and empty args are quoted
|
| 168 |
+
Auto,
|
| 169 |
+
// Arg appended without any changes (#29494)
|
| 170 |
+
Never,
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
pub(crate) fn append_arg(cmd: &mut Vec<u16>, arg: &Arg, force_quotes: bool) -> io::Result<()> {
|
| 174 |
+
let (arg, quote) = match arg {
|
| 175 |
+
Arg::Regular(arg) => (arg, if force_quotes { Quote::Always } else { Quote::Auto }),
|
| 176 |
+
Arg::Raw(arg) => (arg, Quote::Never),
|
| 177 |
+
};
|
| 178 |
+
|
| 179 |
+
// If an argument has 0 characters then we need to quote it to ensure
|
| 180 |
+
// that it actually gets passed through on the command line or otherwise
|
| 181 |
+
// it will be dropped entirely when parsed on the other end.
|
| 182 |
+
ensure_no_nuls(arg)?;
|
| 183 |
+
let arg_bytes = arg.as_encoded_bytes();
|
| 184 |
+
let (quote, escape) = match quote {
|
| 185 |
+
Quote::Always => (true, true),
|
| 186 |
+
Quote::Auto => {
|
| 187 |
+
(arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t') || arg_bytes.is_empty(), true)
|
| 188 |
+
}
|
| 189 |
+
Quote::Never => (false, false),
|
| 190 |
+
};
|
| 191 |
+
if quote {
|
| 192 |
+
cmd.push('"' as u16);
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
let mut backslashes: usize = 0;
|
| 196 |
+
for x in arg.encode_wide() {
|
| 197 |
+
if escape {
|
| 198 |
+
if x == '\\' as u16 {
|
| 199 |
+
backslashes += 1;
|
| 200 |
+
} else {
|
| 201 |
+
if x == '"' as u16 {
|
| 202 |
+
// Add n+1 backslashes to total 2n+1 before internal '"'.
|
| 203 |
+
cmd.extend((0..=backslashes).map(|_| '\\' as u16));
|
| 204 |
+
}
|
| 205 |
+
backslashes = 0;
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
cmd.push(x);
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
if quote {
|
| 212 |
+
// Add n backslashes to total 2n before ending '"'.
|
| 213 |
+
cmd.extend((0..backslashes).map(|_| '\\' as u16));
|
| 214 |
+
cmd.push('"' as u16);
|
| 215 |
+
}
|
| 216 |
+
Ok(())
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
fn append_bat_arg(cmd: &mut Vec<u16>, arg: &OsStr, mut quote: bool) -> io::Result<()> {
|
| 220 |
+
ensure_no_nuls(arg)?;
|
| 221 |
+
// If an argument has 0 characters then we need to quote it to ensure
|
| 222 |
+
// that it actually gets passed through on the command line or otherwise
|
| 223 |
+
// it will be dropped entirely when parsed on the other end.
|
| 224 |
+
//
|
| 225 |
+
// We also need to quote the argument if it ends with `\` to guard against
|
| 226 |
+
// bat usage such as `"%~2"` (i.e. force quote arguments) otherwise a
|
| 227 |
+
// trailing slash will escape the closing quote.
|
| 228 |
+
if arg.is_empty() || arg.as_encoded_bytes().last() == Some(&b'\\') {
|
| 229 |
+
quote = true;
|
| 230 |
+
}
|
| 231 |
+
for cp in arg.as_inner().inner.code_points() {
|
| 232 |
+
if let Some(cp) = cp.to_char() {
|
| 233 |
+
// Rather than trying to find every ascii symbol that must be quoted,
|
| 234 |
+
// we assume that all ascii symbols must be quoted unless they're known to be good.
|
| 235 |
+
// We also quote Unicode control blocks for good measure.
|
| 236 |
+
// Note an unquoted `\` is fine so long as the argument isn't otherwise quoted.
|
| 237 |
+
static UNQUOTED: &str = r"#$*+-./:?@\_";
|
| 238 |
+
let ascii_needs_quotes =
|
| 239 |
+
cp.is_ascii() && !(cp.is_ascii_alphanumeric() || UNQUOTED.contains(cp));
|
| 240 |
+
if ascii_needs_quotes || cp.is_control() {
|
| 241 |
+
quote = true;
|
| 242 |
+
}
|
| 243 |
+
}
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
if quote {
|
| 247 |
+
cmd.push('"' as u16);
|
| 248 |
+
}
|
| 249 |
+
// Loop through the string, escaping `\` only if followed by `"`.
|
| 250 |
+
// And escaping `"` by doubling them.
|
| 251 |
+
let mut backslashes: usize = 0;
|
| 252 |
+
for x in arg.encode_wide() {
|
| 253 |
+
if x == '\\' as u16 {
|
| 254 |
+
backslashes += 1;
|
| 255 |
+
} else {
|
| 256 |
+
if x == '"' as u16 {
|
| 257 |
+
// Add n backslashes to total 2n before internal `"`.
|
| 258 |
+
cmd.extend((0..backslashes).map(|_| '\\' as u16));
|
| 259 |
+
// Appending an additional double-quote acts as an escape.
|
| 260 |
+
cmd.push(b'"' as u16)
|
| 261 |
+
} else if x == '%' as u16 || x == '\r' as u16 {
|
| 262 |
+
// yt-dlp hack: replaces `%` with `%%cd:~,%` to stop %VAR% being expanded as an environment variable.
|
| 263 |
+
//
|
| 264 |
+
// # Explanation
|
| 265 |
+
//
|
| 266 |
+
// cmd supports extracting a substring from a variable using the following syntax:
|
| 267 |
+
// %variable:~start_index,end_index%
|
| 268 |
+
//
|
| 269 |
+
// In the above command `cd` is used as the variable and the start_index and end_index are left blank.
|
| 270 |
+
// `cd` is a built-in variable that dynamically expands to the current directory so it's always available.
|
| 271 |
+
// Explicitly omitting both the start and end index creates a zero-length substring.
|
| 272 |
+
//
|
| 273 |
+
// Therefore it all resolves to nothing. However, by doing this no-op we distract cmd.exe
|
| 274 |
+
// from potentially expanding %variables% in the argument.
|
| 275 |
+
cmd.extend_from_slice(&[
|
| 276 |
+
'%' as u16, '%' as u16, 'c' as u16, 'd' as u16, ':' as u16, '~' as u16,
|
| 277 |
+
',' as u16,
|
| 278 |
+
]);
|
| 279 |
+
}
|
| 280 |
+
backslashes = 0;
|
| 281 |
+
}
|
| 282 |
+
cmd.push(x);
|
| 283 |
+
}
|
| 284 |
+
if quote {
|
| 285 |
+
// Add n backslashes to total 2n before ending `"`.
|
| 286 |
+
cmd.extend((0..backslashes).map(|_| '\\' as u16));
|
| 287 |
+
cmd.push('"' as u16);
|
| 288 |
+
}
|
| 289 |
+
Ok(())
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
pub(crate) fn make_bat_command_line(
|
| 293 |
+
script: &[u16],
|
| 294 |
+
args: &[Arg],
|
| 295 |
+
force_quotes: bool,
|
| 296 |
+
) -> io::Result<Vec<u16>> {
|
| 297 |
+
const INVALID_ARGUMENT_ERROR: io::Error =
|
| 298 |
+
io::const_error!(io::ErrorKind::InvalidInput, r#"batch file arguments are invalid"#);
|
| 299 |
+
// Set the start of the command line to `cmd.exe /c "`
|
| 300 |
+
// It is necessary to surround the command in an extra pair of quotes,
|
| 301 |
+
// hence the trailing quote here. It will be closed after all arguments
|
| 302 |
+
// have been added.
|
| 303 |
+
// Using /e:ON enables "command extensions" which is essential for the `%` hack to work.
|
| 304 |
+
let mut cmd: Vec<u16> = "cmd.exe /e:ON /v:OFF /d /c \"".encode_utf16().collect();
|
| 305 |
+
|
| 306 |
+
// Push the script name surrounded by its quote pair.
|
| 307 |
+
cmd.push(b'"' as u16);
|
| 308 |
+
// Windows file names cannot contain a `"` character or end with `\\`.
|
| 309 |
+
// If the script name does then return an error.
|
| 310 |
+
if script.contains(&(b'"' as u16)) || script.last() == Some(&(b'\\' as u16)) {
|
| 311 |
+
return Err(io::const_error!(
|
| 312 |
+
io::ErrorKind::InvalidInput,
|
| 313 |
+
"Windows file names may not contain `\"` or end with `\\`"
|
| 314 |
+
));
|
| 315 |
+
}
|
| 316 |
+
cmd.extend_from_slice(script.strip_suffix(&[0]).unwrap_or(script));
|
| 317 |
+
cmd.push(b'"' as u16);
|
| 318 |
+
|
| 319 |
+
// Append the arguments.
|
| 320 |
+
// FIXME: This needs tests to ensure that the arguments are properly
|
| 321 |
+
// reconstructed by the batch script by default.
|
| 322 |
+
for arg in args {
|
| 323 |
+
cmd.push(' ' as u16);
|
| 324 |
+
match arg {
|
| 325 |
+
Arg::Regular(arg_os) => {
|
| 326 |
+
let arg_bytes = arg_os.as_encoded_bytes();
|
| 327 |
+
// Disallow \r and \n as they may truncate the arguments.
|
| 328 |
+
const DISALLOWED: &[u8] = b"\r\n";
|
| 329 |
+
if arg_bytes.iter().any(|c| DISALLOWED.contains(c)) {
|
| 330 |
+
return Err(INVALID_ARGUMENT_ERROR);
|
| 331 |
+
}
|
| 332 |
+
append_bat_arg(&mut cmd, arg_os, force_quotes)?;
|
| 333 |
+
}
|
| 334 |
+
_ => {
|
| 335 |
+
// Raw arguments are passed on as-is.
|
| 336 |
+
// It's the user's responsibility to properly handle arguments in this case.
|
| 337 |
+
append_arg(&mut cmd, arg, force_quotes)?;
|
| 338 |
+
}
|
| 339 |
+
};
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
// Close the quote we left opened earlier.
|
| 343 |
+
cmd.push(b'"' as u16);
|
| 344 |
+
|
| 345 |
+
Ok(cmd)
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
/// Takes a path and tries to return a non-verbatim path.
|
| 349 |
+
///
|
| 350 |
+
/// This is necessary because cmd.exe does not support verbatim paths.
|
| 351 |
+
pub(crate) fn to_user_path(path: &Path) -> io::Result<Vec<u16>> {
|
| 352 |
+
from_wide_to_user_path(to_u16s(path)?)
|
| 353 |
+
}
|
| 354 |
+
pub(crate) fn from_wide_to_user_path(mut path: Vec<u16>) -> io::Result<Vec<u16>> {
|
| 355 |
+
// UTF-16 encoded code points, used in parsing and building UTF-16 paths.
|
| 356 |
+
// All of these are in the ASCII range so they can be cast directly to `u16`.
|
| 357 |
+
const SEP: u16 = b'\\' as _;
|
| 358 |
+
const QUERY: u16 = b'?' as _;
|
| 359 |
+
const COLON: u16 = b':' as _;
|
| 360 |
+
const U: u16 = b'U' as _;
|
| 361 |
+
const N: u16 = b'N' as _;
|
| 362 |
+
const C: u16 = b'C' as _;
|
| 363 |
+
|
| 364 |
+
// Early return if the path is too long to remove the verbatim prefix.
|
| 365 |
+
const LEGACY_MAX_PATH: usize = 260;
|
| 366 |
+
if path.len() > LEGACY_MAX_PATH {
|
| 367 |
+
return Ok(path);
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
match &path[..] {
|
| 371 |
+
// `\\?\C:\...` => `C:\...`
|
| 372 |
+
[SEP, SEP, QUERY, SEP, _, COLON, SEP, ..] => unsafe {
|
| 373 |
+
let lpfilename = path[4..].as_ptr();
|
| 374 |
+
fill_utf16_buf(
|
| 375 |
+
|buffer, size| c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut()),
|
| 376 |
+
|full_path: &[u16]| {
|
| 377 |
+
if full_path == &path[4..path.len() - 1] {
|
| 378 |
+
let mut path: Vec<u16> = full_path.into();
|
| 379 |
+
path.push(0);
|
| 380 |
+
path
|
| 381 |
+
} else {
|
| 382 |
+
path
|
| 383 |
+
}
|
| 384 |
+
},
|
| 385 |
+
)
|
| 386 |
+
},
|
| 387 |
+
// `\\?\UNC\...` => `\\...`
|
| 388 |
+
[SEP, SEP, QUERY, SEP, U, N, C, SEP, ..] => unsafe {
|
| 389 |
+
// Change the `C` in `UNC\` to `\` so we can get a slice that starts with `\\`.
|
| 390 |
+
path[6] = b'\\' as u16;
|
| 391 |
+
let lpfilename = path[6..].as_ptr();
|
| 392 |
+
fill_utf16_buf(
|
| 393 |
+
|buffer, size| c::GetFullPathNameW(lpfilename, size, buffer, ptr::null_mut()),
|
| 394 |
+
|full_path: &[u16]| {
|
| 395 |
+
if full_path == &path[6..path.len() - 1] {
|
| 396 |
+
let mut path: Vec<u16> = full_path.into();
|
| 397 |
+
path.push(0);
|
| 398 |
+
path
|
| 399 |
+
} else {
|
| 400 |
+
// Restore the 'C' in "UNC".
|
| 401 |
+
path[6] = b'C' as u16;
|
| 402 |
+
path
|
| 403 |
+
}
|
| 404 |
+
},
|
| 405 |
+
)
|
| 406 |
+
},
|
| 407 |
+
// For everything else, leave the path unchanged.
|
| 408 |
+
_ => get_long_path(path, false),
|
| 409 |
+
}
|
| 410 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/xous.rs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pub use super::common::Args;
|
| 2 |
+
use crate::sys::pal::os::get_application_parameters;
|
| 3 |
+
use crate::sys::pal::os::params::ArgumentList;
|
| 4 |
+
|
| 5 |
+
pub fn args() -> Args {
|
| 6 |
+
let Some(params) = get_application_parameters() else {
|
| 7 |
+
return Args::new(vec![]);
|
| 8 |
+
};
|
| 9 |
+
|
| 10 |
+
for param in params {
|
| 11 |
+
if let Ok(args) = ArgumentList::try_from(¶m) {
|
| 12 |
+
let mut parsed_args = vec![];
|
| 13 |
+
for arg in args {
|
| 14 |
+
parsed_args.push(arg.into());
|
| 15 |
+
}
|
| 16 |
+
return Args::new(parsed_args);
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
Args::new(vec![])
|
| 20 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/args/zkvm.rs
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::ffi::{OsStr, OsString};
|
| 2 |
+
use crate::num::NonZero;
|
| 3 |
+
use crate::sync::OnceLock;
|
| 4 |
+
use crate::sys::pal::{WORD_SIZE, abi};
|
| 5 |
+
use crate::{fmt, ptr, slice};
|
| 6 |
+
|
| 7 |
+
pub fn args() -> Args {
|
| 8 |
+
Args { iter: ARGS.get_or_init(|| get_args()).iter() }
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
fn get_args() -> Vec<&'static OsStr> {
|
| 12 |
+
let argc = unsafe { abi::sys_argc() };
|
| 13 |
+
let mut args = Vec::with_capacity(argc);
|
| 14 |
+
|
| 15 |
+
for i in 0..argc {
|
| 16 |
+
// Get the size of the argument then the data.
|
| 17 |
+
let arg_len = unsafe { abi::sys_argv(ptr::null_mut(), 0, i) };
|
| 18 |
+
|
| 19 |
+
let arg_len_words = (arg_len + WORD_SIZE - 1) / WORD_SIZE;
|
| 20 |
+
let words = unsafe { abi::sys_alloc_words(arg_len_words) };
|
| 21 |
+
|
| 22 |
+
let arg_len2 = unsafe { abi::sys_argv(words, arg_len_words, i) };
|
| 23 |
+
debug_assert_eq!(arg_len, arg_len2);
|
| 24 |
+
|
| 25 |
+
let arg_bytes = unsafe { slice::from_raw_parts(words.cast(), arg_len) };
|
| 26 |
+
args.push(unsafe { OsStr::from_encoded_bytes_unchecked(arg_bytes) });
|
| 27 |
+
}
|
| 28 |
+
args
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
static ARGS: OnceLock<Vec<&'static OsStr>> = OnceLock::new();
|
| 32 |
+
|
| 33 |
+
pub struct Args {
|
| 34 |
+
iter: slice::Iter<'static, &'static OsStr>,
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
impl !Send for Args {}
|
| 38 |
+
impl !Sync for Args {}
|
| 39 |
+
|
| 40 |
+
impl fmt::Debug for Args {
|
| 41 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 42 |
+
self.iter.as_slice().fmt(f)
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
impl Iterator for Args {
|
| 47 |
+
type Item = OsString;
|
| 48 |
+
|
| 49 |
+
fn next(&mut self) -> Option<OsString> {
|
| 50 |
+
self.iter.next().map(|arg| arg.to_os_string())
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
#[inline]
|
| 54 |
+
fn size_hint(&self) -> (usize, Option<usize>) {
|
| 55 |
+
self.iter.size_hint()
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
#[inline]
|
| 59 |
+
fn count(self) -> usize {
|
| 60 |
+
self.iter.len()
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
fn last(self) -> Option<OsString> {
|
| 64 |
+
self.iter.last().map(|arg| arg.to_os_string())
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
#[inline]
|
| 68 |
+
fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
|
| 69 |
+
self.iter.advance_by(n)
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
impl DoubleEndedIterator for Args {
|
| 74 |
+
fn next_back(&mut self) -> Option<OsString> {
|
| 75 |
+
self.iter.next_back().map(|arg| arg.to_os_string())
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
#[inline]
|
| 79 |
+
fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
|
| 80 |
+
self.iter.advance_back_by(n)
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
impl ExactSizeIterator for Args {
|
| 85 |
+
#[inline]
|
| 86 |
+
fn len(&self) -> usize {
|
| 87 |
+
self.iter.len()
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
#[inline]
|
| 91 |
+
fn is_empty(&self) -> bool {
|
| 92 |
+
self.iter.is_empty()
|
| 93 |
+
}
|
| 94 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/backtrace.rs
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Common code for printing backtraces.
|
| 2 |
+
#![forbid(unsafe_op_in_unsafe_fn)]
|
| 3 |
+
|
| 4 |
+
use crate::backtrace_rs::{self, BacktraceFmt, BytesOrWideString, PrintFmt};
|
| 5 |
+
use crate::borrow::Cow;
|
| 6 |
+
use crate::io::prelude::*;
|
| 7 |
+
use crate::path::{self, Path, PathBuf};
|
| 8 |
+
use crate::sync::{Mutex, MutexGuard, PoisonError};
|
| 9 |
+
use crate::{env, fmt, io};
|
| 10 |
+
|
| 11 |
+
/// Max number of frames to print.
|
| 12 |
+
const MAX_NB_FRAMES: usize = 100;
|
| 13 |
+
|
| 14 |
+
pub(crate) const FULL_BACKTRACE_DEFAULT: bool = cfg_select! {
|
| 15 |
+
// Fuchsia components default to full backtrace.
|
| 16 |
+
target_os = "fuchsia" => true,
|
| 17 |
+
_ => false,
|
| 18 |
+
};
|
| 19 |
+
|
| 20 |
+
pub(crate) struct BacktraceLock<'a>(#[allow(dead_code)] MutexGuard<'a, ()>);
|
| 21 |
+
|
| 22 |
+
pub(crate) fn lock<'a>() -> BacktraceLock<'a> {
|
| 23 |
+
static LOCK: Mutex<()> = Mutex::new(());
|
| 24 |
+
BacktraceLock(LOCK.lock().unwrap_or_else(PoisonError::into_inner))
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
impl BacktraceLock<'_> {
|
| 28 |
+
/// Prints the current backtrace.
|
| 29 |
+
pub(crate) fn print(&mut self, w: &mut dyn Write, format: PrintFmt) -> io::Result<()> {
|
| 30 |
+
// There are issues currently linking libbacktrace into tests, and in
|
| 31 |
+
// general during std's own unit tests we're not testing this path. In
|
| 32 |
+
// test mode immediately return here to optimize away any references to the
|
| 33 |
+
// libbacktrace symbols
|
| 34 |
+
if cfg!(test) {
|
| 35 |
+
return Ok(());
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
struct DisplayBacktrace {
|
| 39 |
+
format: PrintFmt,
|
| 40 |
+
}
|
| 41 |
+
impl fmt::Display for DisplayBacktrace {
|
| 42 |
+
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 43 |
+
// SAFETY: the backtrace lock is held
|
| 44 |
+
unsafe { _print_fmt(fmt, self.format) }
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
write!(w, "{}", DisplayBacktrace { format })
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
/// # Safety
|
| 52 |
+
///
|
| 53 |
+
/// This function is not Sync. The caller must hold a mutex lock, or there must be only one thread in the program.
|
| 54 |
+
unsafe fn _print_fmt(fmt: &mut fmt::Formatter<'_>, print_fmt: PrintFmt) -> fmt::Result {
|
| 55 |
+
// Always 'fail' to get the cwd when running under Miri -
|
| 56 |
+
// this allows Miri to display backtraces in isolation mode
|
| 57 |
+
let cwd = if !cfg!(miri) { env::current_dir().ok() } else { None };
|
| 58 |
+
|
| 59 |
+
let mut print_path = move |fmt: &mut fmt::Formatter<'_>, bows: BytesOrWideString<'_>| {
|
| 60 |
+
output_filename(fmt, bows, print_fmt, cwd.as_ref())
|
| 61 |
+
};
|
| 62 |
+
writeln!(fmt, "stack backtrace:")?;
|
| 63 |
+
let mut bt_fmt = BacktraceFmt::new(fmt, print_fmt, &mut print_path);
|
| 64 |
+
bt_fmt.add_context()?;
|
| 65 |
+
let mut idx = 0;
|
| 66 |
+
let mut res = Ok(());
|
| 67 |
+
let mut omitted_count: usize = 0;
|
| 68 |
+
let mut first_omit = true;
|
| 69 |
+
// If we're using a short backtrace, ignore all frames until we're told to start printing.
|
| 70 |
+
let mut print = print_fmt != PrintFmt::Short;
|
| 71 |
+
set_image_base();
|
| 72 |
+
// SAFETY: we roll our own locking in this town
|
| 73 |
+
unsafe {
|
| 74 |
+
backtrace_rs::trace_unsynchronized(|frame| {
|
| 75 |
+
if print_fmt == PrintFmt::Short && idx > MAX_NB_FRAMES {
|
| 76 |
+
return false;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
if cfg!(feature = "backtrace-trace-only") {
|
| 80 |
+
const HEX_WIDTH: usize = 2 + 2 * size_of::<usize>();
|
| 81 |
+
let frame_ip = frame.ip();
|
| 82 |
+
res = writeln!(bt_fmt.formatter(), "{idx:4}: {frame_ip:HEX_WIDTH$?}");
|
| 83 |
+
} else {
|
| 84 |
+
let mut hit = false;
|
| 85 |
+
backtrace_rs::resolve_frame_unsynchronized(frame, |symbol| {
|
| 86 |
+
hit = true;
|
| 87 |
+
|
| 88 |
+
// `__rust_end_short_backtrace` means we are done hiding symbols
|
| 89 |
+
// for now. Print until we see `__rust_begin_short_backtrace`.
|
| 90 |
+
if print_fmt == PrintFmt::Short {
|
| 91 |
+
if let Some(sym) = symbol.name().and_then(|s| s.as_str()) {
|
| 92 |
+
if sym.contains("__rust_end_short_backtrace") {
|
| 93 |
+
print = true;
|
| 94 |
+
return;
|
| 95 |
+
}
|
| 96 |
+
if print && sym.contains("__rust_begin_short_backtrace") {
|
| 97 |
+
print = false;
|
| 98 |
+
return;
|
| 99 |
+
}
|
| 100 |
+
if !print {
|
| 101 |
+
omitted_count += 1;
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
if print {
|
| 107 |
+
if omitted_count > 0 {
|
| 108 |
+
debug_assert!(print_fmt == PrintFmt::Short);
|
| 109 |
+
// only print the message between the middle of frames
|
| 110 |
+
if !first_omit {
|
| 111 |
+
let _ = writeln!(
|
| 112 |
+
bt_fmt.formatter(),
|
| 113 |
+
" [... omitted {} frame{} ...]",
|
| 114 |
+
omitted_count,
|
| 115 |
+
if omitted_count > 1 { "s" } else { "" }
|
| 116 |
+
);
|
| 117 |
+
}
|
| 118 |
+
first_omit = false;
|
| 119 |
+
omitted_count = 0;
|
| 120 |
+
}
|
| 121 |
+
res = bt_fmt.frame().symbol(frame, symbol);
|
| 122 |
+
}
|
| 123 |
+
});
|
| 124 |
+
#[cfg(all(target_os = "nto", any(target_env = "nto70", target_env = "nto71")))]
|
| 125 |
+
if libc::__my_thread_exit as *mut libc::c_void == frame.ip() {
|
| 126 |
+
if !hit && print {
|
| 127 |
+
use crate::backtrace_rs::SymbolName;
|
| 128 |
+
res = bt_fmt.frame().print_raw(
|
| 129 |
+
frame.ip(),
|
| 130 |
+
Some(SymbolName::new("__my_thread_exit".as_bytes())),
|
| 131 |
+
None,
|
| 132 |
+
None,
|
| 133 |
+
);
|
| 134 |
+
}
|
| 135 |
+
return false;
|
| 136 |
+
}
|
| 137 |
+
if !hit && print {
|
| 138 |
+
res = bt_fmt.frame().print_raw(frame.ip(), None, None, None);
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
idx += 1;
|
| 143 |
+
res.is_ok()
|
| 144 |
+
})
|
| 145 |
+
};
|
| 146 |
+
res?;
|
| 147 |
+
bt_fmt.finish()?;
|
| 148 |
+
if print_fmt == PrintFmt::Short {
|
| 149 |
+
writeln!(
|
| 150 |
+
fmt,
|
| 151 |
+
"note: Some details are omitted, \
|
| 152 |
+
run with `RUST_BACKTRACE=full` for a verbose backtrace."
|
| 153 |
+
)?;
|
| 154 |
+
}
|
| 155 |
+
Ok(())
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
/// Fixed frame used to clean the backtrace with `RUST_BACKTRACE=1`. Note that
|
| 159 |
+
/// this is only inline(never) when backtraces in std are enabled, otherwise
|
| 160 |
+
/// it's fine to optimize away.
|
| 161 |
+
#[cfg_attr(feature = "backtrace", inline(never))]
|
| 162 |
+
pub fn __rust_begin_short_backtrace<F, T>(f: F) -> T
|
| 163 |
+
where
|
| 164 |
+
F: FnOnce() -> T,
|
| 165 |
+
{
|
| 166 |
+
let result = f();
|
| 167 |
+
|
| 168 |
+
// prevent this frame from being tail-call optimised away
|
| 169 |
+
crate::hint::black_box(());
|
| 170 |
+
|
| 171 |
+
result
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
/// Fixed frame used to clean the backtrace with `RUST_BACKTRACE=1`. Note that
|
| 175 |
+
/// this is only inline(never) when backtraces in std are enabled, otherwise
|
| 176 |
+
/// it's fine to optimize away.
|
| 177 |
+
#[cfg_attr(feature = "backtrace", inline(never))]
|
| 178 |
+
pub fn __rust_end_short_backtrace<F, T>(f: F) -> T
|
| 179 |
+
where
|
| 180 |
+
F: FnOnce() -> T,
|
| 181 |
+
{
|
| 182 |
+
let result = f();
|
| 183 |
+
|
| 184 |
+
// prevent this frame from being tail-call optimised away
|
| 185 |
+
crate::hint::black_box(());
|
| 186 |
+
|
| 187 |
+
result
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
/// Prints the filename of the backtrace frame.
|
| 191 |
+
///
|
| 192 |
+
/// See also `output`.
|
| 193 |
+
pub fn output_filename(
|
| 194 |
+
fmt: &mut fmt::Formatter<'_>,
|
| 195 |
+
bows: BytesOrWideString<'_>,
|
| 196 |
+
print_fmt: PrintFmt,
|
| 197 |
+
cwd: Option<&PathBuf>,
|
| 198 |
+
) -> fmt::Result {
|
| 199 |
+
let file: Cow<'_, Path> = match bows {
|
| 200 |
+
#[cfg(unix)]
|
| 201 |
+
BytesOrWideString::Bytes(bytes) => {
|
| 202 |
+
use crate::os::unix::prelude::*;
|
| 203 |
+
Path::new(crate::ffi::OsStr::from_bytes(bytes)).into()
|
| 204 |
+
}
|
| 205 |
+
#[cfg(not(unix))]
|
| 206 |
+
BytesOrWideString::Bytes(bytes) => {
|
| 207 |
+
Path::new(crate::str::from_utf8(bytes).unwrap_or("<unknown>")).into()
|
| 208 |
+
}
|
| 209 |
+
#[cfg(windows)]
|
| 210 |
+
BytesOrWideString::Wide(wide) => {
|
| 211 |
+
use crate::os::windows::prelude::*;
|
| 212 |
+
Cow::Owned(crate::ffi::OsString::from_wide(wide).into())
|
| 213 |
+
}
|
| 214 |
+
#[cfg(not(windows))]
|
| 215 |
+
BytesOrWideString::Wide(_wide) => Path::new("<unknown>").into(),
|
| 216 |
+
};
|
| 217 |
+
if print_fmt == PrintFmt::Short && file.is_absolute() {
|
| 218 |
+
if let Some(cwd) = cwd {
|
| 219 |
+
if let Ok(stripped) = file.strip_prefix(&cwd) {
|
| 220 |
+
if let Some(s) = stripped.to_str() {
|
| 221 |
+
return write!(fmt, ".{}{s}", path::MAIN_SEPARATOR);
|
| 222 |
+
}
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
fmt::Display::fmt(&file.display(), fmt)
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))]
|
| 230 |
+
pub fn set_image_base() {
|
| 231 |
+
let image_base = crate::os::fortanix_sgx::mem::image_base();
|
| 232 |
+
backtrace_rs::set_image_base(crate::ptr::without_provenance_mut(image_base as _));
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
#[cfg(not(all(target_vendor = "fortanix", target_env = "sgx")))]
|
| 236 |
+
pub fn set_image_base() {
|
| 237 |
+
// nothing to do for platforms other than SGX
|
| 238 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/cmath.rs
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#![cfg(not(test))]
|
| 2 |
+
|
| 3 |
+
// These symbols are all defined by `libm`,
|
| 4 |
+
// or by `compiler-builtins` on unsupported platforms.
|
| 5 |
+
unsafe extern "C" {
|
| 6 |
+
pub safe fn acos(n: f64) -> f64;
|
| 7 |
+
pub safe fn asin(n: f64) -> f64;
|
| 8 |
+
pub safe fn atan(n: f64) -> f64;
|
| 9 |
+
pub safe fn atan2(a: f64, b: f64) -> f64;
|
| 10 |
+
pub safe fn cosh(n: f64) -> f64;
|
| 11 |
+
pub safe fn expm1(n: f64) -> f64;
|
| 12 |
+
pub safe fn expm1f(n: f32) -> f32;
|
| 13 |
+
#[cfg_attr(target_env = "msvc", link_name = "_hypot")]
|
| 14 |
+
pub safe fn hypot(x: f64, y: f64) -> f64;
|
| 15 |
+
#[cfg_attr(target_env = "msvc", link_name = "_hypotf")]
|
| 16 |
+
pub safe fn hypotf(x: f32, y: f32) -> f32;
|
| 17 |
+
pub safe fn log1p(n: f64) -> f64;
|
| 18 |
+
pub safe fn log1pf(n: f32) -> f32;
|
| 19 |
+
pub safe fn sinh(n: f64) -> f64;
|
| 20 |
+
pub safe fn tan(n: f64) -> f64;
|
| 21 |
+
pub safe fn tanh(n: f64) -> f64;
|
| 22 |
+
pub safe fn tgamma(n: f64) -> f64;
|
| 23 |
+
pub safe fn tgammaf(n: f32) -> f32;
|
| 24 |
+
pub safe fn lgamma_r(n: f64, s: &mut i32) -> f64;
|
| 25 |
+
#[cfg(not(target_os = "aix"))]
|
| 26 |
+
pub safe fn lgammaf_r(n: f32, s: &mut i32) -> f32;
|
| 27 |
+
pub safe fn erf(n: f64) -> f64;
|
| 28 |
+
pub safe fn erff(n: f32) -> f32;
|
| 29 |
+
pub safe fn erfc(n: f64) -> f64;
|
| 30 |
+
pub safe fn erfcf(n: f32) -> f32;
|
| 31 |
+
|
| 32 |
+
pub safe fn acosf128(n: f128) -> f128;
|
| 33 |
+
pub safe fn asinf128(n: f128) -> f128;
|
| 34 |
+
pub safe fn atanf128(n: f128) -> f128;
|
| 35 |
+
pub safe fn atan2f128(a: f128, b: f128) -> f128;
|
| 36 |
+
pub safe fn cbrtf128(n: f128) -> f128;
|
| 37 |
+
pub safe fn coshf128(n: f128) -> f128;
|
| 38 |
+
pub safe fn expm1f128(n: f128) -> f128;
|
| 39 |
+
pub safe fn hypotf128(x: f128, y: f128) -> f128;
|
| 40 |
+
pub safe fn log1pf128(n: f128) -> f128;
|
| 41 |
+
pub safe fn sinhf128(n: f128) -> f128;
|
| 42 |
+
pub safe fn tanf128(n: f128) -> f128;
|
| 43 |
+
pub safe fn tanhf128(n: f128) -> f128;
|
| 44 |
+
pub safe fn tgammaf128(n: f128) -> f128;
|
| 45 |
+
pub safe fn lgammaf128_r(n: f128, s: &mut i32) -> f128;
|
| 46 |
+
pub safe fn erff128(n: f128) -> f128;
|
| 47 |
+
pub safe fn erfcf128(n: f128) -> f128;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
cfg_select! {
|
| 51 |
+
all(target_os = "windows", target_env = "msvc", target_arch = "x86") => {
|
| 52 |
+
// On 32-bit x86 MSVC these functions aren't defined, so we just define shims
|
| 53 |
+
// which promote everything to f64, perform the calculation, and then demote
|
| 54 |
+
// back to f32. While not precisely correct should be "correct enough" for now.
|
| 55 |
+
#[inline]
|
| 56 |
+
pub fn acosf(n: f32) -> f32 {
|
| 57 |
+
f64::acos(n as f64) as f32
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
#[inline]
|
| 61 |
+
pub fn asinf(n: f32) -> f32 {
|
| 62 |
+
f64::asin(n as f64) as f32
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
#[inline]
|
| 66 |
+
pub fn atan2f(n: f32, b: f32) -> f32 {
|
| 67 |
+
f64::atan2(n as f64, b as f64) as f32
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
#[inline]
|
| 71 |
+
pub fn atanf(n: f32) -> f32 {
|
| 72 |
+
f64::atan(n as f64) as f32
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
#[inline]
|
| 76 |
+
pub fn coshf(n: f32) -> f32 {
|
| 77 |
+
f64::cosh(n as f64) as f32
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
#[inline]
|
| 81 |
+
pub fn sinhf(n: f32) -> f32 {
|
| 82 |
+
f64::sinh(n as f64) as f32
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
#[inline]
|
| 86 |
+
pub fn tanf(n: f32) -> f32 {
|
| 87 |
+
f64::tan(n as f64) as f32
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
#[inline]
|
| 91 |
+
pub fn tanhf(n: f32) -> f32 {
|
| 92 |
+
f64::tanh(n as f64) as f32
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
_ => {
|
| 96 |
+
unsafe extern "C" {
|
| 97 |
+
pub safe fn acosf(n: f32) -> f32;
|
| 98 |
+
pub safe fn asinf(n: f32) -> f32;
|
| 99 |
+
pub safe fn atan2f(a: f32, b: f32) -> f32;
|
| 100 |
+
pub safe fn atanf(n: f32) -> f32;
|
| 101 |
+
pub safe fn coshf(n: f32) -> f32;
|
| 102 |
+
pub safe fn sinhf(n: f32) -> f32;
|
| 103 |
+
pub safe fn tanf(n: f32) -> f32;
|
| 104 |
+
pub safe fn tanhf(n: f32) -> f32;
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
// On AIX, we don't have lgammaf_r only the f64 version, so we can
|
| 110 |
+
// use the f64 version lgamma_r
|
| 111 |
+
#[cfg(target_os = "aix")]
|
| 112 |
+
pub fn lgammaf_r(n: f32, s: &mut i32) -> f32 {
|
| 113 |
+
lgamma_r(n.into(), s) as f32
|
| 114 |
+
}
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/configure_builtins.rs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! The configure builtins provides runtime support compiler-builtin features
|
| 2 |
+
//! which require dynamic initialization to work as expected, e.g. aarch64
|
| 3 |
+
//! outline-atomics.
|
| 4 |
+
|
| 5 |
+
/// Enable LSE atomic operations at startup, if supported.
|
| 6 |
+
///
|
| 7 |
+
/// Linker sections are based on what [`ctor`] does, with priorities to run slightly before user
|
| 8 |
+
/// code:
|
| 9 |
+
///
|
| 10 |
+
/// - Apple uses the section `__mod_init_func`, `mod_init_funcs` is needed to set
|
| 11 |
+
/// `S_MOD_INIT_FUNC_POINTERS`. There doesn't seem to be a way to indicate priorities.
|
| 12 |
+
/// - Windows uses `.CRT$XCT`, which is run before user constructors (these should use `.CRT$XCU`).
|
| 13 |
+
/// - ELF uses `.init_array` with a priority of 90, which runs before our `ARGV_INIT_ARRAY`
|
| 14 |
+
/// initializer (priority 99). Both are within the 0-100 implementation-reserved range, per docs
|
| 15 |
+
/// for the [`prio-ctor-dtor`] warning, and this matches compiler-rt's `CONSTRUCTOR_PRIORITY`.
|
| 16 |
+
///
|
| 17 |
+
/// To save startup time, the initializer is only run if outline atomic routines from
|
| 18 |
+
/// compiler-builtins may be used. If LSE is known to be available then the calls are never
|
| 19 |
+
/// emitted, and if we build the C intrinsics then it has its own initializer using the symbol
|
| 20 |
+
/// `__aarch64_have_lse_atomics`.
|
| 21 |
+
///
|
| 22 |
+
/// Initialization is done in a global constructor to so we get the same behavior regardless of
|
| 23 |
+
/// whether Rust's `init` is used, or if we are in a `dylib` or `no_main` situation (as opposed
|
| 24 |
+
/// to doing it as part of pre-main startup). This also matches C implementations.
|
| 25 |
+
///
|
| 26 |
+
/// Ideally `core` would have something similar, but detecting the CPU features requires the
|
| 27 |
+
/// auxiliary vector from the OS. We do the initialization in `std` rather than as part of
|
| 28 |
+
/// `compiler-builtins` because a builtins->std dependency isn't possible, and inlining parts of
|
| 29 |
+
/// `std-detect` would be much messier.
|
| 30 |
+
///
|
| 31 |
+
/// [`ctor`]: https://github.com/mmastrac/rust-ctor/blob/63382b833ddcbfb8b064f4e86bfa1ed4026ff356/shared/src/macros/mod.rs#L522-L534
|
| 32 |
+
/// [`prio-ctor-dtor`]: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
|
| 33 |
+
#[cfg(all(
|
| 34 |
+
target_arch = "aarch64",
|
| 35 |
+
target_feature = "outline-atomics",
|
| 36 |
+
not(target_feature = "lse"),
|
| 37 |
+
not(feature = "compiler-builtins-c"),
|
| 38 |
+
))]
|
| 39 |
+
#[used]
|
| 40 |
+
#[cfg_attr(target_vendor = "apple", unsafe(link_section = "__DATA,__mod_init_func,mod_init_funcs"))]
|
| 41 |
+
#[cfg_attr(target_os = "windows", unsafe(link_section = ".CRT$XCT"))]
|
| 42 |
+
#[cfg_attr(
|
| 43 |
+
not(any(target_vendor = "apple", target_os = "windows")),
|
| 44 |
+
unsafe(link_section = ".init_array.90")
|
| 45 |
+
)]
|
| 46 |
+
static RUST_LSE_INIT: extern "C" fn() = {
|
| 47 |
+
extern "C" fn init_lse() {
|
| 48 |
+
use crate::arch;
|
| 49 |
+
|
| 50 |
+
// This is provided by compiler-builtins::aarch64_outline_atomics.
|
| 51 |
+
unsafe extern "C" {
|
| 52 |
+
fn __rust_enable_lse();
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
if arch::is_aarch64_feature_detected!("lse") {
|
| 56 |
+
unsafe {
|
| 57 |
+
__rust_enable_lse();
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
init_lse
|
| 62 |
+
};
|
rust/.rustup/toolchains/stable-x86_64-pc-windows-msvc/lib/rustlib/src/rust/library/std/src/sys/env/common.rs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use crate::ffi::OsString;
|
| 2 |
+
use crate::{fmt, vec};
|
| 3 |
+
|
| 4 |
+
pub struct Env {
|
| 5 |
+
iter: vec::IntoIter<(OsString, OsString)>,
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
impl Env {
|
| 9 |
+
pub(super) fn new(env: Vec<(OsString, OsString)>) -> Self {
|
| 10 |
+
Env { iter: env.into_iter() }
|
| 11 |
+
}
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
impl fmt::Debug for Env {
|
| 15 |
+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
| 16 |
+
f.debug_list().entries(self.iter.as_slice()).finish()
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
impl !Send for Env {}
|
| 21 |
+
impl !Sync for Env {}
|
| 22 |
+
|
| 23 |
+
impl Iterator for Env {
|
| 24 |
+
type Item = (OsString, OsString);
|
| 25 |
+
fn next(&mut self) -> Option<(OsString, OsString)> {
|
| 26 |
+
self.iter.next()
|
| 27 |
+
}
|
| 28 |
+
fn size_hint(&self) -> (usize, Option<usize>) {
|
| 29 |
+
self.iter.size_hint()
|
| 30 |
+
}
|
| 31 |
+
}
|