This contains a mixture of mostly high quality crates and a few low quality crates. Randomly selected based on presence of specific regexes.
/// Checks if this channel contains a message that this receiver has not yet
/// seen. The new value is not marked as seen.
///
/// Although this method is called `has_changed`, it does not check new
/// messages for equality, so this call will return true even if the new
/// message is equal to the old message.
///
/// Returns an error if the channel has been closed.
/// # Examples
///
/// ```
/// use tokio::sync::watch;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = watch::channel("hello");
///
/// tx.send("goodbye").unwrap();
///
/// assert!(rx.has_changed().unwrap());
/// assert_eq!(*rx.borrow_and_update(), "goodbye");
///
/// // The value has been marked as seen
/// assert!(!rx.has_changed().unwrap());
///
/// drop(tx);
/// // The `tx` handle has been dropped
/// assert!(rx.has_changed().is_err());
/// }
/// ```
pub fn has_changed(&self) -> Result<bool, error::RecvError> {
/// Calculates the offset from a pointer (convenience for `.offset(count as isize)`).
///
/// `count` is in units of T; e.g., a `count` of 3 represents a pointer
/// offset of `3 * size_of::<T>()` bytes.
///
/// # Safety
///
/// If any of the following conditions are violated, the result is Undefined
/// Behavior:
///
/// * Both the starting and resulting pointer must be either in bounds or one
/// byte past the end of the same [allocated object].
///
/// * The computed offset, **in bytes**, cannot overflow an `isize`.
///
/// * The offset being in bounds cannot rely on "wrapping around" the address
/// space. That is, the infinite-precision sum must fit in a `usize`.
///
/// The compiler and standard library generally tries to ensure allocations
/// never reach a size where an offset is a concern. For instance, `Vec`
/// and `Box` ensure they never allocate more than `isize::MAX` bytes, so
/// `vec.as_ptr().add(vec.len())` is always safe.
///
/// Most platforms fundamentally can't even construct such an allocation.
/// For instance, no known 64-bit platform can ever serve a request
/// for 2<sup>63</sup> bytes due to page-table limitations or splitting the address space.
/// However, some 32-bit and 16-bit platforms may successfully serve a request for
/// more than `isize::MAX` bytes with things like Physical Address
/// Extension. As such, memory acquired directly from allocators or memory
/// mapped files *may* be too large to handle with this function.
///
/// Consider using [`wrapping_add`] instead if these constraints are
/// difficult to satisfy. The only advantage of this method is that it
/// enables more aggressive compiler optimizations.
///
/// [`wrapping_add`]: #method.wrapping_add
/// [allocated object]: crate::ptr#allocated-object
///
/// # Examples
///
/// ```
/// let s: &str = "123";
/// let ptr: *const u8 = s.as_ptr();
///
/// unsafe {
/// println!("{}", *ptr.add(1) as char);
/// println!("{}", *ptr.add(2) as char);
/// }
/// ```
#[stable(feature = "pointer_methods", since = "1.26.0")]
/// Opens a TCP connection to a remote host.
///
/// `addr` is an address of the remote host. Anything which implements the
/// [`ToSocketAddrs`] trait can be supplied as the address. If `addr`
/// yields multiple addresses, connect will be attempted with each of the
/// addresses until a connection is successful. If none of the addresses
/// result in a successful connection, the error returned from the last
/// connection attempt (the last address) is returned.
///
/// To configure the socket before connecting, you can use the [`TcpSocket`]
/// type.
///
/// [`ToSocketAddrs`]: trait@crate::net::ToSocketAddrs
/// [`TcpSocket`]: struct@crate::net::TcpSocket
///
/// # Examples
///
/// ```no_run
/// use tokio::net::TcpStream;
/// use tokio::io::AsyncWriteExt;
/// use std::error::Error;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn Error>> {
/// // Connect to a peer
/// let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// // Write some data.
/// stream.write_all(b"hello world!").await?;
///
/// Ok(())
/// }
/// ```
///
/// The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.
///
/// [`write_all`]: fn@crate::io::AsyncWriteExt::write_all
/// [`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt
pub async fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
/// Sets the [`Styles`] for terminal output
///
/// **NOTE:** This choice is propagated to all child subcommands.
///
/// **NOTE:** Default behaviour is [`Styles::default`].
///
/// # Examples
///
/// ```no_run
/// # use clap_builder as clap;
/// # use clap::{Command, ColorChoice, builder::styling};
/// let styles = styling::Styles::styled()
/// .header(styling::AnsiColor::Green.on_default() | styling::Effects::BOLD)
/// .usage(styling::AnsiColor::Green.on_default() | styling::Effects::BOLD)
/// .literal(styling::AnsiColor::Blue.on_default() | styling::Effects::BOLD)
/// .placeholder(styling::AnsiColor::Cyan.on_default());
/// Command::new("myprog")
/// .styles(styles)
/// .get_matches();
/// ```
#[cfg(feature = "color")]
/// Deserialize a `NaiveDateTime` from a microseconds timestamp
///
/// Intended for use with `serde`s `deserialize_with` attribute.
///
/// # Example:
///
/// ```rust
/// # use chrono::NaiveDateTime;
/// # use serde_derive::Deserialize;
/// use chrono::naive::serde::ts_microseconds::deserialize as from_micro_ts;
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct S {
/// #[serde(deserialize_with = "from_micro_ts")]
/// time: NaiveDateTime,
/// }
///
/// let my_s: S = serde_json::from_str(r#"{ "time": 1526522699918355 }"#)?;
/// assert_eq!(my_s, S { time: NaiveDateTime::from_timestamp_opt(1526522699, 918355000).unwrap() });
///
/// let my_s: S = serde_json::from_str(r#"{ "time": -1 }"#)?;
/// assert_eq!(my_s, S { time: NaiveDateTime::from_timestamp_opt(-1, 999_999_000).unwrap() });
/// # Ok::<(), serde_json::Error>(())
/// ```
pub fn deserialize<'de, D>(d: D) -> Result<NaiveDateTime, D::Error>
/// Set value for the `IPV6_FREEBIND` option on this socket.
///
/// This is an IPv6 counterpart of `IP_FREEBIND` socket option on
/// Android/Linux. For more information about this option, see
/// [`set_freebind`].
///
/// [`set_freebind`]: crate::Socket::set_freebind
///
/// # Examples
///
/// On Linux:
///
/// ```
/// use socket2::{Domain, Socket, Type};
/// use std::io::{self, Error, ErrorKind};
///
/// fn enable_freebind(socket: &Socket) -> io::Result<()> {
/// match socket.domain()? {
/// Domain::IPV4 => socket.set_freebind(true)?,
/// Domain::IPV6 => socket.set_freebind_ipv6(true)?,
/// _ => return Err(Error::new(ErrorKind::Other, "unsupported domain")),
/// };
/// Ok(())
/// }
///
/// # fn main() -> io::Result<()> {
/// # let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?;
/// # enable_freebind(&socket)
/// # }
/// ```
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
/// Characters used in mathematical notation
///
/// ✨ *Enabled with the `compiled_data` Cargo feature.*
///
/// [📚 Help choosing a constructor](icu_provider::constructors)
///
/// # Example
///
/// ```
/// use icu_properties::sets;
///
/// let math = sets::math();
///
/// assert!(math.contains('='));
/// assert!(math.contains('+'));
/// assert!(!math.contains('-'));
/// assert!(math.contains('−')); // U+2212 MINUS SIGN
/// assert!(!math.contains('/'));
/// assert!(math.contains('∕')); // U+2215 DIVISION SLASH
/// ```
/// Parse an absolute URL from a string.
///
/// # Examples
///
/// ```rust
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("https://example.net")?;
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
///
/// # Errors
///
/// If the function can not parse an absolute URL from the given string,
/// a [`ParseError`] variant will be returned.
///
/// [`ParseError`]: enum.ParseError.html
#[inline]
/// Returns the first entry in the map for in-place manipulation.
/// The key of this entry is the minimum key in the map.
///
/// # Examples
///
/// ```
/// use std::collections::BTreeMap;
///
/// let mut map = BTreeMap::new();
/// map.insert(1, "a");
/// map.insert(2, "b");
/// if let Some(mut entry) = map.first_entry() {
/// if *entry.key() > 0 {
/// entry.insert("first");
/// }
/// }
/// assert_eq!(*map.get(&1).unwrap(), "first");
/// assert_eq!(*map.get(&2).unwrap(), "b");
/// ```
#[stable(feature = "map_first_last", since = "1.66.0")]
/// Tries to receive a datagram from the peer without waiting.
///
/// # Examples
///
/// ```no_run
/// use tokio::net::UnixDatagram;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// // Connect to a peer
/// let dir = tempfile::tempdir().unwrap();
/// let client_path = dir.path().join("client.sock");
/// let server_path = dir.path().join("server.sock");
/// let socket = UnixDatagram::bind(&client_path)?;
/// socket.connect(&server_path)?;
///
/// loop {
/// // Wait for the socket to be readable
/// socket.readable().await?;
///
/// // The buffer is **not** included in the async task and will
/// // only exist on the stack.
/// let mut buf = [0; 1024];
///
/// // Try to recv data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match socket.try_recv(&mut buf) {
/// Ok(n) => {
/// println!("GOT {:?}", &buf[..n]);
/// break;
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue;
/// }
/// Err(e) => {
/// return Err(e);
/// }
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub fn try_recv(&self, buf: &mut [u8]) -> io::Result<usize> {
/// Return the memory representation of this floating point number as a byte array in
/// little-endian byte order.
///
/// See [`from_bits`](Self::from_bits) for some discussion of the
/// portability of this operation (there are almost no issues).
///
/// # Examples
///
/// ```
/// let bytes = 12.5f32.to_le_bytes();
/// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
/// ```
#[must_use = "this returns the result of the operation, \
/// Creates a `Vec<usize>` from a [`FlexZeroSlice`] (or `FlexZeroVec`).
///
/// # Examples
///
/// ```
/// use zerovec::vecs::FlexZeroVec;
///
/// let nums: &[usize] = &[211, 281, 421, 461];
/// let fzv: FlexZeroVec = nums.iter().copied().collect();
/// let vec: Vec<usize> = fzv.to_vec();
///
/// assert_eq!(nums, vec.as_slice());
/// ```
#[inline]
/// Generates a wrapper function for a ioctl that writes an integer to the kernel.
///
/// The arguments to this macro are:
///
/// * The function name
/// * The ioctl identifier
/// * The ioctl sequence number
///
/// The generated function has the following signature:
///
/// ```rust,ignore
/// pub unsafe fn FUNCTION_NAME(fd: libc::c_int, data: nix::sys::ioctl::ioctl_param_type) -> Result<libc::c_int>
/// ```
///
/// `nix::sys::ioctl::ioctl_param_type` depends on the OS:
/// * BSD - `libc::c_int`
/// * Linux - `libc::c_ulong`
///
/// For a more in-depth explanation of ioctls, see [`::sys::ioctl`](sys/ioctl/index.html).
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate nix;
/// ioctl_write_int!(vt_activate, b'v', 4);
/// # fn main() {}
/// ```
#[macro_export(local_inner_macros)]
/// Return the span for this search configuration.
///
/// If one was not explicitly set, then the span corresponds to the entire
/// range of the haystack.
///
/// # Example
///
/// ```
/// use aho_corasick::{Input, Span};
///
/// let input = Input::new("foobar");
/// assert_eq!(Span { start: 0, end: 6 }, input.get_span());
/// ```
#[inline]
/// Overrides the runtime-determined display name of the program for help and error messages.
///
/// # Examples
///
/// ```no_run
/// # use clap::Command;
/// Command::new("My Program")
/// .display_name("my_program")
/// # ;
/// ```
#[must_use]
/// Calculates `self` + `rhs` with an unsigned `rhs`
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
#[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
/// Wait for channel capacity. Once capacity to send one message is
/// available, it is reserved for the caller.
///
/// If the channel is full, the function waits for the number of unreceived
/// messages to become less than the channel capacity. Capacity to send one
/// message is reserved for the caller. A [`Permit`] is returned to track
/// the reserved capacity. The [`send`] function on [`Permit`] consumes the
/// reserved capacity.
///
/// Dropping [`Permit`] without sending a message releases the capacity back
/// to the channel.
///
/// [`Permit`]: Permit
/// [`send`]: Permit::send
///
/// # Examples
///
/// ```
/// use tokio::sync::mpsc;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = mpsc::channel(1);
///
/// // Reserve capacity
/// let permit = tx.reserve().await.unwrap();
///
/// // Trying to send directly on the `tx` will fail due to no
/// // available capacity.
/// assert!(tx.try_send(123).is_err());
///
/// // Sending on the permit succeeds
/// permit.send(456);
///
/// // The value sent on the permit is received
/// assert_eq!(rx.recv().await.unwrap(), 456);
/// }
/// ```
pub async fn reserve(&self) -> Result<Permit<'_, T>, SendError<()>> {
/// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
/// with a lifetime bound to the map itself.
///
/// # Examples
///
/// ```
/// use hashbrown::hash_map::{HashMap, RawEntryMut};
/// use std::rc::Rc;
///
/// let key_one = Rc::new("a");
/// let key_two = Rc::new("a");
///
/// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
/// map.insert(key_one.clone(), 10);
///
/// assert_eq!(map[&key_one], 10);
/// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
///
/// let inside_key: &mut Rc<&str>;
/// let inside_value: &mut u32;
/// match map.raw_entry_mut().from_key(&key_one) {
/// RawEntryMut::Vacant(_) => panic!(),
/// RawEntryMut::Occupied(o) => {
/// let tuple = o.into_key_value();
/// inside_key = tuple.0;
/// inside_value = tuple.1;
/// }
/// }
/// *inside_key = key_two.clone();
/// *inside_value = 100;
/// assert_eq!(map[&key_two], 100);
/// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Waits for a permit for a concurrent operation.
///
/// Returns a guard that releases the permit when dropped.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`acquire`][Semaphore::acquire] method,
/// this method will block the current thread until the permit is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a semaphore can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use async_lock::Semaphore;
///
/// let s = Semaphore::new(2);
/// let guard = s.acquire_blocking();
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Completes when the receiver has dropped.
///
/// This allows the producers to get notified when interest in the produced
/// values is canceled and immediately stop doing work.
///
/// # Cancel safety
///
/// This method is cancel safe. Once the channel is closed, it stays closed
/// forever and all future calls to `closed` will return immediately.
///
/// # Examples
///
/// ```
/// use tokio::sync::mpsc;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx1, rx) = mpsc::channel::<()>(1);
/// let tx2 = tx1.clone();
/// let tx3 = tx1.clone();
/// let tx4 = tx1.clone();
/// let tx5 = tx1.clone();
/// tokio::spawn(async move {
/// drop(rx);
/// });
///
/// futures::join!(
/// tx1.closed(),
/// tx2.closed(),
/// tx3.closed(),
/// tx4.closed(),
/// tx5.closed()
/// );
/// println!("Receiver dropped");
/// }
/// ```
pub async fn closed(&self) {
/// Retains only the characters specified by the predicate.
///
/// In other words, remove all characters `c` such that `f(c)` returns `false`.
/// This method operates in place, visiting each character exactly once in the
/// original order, and preserves the order of the retained characters.
///
/// # Examples
///
/// ```
/// let mut s = String::from("f_o_ob_ar");
///
/// s.retain(|c| c != '_');
///
/// assert_eq!(s, "foobar");
/// ```
///
/// Because the elements are visited exactly once in the original order,
/// external state may be used to decide which elements to keep.
///
/// ```
/// let mut s = String::from("abcde");
/// let keep = [false, true, true, false, true];
/// let mut iter = keep.iter();
/// s.retain(|_| *iter.next().unwrap());
/// assert_eq!(s, "bce");
/// ```
#[inline]
/// Converts this address to an [IPv4-compatible] [`IPv6` address].
///
/// `a.b.c.d` becomes `::a.b.c.d`
///
/// Note that IPv4-compatible addresses have been officially deprecated.
/// If you don't explicitly need an IPv4-compatible address for legacy reasons, consider using `to_ipv6_mapped` instead.
///
/// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
/// [`IPv6` address]: Ipv6Addr
///
/// # Examples
///
/// ```
/// use std::net::{Ipv4Addr, Ipv6Addr};
///
/// assert_eq!(
/// Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
/// Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x2ff)
/// );
/// ```
#[cfg_attr(
/// Returns an unsafe mutable pointer to the vector's buffer, or a dangling
/// raw pointer valid for zero sized reads if the vector didn't allocate.
///
/// The caller must ensure that the vector outlives the pointer this
/// function returns, or else it will end up pointing to garbage.
/// Modifying the vector may cause its buffer to be reallocated,
/// which would also make any pointers to it invalid.
///
/// This method guarantees that for the purpose of the aliasing model, this method
/// does not materialize a reference to the underlying slice, and thus the returned pointer
/// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`].
/// Note that calling other methods that materialize references to the slice,
/// or references to specific elements you are planning on accessing through this pointer,
/// may still invalidate this pointer.
/// See the second example below for how this guarantee can be used.
///
///
/// # Examples
///
/// ```
/// // Allocate vector big enough for 4 elements.
/// let size = 4;
/// let mut x: Vec<i32> = Vec::with_capacity(size);
/// let x_ptr = x.as_mut_ptr();
///
/// // Initialize elements via raw pointer writes, then set length.
/// unsafe {
/// for i in 0..size {
/// *x_ptr.add(i) = i as i32;
/// }
/// x.set_len(size);
/// }
/// assert_eq!(&*x, &[0, 1, 2, 3]);
/// ```
///
/// Due to the aliasing guarantee, the following code is legal:
///
/// ```rust
/// unsafe {
/// let mut v = vec![0];
/// let ptr1 = v.as_mut_ptr();
/// ptr1.write(1);
/// let ptr2 = v.as_mut_ptr();
/// ptr2.write(2);
/// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
/// ptr1.write(3);
/// }
/// ```
///
/// [`as_mut_ptr`]: Vec::as_mut_ptr
/// [`as_ptr`]: Vec::as_ptr
#[stable(feature = "vec_as_ptr", since = "1.37.0")]
/// Compare two DateTimes based on their true time, ignoring time zones
///
/// # Example
///
/// ```
/// use chrono::prelude::*;
///
/// let earlier = Utc
/// .with_ymd_and_hms(2015, 5, 15, 2, 0, 0)
/// .unwrap()
/// .with_timezone(&FixedOffset::west_opt(1 * 3600).unwrap());
/// let later = Utc
/// .with_ymd_and_hms(2015, 5, 15, 3, 0, 0)
/// .unwrap()
/// .with_timezone(&FixedOffset::west_opt(5 * 3600).unwrap());
///
/// assert_eq!(earlier.to_string(), "2015-05-15 01:00:00 -01:00");
/// assert_eq!(later.to_string(), "2015-05-14 22:00:00 -05:00");
///
/// assert!(later > earlier);
/// ```
fn partial_cmp(&self, other: &DateTime<Tz2>) -> Option<Ordering> {
/// Combine two streams into one by interleaving the output of both as it
/// is produced.
///
/// Values are produced from the merged stream in the order they arrive from
/// the two source streams. If both source streams provide values
/// simultaneously, the merge stream alternates between them. This provides
/// some level of fairness. You should not chain calls to `merge`, as this
/// will break the fairness of the merging.
///
/// The merged stream completes once **both** source streams complete. When
/// one source stream completes before the other, the merge stream
/// exclusively polls the remaining stream.
///
/// For merging multiple streams, consider using [`StreamMap`] instead.
///
/// [`StreamMap`]: crate::StreamMap
///
/// # Examples
///
/// ```
/// use tokio_stream::{StreamExt, Stream};
/// use tokio::sync::mpsc;
/// use tokio::time;
///
/// use std::time::Duration;
/// use std::pin::Pin;
///
/// # /*
/// #[tokio::main]
/// # */
/// # #[tokio::main(flavor = "current_thread")]
/// async fn main() {
/// # time::pause();
/// let (tx1, mut rx1) = mpsc::channel::<usize>(10);
/// let (tx2, mut rx2) = mpsc::channel::<usize>(10);
///
/// // Convert the channels to a `Stream`.
/// let rx1 = Box::pin(async_stream::stream! {
/// while let Some(item) = rx1.recv().await {
/// yield item;
/// }
/// }) as Pin<Box<dyn Stream<Item = usize> + Send>>;
///
/// let rx2 = Box::pin(async_stream::stream! {
/// while let Some(item) = rx2.recv().await {
/// yield item;
/// }
/// }) as Pin<Box<dyn Stream<Item = usize> + Send>>;
///
/// let mut rx = rx1.merge(rx2);
///
/// tokio::spawn(async move {
/// // Send some values immediately
/// tx1.send(1).await.unwrap();
/// tx1.send(2).await.unwrap();
///
/// // Let the other task send values
/// time::sleep(Duration::from_millis(20)).await;
///
/// tx1.send(4).await.unwrap();
/// });
///
/// tokio::spawn(async move {
/// // Wait for the first task to send values
/// time::sleep(Duration::from_millis(5)).await;
///
/// tx2.send(3).await.unwrap();
///
/// time::sleep(Duration::from_millis(25)).await;
///
/// // Send the final value
/// tx2.send(5).await.unwrap();
/// });
///
/// assert_eq!(1, rx.next().await.unwrap());
/// assert_eq!(2, rx.next().await.unwrap());
/// assert_eq!(3, rx.next().await.unwrap());
/// assert_eq!(4, rx.next().await.unwrap());
/// assert_eq!(5, rx.next().await.unwrap());
///
/// // The merged stream is consumed
/// assert!(rx.next().await.is_none());
/// }
/// ```
fn merge<U>(self, other: U) -> Merge<Self, U>
/// Write raw bytes from `RegValue` struct to a registry value.
/// Will set the `Default` value if `name` is an empty string.
///
/// # Examples
///
/// ```no_run
/// # use std::error::Error;
/// use winreg::{RegKey, RegValue};
/// use winreg::enums::*;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let hkcu = RegKey::predef(HKEY_CURRENT_USER);
/// let settings = hkcu.open_subkey("Software\\MyProduct\\Settings")?;
/// let bytes: Vec<u8> = vec![1, 2, 3, 5, 8, 13, 21, 34, 55, 89];
/// let data = RegValue{ vtype: REG_BINARY, bytes: bytes};
/// settings.set_raw_value("data", &data)?;
/// println!("Bytes: {:?}", data.bytes);
/// # Ok(())
/// # }
/// ```
pub fn set_raw_value<N: AsRef<OsStr>>(&self, name: N, value: &RegValue) -> io::Result<()> {
/// Apply `dimmed` effect
///
/// # Examples
///
/// ```rust
/// let style = anstyle::Style::new().dimmed();
/// ```
#[must_use]
/// Returns a tuple consisting of the `l` and `r` in `Both(l, r)`, if present.
/// Otherwise, returns the wrapped value for the present element, and the supplied
/// value for the other. The first (`l`) argument is used for a missing `Left`
/// value. The second (`r`) argument is used for a missing `Right` value.
///
/// Arguments passed to `or` are eagerly evaluated; if you are passing
/// the result of a function call, it is recommended to use [`or_else`],
/// which is lazily evaluated.
///
/// [`or_else`]: EitherOrBoth::or_else
///
/// # Examples
///
/// ```
/// # use itertools::EitherOrBoth;
/// assert_eq!(EitherOrBoth::Both("tree", 1).or("stone", 5), ("tree", 1));
/// assert_eq!(EitherOrBoth::Left("tree").or("stone", 5), ("tree", 5));
/// assert_eq!(EitherOrBoth::Right(1).or("stone", 5), ("stone", 1));
/// ```
pub fn or(self, l: A, r: B) -> (A, B) {
/// Gets an IEEE754 single-precision (4 bytes) floating point number from
/// `self` in little-endian byte order.
///
/// The current position is advanced by 4.
///
/// # Examples
///
/// ```
/// use bytes::Buf;
///
/// let mut buf = &b"\x9A\x99\x99\x3F hello"[..];
/// assert_eq!(1.2f32, buf.get_f32_le());
/// ```
///
/// # Panics
///
/// This function panics if there is not enough remaining data in `self`.
fn get_f32_le(&mut self) -> f32 {
/// Creates an AsyncFd backed by (and taking ownership of) an object
/// implementing [`AsRawFd`]. The backing file descriptor is cached at the
/// time of creation.
///
/// This method must be called in the context of a tokio runtime.
///
/// # Panics
///
/// This function panics if there is no current reactor set, or if the `rt`
/// feature flag is not enabled.
#[inline]
/// Runs a future to completion on the provided runtime, driving any local
/// futures spawned on this task set on the current thread.
///
/// This runs the given future on the runtime, blocking until it is
/// complete, and yielding its resolved result. Any tasks or timers which
/// the future spawns internally will be executed on the runtime. The future
/// may also call [`spawn_local`] to spawn_local additional local futures on the
/// current thread.
///
/// This method should not be called from an asynchronous context.
///
/// # Panics
///
/// This function panics if the executor is at capacity, if the provided
/// future panics, or if called within an asynchronous execution context.
///
/// # Notes
///
/// Since this function internally calls [`Runtime::block_on`], and drives
/// futures in the local task set inside that call to `block_on`, the local
/// futures may not use [in-place blocking]. If a blocking call needs to be
/// issued from a local task, the [`spawn_blocking`] API may be used instead.
///
/// For example, this will panic:
/// ```should_panic
/// use tokio::runtime::Runtime;
/// use tokio::task;
///
/// let rt = Runtime::new().unwrap();
/// let local = task::LocalSet::new();
/// local.block_on(&rt, async {
/// let join = task::spawn_local(async {
/// let blocking_result = task::block_in_place(|| {
/// // ...
/// });
/// // ...
/// });
/// join.await.unwrap();
/// })
/// ```
/// This, however, will not panic:
/// ```
/// use tokio::runtime::Runtime;
/// use tokio::task;
///
/// let rt = Runtime::new().unwrap();
/// let local = task::LocalSet::new();
/// local.block_on(&rt, async {
/// let join = task::spawn_local(async {
/// let blocking_result = task::spawn_blocking(|| {
/// // ...
/// }).await;
/// // ...
/// });
/// join.await.unwrap();
/// })
/// ```
///
/// [`spawn_local`]: fn@spawn_local
/// [`Runtime::block_on`]: method@crate::runtime::Runtime::block_on
/// [in-place blocking]: fn@crate::task::block_in_place
/// [`spawn_blocking`]: fn@crate::task::spawn_blocking
#[track_caller]
/// Writes an unsigned 16 bit integer to `self` in big-endian byte order.
///
/// The current position is advanced by 2.
///
/// # Examples
///
/// ```
/// use bytes::BufMut;
///
/// let mut buf = vec![];
/// buf.put_u16(0x0809);
/// assert_eq!(buf, b"\x08\x09");
/// ```
///
/// # Panics
///
/// This function panics if there is not enough remaining capacity in
/// `self`.
fn put_u16(&mut self, n: u16) {
/// # Panics
///
/// This may panic if an overflow occurs.
fn sub(self, rhs: Self) -> Self::Output {
/// Insert an element at `index`
fn zvl_insert(&mut self, index: usize, value: &T);
/// Remove the element at `index` (panicking if nonexistant)
fn zvl_remove(&mut self, index: usize) -> Self::OwnedType;
/// Replace the element at `index` with another one, returning the old element
fn zvl_replace(&mut self, index: usize, value: &T) -> Self::OwnedType;
/// Push an element to the end of this vector
fn zvl_push(&mut self, value: &T);
/// Create a new, empty vector, with given capacity
fn zvl_with_capacity(cap: usize) -> Self;
/// Remove all elements from the vector
fn zvl_clear(&mut self);
/// Reserve space for `addl` additional elements
fn zvl_reserve(&mut self, addl: usize);
/// Applies the permutation such that `before.zvl_get(permutation[i]) == after.zvl_get(i)`.
///
/// # Panics
/// If `permutation` is not a valid permutation of length `zvl_len()`.
fn zvl_permute(&mut self, permutation: &mut [usize]);
/// Returns true if and only if this regex matches the given haystack.
///
/// This routine may short circuit if it knows that scanning future input
/// will never lead to a different result. In particular, if the underlying
/// DFA enters a match state or a dead state, then this routine will return
/// `true` or `false`, respectively, without inspecting any future input.
///
/// # Panics
///
/// This routine panics if the search could not complete. This can occur
/// in a number of circumstances:
///
/// * The configuration of the DFA may permit it to "quit" the search.
/// For example, setting quit bytes or enabling heuristic support for
/// Unicode word boundaries. The default configuration does not enable any
/// option that could result in the DFA quitting.
/// * When the provided `Input` configuration is not supported. For
/// example, by providing an unsupported anchor mode.
///
/// When a search panics, callers cannot know whether a match exists or
/// not.
///
/// Use [`Regex::try_search`] if you want to handle these error conditions.
///
/// # Example
///
/// ```
/// use regex_automata::dfa::regex::Regex;
///
/// let re = Regex::new("foo[0-9]+bar")?;
/// assert_eq!(true, re.is_match("foo12345bar"));
/// assert_eq!(false, re.is_match("foobar"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
/// # Panics
///
/// Panics if the lifetime does not conform to the bulleted rules above.
///
/// # Invocation
///
/// ```
/// # use proc_macro2::Span;
/// # use syn::Lifetime;
/// #
/// # fn f() -> Lifetime {
/// Lifetime::new("'a", Span::call_site())
/// # }
/// ```
pub fn new(symbol: &str, span: Span) -> Self {
/// This is a convenience routine for extracting the substrings
/// corresponding to matching capture groups.
///
/// This returns a tuple where the first element corresponds to the full
/// substring of the haystack that matched the regex. The second element is
/// an array of substrings, with each corresponding to the to the substring
/// that matched for a particular capture group.
///
/// # Panics
///
/// This panics if the number of possible matching groups in this
/// `Captures` value is not fixed to `N` in all circumstances.
/// More precisely, this routine only works when `N` is equivalent to
/// [`Regex::static_captures_len`].
///
/// Stated more plainly, if the number of matching capture groups in a
/// regex can vary from match to match, then this function always panics.
///
/// For example, `(a)(b)|(c)` could produce two matching capture groups
/// or one matching capture group for any given match. Therefore, one
/// cannot use `extract` with such a pattern.
///
/// But a pattern like `(a)(b)|(c)(d)` can be used with `extract` because
/// the number of capture groups in every match is always equivalent,
/// even if the capture _indices_ in each match are not.
///
/// # Example
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})").unwrap();
/// let hay = b"On 2010-03-14, I became a Tenneessee lamb.";
/// let Some((full, [year, month, day])) =
/// re.captures(hay).map(|caps| caps.extract()) else { return };
/// assert_eq!(b"2010-03-14", full);
/// assert_eq!(b"2010", year);
/// assert_eq!(b"03", month);
/// assert_eq!(b"14", day);
/// ```
///
/// # Example: iteration
///
/// This example shows how to use this method when iterating over all
/// `Captures` matches in a haystack.
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"([0-9]{4})-([0-9]{2})-([0-9]{2})").unwrap();
/// let hay = b"1973-01-05, 1975-08-25 and 1980-10-18";
///
/// let mut dates: Vec<(&[u8], &[u8], &[u8])> = vec![];
/// for (_, [y, m, d]) in re.captures_iter(hay).map(|c| c.extract()) {
/// dates.push((y, m, d));
/// }
/// assert_eq!(dates, vec![
/// (&b"1973"[..], &b"01"[..], &b"05"[..]),
/// (&b"1975"[..], &b"08"[..], &b"25"[..]),
/// (&b"1980"[..], &b"10"[..], &b"18"[..]),
/// ]);
/// ```
///
/// # Example: parsing different formats
///
/// This API is particularly useful when you need to extract a particular
/// value that might occur in a different format. Consider, for example,
/// an identifier that might be in double quotes or single quotes:
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r#"id:(?:"([^"]+)"|'([^']+)')"#).unwrap();
/// let hay = br#"The first is id:"foo" and the second is id:'bar'."#;
/// let mut ids = vec![];
/// for (_, [id]) in re.captures_iter(hay).map(|c| c.extract()) {
/// ids.push(id);
/// }
/// assert_eq!(ids, vec![b"foo", b"bar"]);
/// ```
pub fn extract<const N: usize>(&self) -> (&'h [u8], [&'h [u8]; N]) {
/// The first index of that an argument showed up.
///
/// Indices are similar to argv indices, but are not exactly 1:1.
///
/// For flags (i.e. those arguments which don't have an associated value), indices refer
/// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
/// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
/// index for `val` would be recorded. This is by design.
///
/// Besides the flag/option discrepancy, the primary difference between an argv index and clap
/// index, is that clap continues counting once all arguments have properly separated, whereas
/// an argv index does not.
///
/// The examples should clear this up.
///
/// *NOTE:* If an argument is allowed multiple times, this method will only give the *first*
/// index. See [`ArgMatches::indices_of`].
///
/// # Panics
///
/// If `id` is not a valid argument or group id (debug builds).
///
/// # Examples
///
/// The argv indices are listed in the comments below. See how they correspond to the clap
/// indices. Note that if it's not listed in a clap index, this is because it's not saved in
/// in an `ArgMatches` struct for querying.
///
/// ```rust
/// # use clap_builder as clap;
/// # use clap::{Command, Arg, ArgAction};
/// let m = Command::new("myapp")
/// .arg(Arg::new("flag")
/// .short('f')
/// .action(ArgAction::SetTrue))
/// .arg(Arg::new("option")
/// .short('o')
/// .action(ArgAction::Set))
/// .get_matches_from(vec!["myapp", "-f", "-o", "val"]);
/// // ARGV indices: ^0 ^1 ^2 ^3
/// // clap indices: ^1 ^3
///
/// assert_eq!(m.index_of("flag"), Some(1));
/// assert_eq!(m.index_of("option"), Some(3));
/// ```
///
/// Now notice, if we use one of the other styles of options:
///
/// ```rust
/// # use clap_builder as clap;
/// # use clap::{Command, Arg, ArgAction};
/// let m = Command::new("myapp")
/// .arg(Arg::new("flag")
/// .short('f')
/// .action(ArgAction::SetTrue))
/// .arg(Arg::new("option")
/// .short('o')
/// .action(ArgAction::Set))
/// .get_matches_from(vec!["myapp", "-f", "-o=val"]);
/// // ARGV indices: ^0 ^1 ^2
/// // clap indices: ^1 ^3
///
/// assert_eq!(m.index_of("flag"), Some(1));
/// assert_eq!(m.index_of("option"), Some(3));
/// ```
///
/// Things become much more complicated, or clear if we look at a more complex combination of
/// flags. Let's also throw in the final option style for good measure.
///
/// ```rust
/// # use clap_builder as clap;
/// # use clap::{Command, Arg, ArgAction};
/// let m = Command::new("myapp")
/// .arg(Arg::new("flag")
/// .short('f')
/// .action(ArgAction::SetTrue))
/// .arg(Arg::new("flag2")
/// .short('F')
/// .action(ArgAction::SetTrue))
/// .arg(Arg::new("flag3")
/// .short('z')
/// .action(ArgAction::SetTrue))
/// .arg(Arg::new("option")
/// .short('o')
/// .action(ArgAction::Set))
/// .get_matches_from(vec!["myapp", "-fzF", "-oval"]);
/// // ARGV indices: ^0 ^1 ^2
/// // clap indices: ^1,2,3 ^5
/// //
/// // clap sees the above as 'myapp -f -z -F -o val'
/// // ^0 ^1 ^2 ^3 ^4 ^5
/// assert_eq!(m.index_of("flag"), Some(1));
/// assert_eq!(m.index_of("flag2"), Some(3));
/// assert_eq!(m.index_of("flag3"), Some(2));
/// assert_eq!(m.index_of("option"), Some(5));
/// ```
///
/// One final combination of flags/options to see how they combine:
///
/// ```rust
/// # use clap_builder as clap;
/// # use clap::{Command, Arg, ArgAction};
/// let m = Command::new("myapp")
/// .arg(Arg::new("flag")
/// .short('f')
/// .action(ArgAction::SetTrue))
/// .arg(Arg::new("flag2")
/// .short('F')
/// .action(ArgAction::SetTrue))
/// .arg(Arg::new("flag3")
/// .short('z')
/// .action(ArgAction::SetTrue))
/// .arg(Arg::new("option")
/// .short('o')
/// .action(ArgAction::Set))
/// .get_matches_from(vec!["myapp", "-fzFoval"]);
/// // ARGV indices: ^0 ^1
/// // clap indices: ^1,2,3^5
/// //
/// // clap sees the above as 'myapp -f -z -F -o val'
/// // ^0 ^1 ^2 ^3 ^4 ^5
/// assert_eq!(m.index_of("flag"), Some(1));
/// assert_eq!(m.index_of("flag2"), Some(3));
/// assert_eq!(m.index_of("flag3"), Some(2));
/// assert_eq!(m.index_of("option"), Some(5));
/// ```
///
/// The last part to mention is when values are sent in multiple groups with a [delimiter].
///
/// ```rust
/// # use clap_builder as clap;
/// # use clap::{Command, Arg};
/// let m = Command::new("myapp")
/// .arg(Arg::new("option")
/// .short('o')
/// .value_delimiter(',')
/// .num_args(1..))
/// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
/// // ARGV indices: ^0 ^1
/// // clap indices: ^2 ^3 ^4
/// //
/// // clap sees the above as 'myapp -o val1 val2 val3'
/// // ^0 ^1 ^2 ^3 ^4
/// assert_eq!(m.index_of("option"), Some(2));
/// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
/// ```
/// [delimiter]: crate::Arg::value_delimiter()
#[cfg_attr(debug_assertions, track_caller)]
/// Creates a new instance of an `RwLock<T>` which is unlocked
/// and allows a maximum of `max_reads` concurrent readers.
///
/// # Examples
///
/// ```
/// use tokio::sync::RwLock;
///
/// let lock = RwLock::with_max_readers(5, 1024);
/// ```
///
/// # Panics
///
/// Panics if `max_reads` is more than `u32::MAX >> 3`.
#[track_caller]
/// Converts slice to a generic array reference with inferred length;
///
/// # Panics
///
/// Panics if the slice is not equal to the length of the array.
#[inline]
/// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
/// of the slice.
///
/// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
/// slice, then the last chunk will not have length `chunk_size`.
///
/// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
/// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
/// of the slice.
///
/// # Panics
///
/// Panics if `chunk_size` is 0.
///
/// # Examples
///
/// ```
/// let slice = ['l', 'o', 'r', 'e', 'm'];
/// let mut iter = slice.rchunks(2);
/// assert_eq!(iter.next().unwrap(), &['e', 'm']);
/// assert_eq!(iter.next().unwrap(), &['o', 'r']);
/// assert_eq!(iter.next().unwrap(), &['l']);
/// assert!(iter.next().is_none());
/// ```
///
/// [`rchunks_exact`]: slice::rchunks_exact
/// [`chunks`]: slice::chunks
#[stable(feature = "rchunks", since = "1.31.0")]
/// Decode an entry from the given entry data `d`, providing the `pack_offset` to allow tracking the start of the entry data section.
///
/// # Panics
///
/// If we cannot understand the header, garbage data is likely to trigger this.
pub fn from_bytes(d: &[u8], pack_offset: data::Offset, hash_len: usize) -> data::Entry {
/// Creates new `UnixDatagram` from a `std::os::unix::net::UnixDatagram`.
///
/// This function is intended to be used to wrap a UnixDatagram from the
/// standard library in the Tokio equivalent.
///
/// # Notes
///
/// The caller is responsible for ensuring that the socker is in
/// non-blocking mode. Otherwise all I/O operations on the socket
/// will block the thread, which will cause unexpected behavior.
/// Non-blocking mode can be set using [`set_nonblocking`].
///
/// [`set_nonblocking`]: std::os::unix::net::UnixDatagram::set_nonblocking
///
/// # Panics
///
/// This function panics if it is not called from within a runtime with
/// IO enabled.
///
/// The runtime is usually set implicitly when this function is called
/// from a future driven by a Tokio runtime, otherwise runtime can be set
/// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
/// # Examples
/// ```
/// # use std::error::Error;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn Error>> {
/// use tokio::net::UnixDatagram;
/// use std::os::unix::net::UnixDatagram as StdUDS;
/// use tempfile::tempdir;
///
/// // We use a temporary directory so that the socket
/// // files left by the bound sockets will get cleaned up.
/// let tmp = tempdir()?;
///
/// // Bind the socket to a filesystem path
/// let socket_path = tmp.path().join("socket");
/// let std_socket = StdUDS::bind(&socket_path)?;
/// std_socket.set_nonblocking(true)?;
/// let tokio_socket = UnixDatagram::from_std(std_socket)?;
///
/// # Ok(())
/// # }
/// ```
#[track_caller]
/// Replaces the entry, returning the old key and value. The new key in the hash map will be
/// the key used to create this entry.
///
/// # Panics
///
/// Will panic if this OccupiedEntryRef was created through [`EntryRef::insert`].
///
/// # Examples
///
/// ```
/// use hashbrown::hash_map::{EntryRef, HashMap};
/// use std::rc::Rc;
///
/// let mut map: HashMap<Rc<str>, u32> = HashMap::new();
/// let key: Rc<str> = Rc::from("Stringthing");
///
/// map.insert(key.clone(), 15);
/// assert_eq!(Rc::strong_count(&key), 2);
///
/// match map.entry_ref("Stringthing") {
/// EntryRef::Occupied(entry) => {
/// let (old_key, old_value): (Rc<str>, u32) = entry.replace_entry(16);
/// assert!(Rc::ptr_eq(&key, &old_key) && old_value == 15);
/// }
/// EntryRef::Vacant(_) => panic!(),
/// }
///
/// assert_eq!(Rc::strong_count(&key), 1);
/// assert_eq!(map["Stringthing"], 16);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Blockingly locks this `RwLock` with exclusive write access.
///
/// This method is intended for use cases where you
/// need to use this rwlock in asynchronous code as well as in synchronous code.
///
/// Returns an RAII guard which will drop the write access of this `RwLock` when dropped.
///
/// # Panics
///
/// This function panics if called within an asynchronous execution context.
///
/// - If you find yourself in an asynchronous execution context and needing
/// to call some (synchronous) function which performs one of these
/// `blocking_` operations, then consider wrapping that call inside
/// [`spawn_blocking()`][crate::runtime::Handle::spawn_blocking]
/// (or [`block_in_place()`][crate::task::block_in_place]).
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use tokio::{sync::RwLock};
///
/// #[tokio::main]
/// async fn main() {
/// let rwlock = Arc::new(RwLock::new(1));
/// let read_lock = rwlock.read().await;
///
/// let blocking_task = tokio::task::spawn_blocking({
/// let rwlock = Arc::clone(&rwlock);
/// move || {
/// // This shall block until the `read_lock` is released.
/// let mut write_lock = rwlock.blocking_write();
/// *write_lock = 2;
/// }
/// });
///
/// assert_eq!(*read_lock, 1);
/// // Release the last outstanding read lock.
/// drop(read_lock);
///
/// // Await the completion of the blocking task.
/// blocking_task.await.unwrap();
///
/// // Assert uncontended.
/// let read_lock = rwlock.try_read().unwrap();
/// assert_eq!(*read_lock, 2);
/// }
/// ```
#[track_caller]
/// Adds the key part of a new entry to the map output.
///
/// This method, together with `value`, is an alternative to `entry` that
/// can be used when the complete entry isn't known upfront. Prefer the `entry`
/// method when it's possible to use.
///
/// # Panics
///
/// `key` must be called before `value` and each call to `key` must be followed
/// by a corresponding call to `value`. Otherwise this method will panic.
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo(Vec<(String, i32)>);
///
/// impl fmt::Debug for Foo {
/// fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt.debug_map()
/// .key(&"whole").value(&self.0) // We add the "whole" entry.
/// .finish()
/// }
/// }
///
/// assert_eq!(
/// format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
/// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}",
/// );
/// ```
#[stable(feature = "debug_map_key_value", since = "1.42.0")]
/// Gets a signed 32 bit integer from `self` in big-endian byte order.
///
/// The current position is advanced by 4.
///
/// # Examples
///
/// ```
/// use bytes::Buf;
///
/// let mut buf = &b"\x08\x09\xA0\xA1 hello"[..];
/// assert_eq!(0x0809A0A1, buf.get_i32());
/// ```
///
/// # Panics
///
/// This function panics if there is not enough remaining data in `self`.
fn get_i32(&mut self) -> i32 {
/// Returns an iterator over `N` elements of the slice at a time, starting at the
/// beginning of the slice.
///
/// The chunks are array references and do not overlap. If `N` does not divide the
/// length of the slice, then the last up to `N-1` elements will be omitted and can be
/// retrieved from the `remainder` function of the iterator.
///
/// This method is the const generic equivalent of [`chunks_exact`].
///
/// # Panics
///
/// Panics if `N` is 0. This check will most probably get changed to a compile time
/// error before this method gets stabilized.
///
/// # Examples
///
/// ```
/// #![feature(array_chunks)]
/// let slice = ['l', 'o', 'r', 'e', 'm'];
/// let mut iter = slice.array_chunks();
/// assert_eq!(iter.next().unwrap(), &['l', 'o']);
/// assert_eq!(iter.next().unwrap(), &['r', 'e']);
/// assert!(iter.next().is_none());
/// assert_eq!(iter.remainder(), &['m']);
/// ```
///
/// [`chunks_exact`]: slice::chunks_exact
#[unstable(feature = "array_chunks", issue = "74985")]
/// Changes the size of the points
///
/// # Panics
///
/// Panics if `size` is a non-positive value
fn set(&mut self, ps: PointSize) -> &mut Properties {
/// This returns a `Ok(value)` for the next value in the map.
///
/// `Deserialize` implementations should typically use
/// `MapAccess::next_value` instead.
///
/// # Panics
///
/// Calling `next_value_seed` before `next_key_seed` is incorrect and is
/// allowed to panic or return bogus results.
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
/// Remove the binding at the given index.
///
/// # Panics
///
/// Panics if the index is out of range.
pub fn remove_binding(&mut self, idx: usize) -> &mut Self {
/// Sends a value, waiting until there is capacity, but only for a limited time.
///
/// Shares the same success and error conditions as [`send`], adding one more
/// condition for an unsuccessful send, which is when the provided timeout has
/// elapsed, and there is no capacity available.
///
/// [`send`]: Sender::send
///
/// # Errors
///
/// If the receive half of the channel is closed, either due to [`close`]
/// being called or the [`Receiver`] having been dropped,
/// the function returns an error. The error includes the value passed to `send`.
///
/// [`close`]: Receiver::close
/// [`Receiver`]: Receiver
///
/// # Panics
///
/// This function panics if it is called outside the context of a Tokio
/// runtime [with time enabled](crate::runtime::Builder::enable_time).
///
/// # Examples
///
/// In the following example, each call to `send_timeout` will block until the
/// previously sent value was received, unless the timeout has elapsed.
///
/// ```rust
/// use tokio::sync::mpsc;
/// use tokio::time::{sleep, Duration};
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = mpsc::channel(1);
///
/// tokio::spawn(async move {
/// for i in 0..10 {
/// if let Err(e) = tx.send_timeout(i, Duration::from_millis(100)).await {
/// println!("send error: #{:?}", e);
/// return;
/// }
/// }
/// });
///
/// while let Some(i) = rx.recv().await {
/// println!("got = {}", i);
/// sleep(Duration::from_millis(200)).await;
/// }
/// }
/// ```
#[cfg(feature = "time")]
/// Clears the entry for the given queue family index and the current thread. This does not
/// mean that the pools are dropped immediately. A pool is kept alive for as long as command
/// buffers allocated from it exist.
///
/// This has no effect if the entry was not initialized yet.
///
/// # Panics
///
/// - Panics if `queue_family_index` is not less than the number of queue families.
#[inline]
/// Blocking receive to call outside of asynchronous contexts.
///
/// # Panics
///
/// This function panics if called within an asynchronous execution
/// context.
///
/// # Examples
/// ```
/// use std::thread;
/// use tokio::sync::broadcast;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = broadcast::channel(16);
///
/// let sync_code = thread::spawn(move || {
/// assert_eq!(rx.blocking_recv(), Ok(10));
/// });
///
/// let _ = tx.send(10);
/// sync_code.join().unwrap();
/// }
/// ```
pub fn blocking_recv(&mut self) -> Result<T, RecvError> {
/// Makes a new `NaiveDateTime` from the current date, hour, minute, second and nanosecond.
///
/// The nanosecond part is allowed to exceed 1,000,000,000 in order to represent a [leap second](
/// ./struct.NaiveTime.html#leap-second-handling), but only when `sec == 59`.
///
/// # Panics
///
/// Panics on invalid hour, minute, second and/or nanosecond.
#[deprecated(since = "0.4.23", note = "use `and_hms_nano_opt()` instead")]
/// Obtain a [`Command`] given the cmd vec from [`Config`][crate::config::Config].
///
/// Behaves as described in the enum documentation.
///
/// # Panics
///
/// - Panics if `cmd` is empty.
/// - Panics if the string in the `Unix` variant is empty or only whitespace.
pub fn to_command(&self, cmd: &[String]) -> Command {
/// Converts a known non-zero `RawPid` into a `Pid`.
///
/// # Safety
///
/// `raw` must be the value of a valid Unix process ID. It must not be
/// zero.
#[inline]
/// Run all generated forward prefilter tests that pass the given
/// predicate on the given prefn.
///
/// # Safety
///
/// Callers must ensure that the given prefilter function pointer is
/// safe to call for all inputs in the current environment.
pub(crate) unsafe fn run_all_tests_filter(
/// # Safety
/// The provided pointer must point at a valid list item.
unsafe fn get_shard_id(target: NonNull<Self::Target>) -> usize;
/// Releases an exclusive lock.
///
/// # Safety
///
/// This method may only be called if an exclusive lock is held in the current context.
unsafe fn unlock_exclusive(&self);
/// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`]
/// must be used instead.
///
/// For the shared counterpart see [`as_ref`].
///
/// [`as_uninit_mut`]: NonNull::as_uninit_mut
/// [`as_ref`]: NonNull::as_ref
///
/// # Safety
///
/// When calling this method, you have to ensure that all of the following is true:
///
/// * The pointer must be properly aligned.
///
/// * It must be "dereferenceable" in the sense defined in [the module documentation].
///
/// * The pointer must point to an initialized instance of `T`.
///
/// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is
/// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data.
/// In particular, while this reference exists, the memory the pointer points to must
/// not get accessed (read or written) through any other pointer.
///
/// This applies even if the result of this method is unused!
/// (The part about being initialized is not yet fully decided, but until
/// it is, the only safe approach is to ensure that they are indeed initialized.)
/// # Examples
///
/// ```
/// use std::ptr::NonNull;
///
/// let mut x = 0u32;
/// let mut ptr = NonNull::new(&mut x).expect("null pointer");
///
/// let x_ref = unsafe { ptr.as_mut() };
/// assert_eq!(*x_ref, 0);
/// *x_ref += 2;
/// assert_eq!(*x_ref, 2);
/// ```
///
/// [the module documentation]: crate::ptr#safety
#[stable(feature = "nonnull", since = "1.25.0")]
/// Attempts to get mutable references to `N` values in the map at once, without validating that
/// the values are unique.
///
/// Returns an array of length `N` with the results of each query. `None` will be returned if
/// any of the keys are missing.
///
/// For a safe alternative see [`get_many_mut`](`HashMap::get_many_mut`).
///
/// # Safety
///
/// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
/// references are not used.
///
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
///
/// let mut libraries = HashMap::new();
/// libraries.insert("Bodleian Library".to_string(), 1602);
/// libraries.insert("Athenæum".to_string(), 1807);
/// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
/// libraries.insert("Library of Congress".to_string(), 1800);
///
/// let got = libraries.get_many_mut([
/// "Athenæum",
/// "Library of Congress",
/// ]);
/// assert_eq!(
/// got,
/// Some([
/// &mut 1807,
/// &mut 1800,
/// ]),
/// );
///
/// // Missing keys result in None
/// let got = libraries.get_many_mut([
/// "Athenæum",
/// "New York Public Library",
/// ]);
/// assert_eq!(got, None);
/// ```
pub unsafe fn get_many_unchecked_mut<Q: ?Sized, const N: usize>(
/// ### What it does
/// Checks for the doc comments of publicly visible
/// safe functions and traits and warns if there is a `# Safety` section.
///
/// ### Why is this bad?
/// Safe functions and traits are safe to implement and therefore do not
/// need to describe safety preconditions that users are required to uphold.
///
/// ### Examples
/// ```no_run
///# type Universe = ();
/// /// # Safety
/// ///
/// /// This function should not be called before the horsemen are ready.
/// pub fn start_apocalypse_but_safely(u: &mut Universe) {
/// unimplemented!();
/// }
/// ```
///
/// The function is safe, so there shouldn't be any preconditions
/// that have to be explained for safety reasons.
///
/// ```no_run
///# type Universe = ();
/// /// This function should really be documented
/// pub fn start_apocalypse(u: &mut Universe) {
/// unimplemented!();
/// }
/// ```
#[clippy::version = "1.67.0"]
/// # Safety
///
/// The vector must be on the heap
#[inline]
/// Cancel previous polled request of `Afd`.
///
/// iosb needs to be used by `poll` first for valid `cancel`.
///
/// # Unsafety
///
/// This function is unsafe due to memory of `IO_STATUS_BLOCK` still being used by `Afd` instance while `Ok(false)` (`STATUS_PENDING`).
/// Use it only with request is still being polled so that you have valid `IO_STATUS_BLOCK` to use.
/// User should NOT deallocate there overlapped value after the `cancel` to prevent double free.
pub unsafe fn cancel(&self, iosb: *mut IO_STATUS_BLOCK) -> io::Result<()> {
/// Extends `self` from an iterator of trusted len.
///
/// # Safety
/// The caller must guarantee that the iterator has a trusted len.
#[inline]
/// Frees some descriptor sets.
///
/// Note that it is not mandatory to free sets. Destroying or resetting the pool destroys all
/// the descriptor sets.
///
/// # Safety
///
/// - All elements of `descriptor_sets` must have been allocated from `self`, and not freed
/// previously.
/// - All elements of `descriptor_sets` must not be in use by the host or device.
#[inline]
/// Insert an entry into the timing wheel.
///
/// # Arguments
///
/// * `item`: The item to insert into the wheel.
///
/// # Return
///
/// Returns `Ok` when the item is successfully inserted, `Err` otherwise.
///
/// `Err(Elapsed)` indicates that `when` represents an instant that has
/// already passed. In this case, the caller should fire the timeout
/// immediately.
///
/// `Err(Invalid)` indicates an invalid `when` argument as been supplied.
///
/// # Safety
///
/// This function registers item into an intrusive linked list. The caller
/// must ensure that `item` is pinned and will not be dropped without first
/// being deregistered.
pub(crate) unsafe fn insert(
/// # Safety
///
/// If `f` writes to its `*mut *mut libc::group` parameter, then it must
/// also initialize the value pointed to by its `*mut libc::group`
/// parameter.
unsafe fn from_anything<F>(f: F) -> Result<Option<Self>>
/// Get a value at a certain index location
///
/// # Safety
///
/// This does not any bound checks. The caller needs to ensure the index is within
/// the size of the array.
pub unsafe fn value_unchecked(&self, index: usize) -> &T {
/// Shuffles the bytes in this vector according to the indices in each of
/// the corresponding lanes in `indices`.
///
/// If `i` is the index of corresponding lanes, `A` is this vector, `B` is
/// indices and `C` is the resulting vector, then `C = A[B[i]]`.
///
/// # Safety
///
/// Callers must ensure that this is okay to call in the current target for
/// the current CPU.
unsafe fn shuffle_bytes(self, indices: Self) -> Self;
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
/// i.e. when [`checked_sub`] would return `None`.
///
#[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
/// Create a UnixAddr from a raw `sockaddr_un` struct and a size. `sun_len`
/// is the size of the valid portion of the struct, excluding any trailing
/// NUL.
///
/// # Safety
/// This pair of sockaddr_un & sun_len must be a valid unix addr, which
/// means:
/// - sun_len >= offset_of(sockaddr_un, sun_path)
/// - sun_len <= sockaddr_un.sun_path.len() - offset_of(sockaddr_un, sun_path)
/// - if this is a unix addr with a pathname, sun.sun_path is a
/// fs path, not necessarily nul-terminated.
pub(crate) unsafe fn from_raw_parts(
/// Reads data of a previously serialized acceleration structure from a buffer, and
/// deserializes it back into an acceleration structure.
///
/// # Safety
///
/// - `info.src` must contain data previously serialized using
/// [`copy_acceleration_structure_to_memory`], and must have a format compatible with the
/// device (as queried by [`Device::acceleration_structure_is_compatible`]).
/// - `info.dst.size()` must be at least the size that the structure in `info.src` had before
/// it was serialized.
///
/// [`copy_acceleration_structure_to_memory`]: Self::copy_acceleration_structure_to_memory
/// [`Device::acceleration_structure_is_compatible`]: crate::device::Device::acceleration_structure_is_compatible
#[inline]
/// # Safety
///
/// Owner's own the pointer they wrap, using the pointer after dropping the Owner,
/// or creating multiple Owners from the same pointer will cause UB. Use `into_ptr` to
/// retrieve the pointer and consume the Owner without dropping the pointee.
pub unsafe fn from_raw(ptr: *mut physx_sys::PxConvexMesh) -> Option<Owner<ConvexMesh>> {
/// Creates a new `String` from a length, capacity, and pointer.
///
/// # Safety
///
/// This is highly unsafe, due to the number of invariants that aren't
/// checked:
///
/// * The memory at `ptr` needs to have been previously allocated by the
/// same allocator the standard library uses.
/// * `length` needs to be less than or equal to `capacity`.
/// * `capacity` needs to be the correct value.
///
/// Violating these may cause problems like corrupting the allocator's
/// internal data structures.
///
/// The ownership of `ptr` is effectively transferred to the
/// `String` which may then deallocate, reallocate or change the
/// contents of memory pointed to by the pointer at will. Ensure
/// that nothing else uses the pointer after calling this
/// function.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bumpalo::{Bump, collections::String};
/// use std::mem;
///
/// let b = Bump::new();
///
/// unsafe {
/// let mut s = String::from_str_in("hello", &b);
/// let ptr = s.as_mut_ptr();
/// let len = s.len();
/// let capacity = s.capacity();
///
/// mem::forget(s);
///
/// let s = String::from_raw_parts_in(ptr, len, capacity, &b);
///
/// assert_eq!(s, "hello");
/// }
/// ```
#[inline]
/// Converts a vector of bytes to a `String` without checking that the
/// string contains valid UTF-8.
///
/// See the safe version, [`from_utf8`], for more details.
///
/// [`from_utf8`]: struct.String.html#method.from_utf8
///
/// # Safety
///
/// This function is unsafe because it does not check that the bytes passed
/// to it are valid UTF-8. If this constraint is violated, it may cause
/// memory unsafety issues with future users of the `String`,
/// as it is assumed that `String`s are valid UTF-8.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bumpalo::{Bump, collections::String};
///
/// let b = Bump::new();
///
/// // some bytes, in a vector
/// let sparkle_heart = bumpalo::vec![in &b; 240, 159, 146, 150];
///
/// let sparkle_heart = unsafe {
/// String::from_utf8_unchecked(sparkle_heart)
/// };
///
/// assert_eq!("💖", sparkle_heart);
/// ```
#[inline]
/// Creates a new `Framebuffer` from a raw object handle.
///
/// # Safety
///
/// - `handle` must be a valid Vulkan object handle created from `render_pass`.
/// - `create_info` must match the info used to create the object.
#[inline]
/// Extracts the values from an array of `MaybeUninit` containers.
///
/// # Safety
///
/// It is up to the caller to guarantee that all elements of the array are
/// in an initialized state.
///
/// # Examples
///
/// ```
/// #![feature(maybe_uninit_uninit_array)]
/// #![feature(maybe_uninit_array_assume_init)]
/// use std::mem::MaybeUninit;
///
/// let mut array: [MaybeUninit<i32>; 3] = MaybeUninit::uninit_array();
/// array[0].write(0);
/// array[1].write(1);
/// array[2].write(2);
///
/// // SAFETY: Now safe as we initialised all elements
/// let array = unsafe {
/// MaybeUninit::array_assume_init(array)
/// };
///
/// assert_eq!(array, [0, 1, 2]);
/// ```
#[unstable(feature = "maybe_uninit_array_assume_init", issue = "96097")]
/// # Safety
///
/// The name is a static string. If detached, consider threading support of your allocators. Not all support
/// cross-thread events. Context is the value return from `ProfilerCallback::zone_start`.
unsafe extern "C" fn zone_end(
/// Allocates descriptor sets from the pool, one for each element in `allocate_info`.
/// Returns an iterator to the allocated sets, or an error.
///
/// The `FragmentedPool` errors often can't be prevented. If the function returns this error,
/// you should just create a new pool.
///
/// # Safety
///
/// - When the pool is dropped, the returned descriptor sets must not be in use by either the
/// host or device.
/// - If the device API version is less than 1.1, and the [`khr_maintenance1`] extension is not
/// enabled on the device, then the length of `allocate_infos` must not be greater than the
/// number of descriptor sets remaining in the pool, and the total number of descriptors of
/// each type being allocated must not be greater than the number of descriptors of that type
/// remaining in the pool.
///
/// [`khr_maintenance1`]: crate::device::DeviceExtensions::khr_maintenance1
#[inline]
/// Prepares for rehashing data in place (that is, without allocating new memory).
/// Converts all full index `control bytes` to `DELETED` and all `DELETED` control
/// bytes to `EMPTY`, i.e. performs the following conversion:
///
/// - `EMPTY` control bytes -> `EMPTY`;
/// - `DELETED` control bytes -> `EMPTY`;
/// - `FULL` control bytes -> `DELETED`.
///
/// This function does not make any changes to the `data` parts of the table,
/// or any changes to the the `items` or `growth_left` field of the table.
///
/// # Safety
///
/// You must observe the following safety rules when calling this function:
///
/// * The [`RawTableInner`] has already been allocated;
///
/// * The caller of this function must convert the `DELETED` bytes back to `FULL`
/// bytes when re-inserting them into their ideal position (which was impossible
/// to do during the first insert due to tombstones). If the caller does not do
/// this, then calling this function may result in a memory leak.
///
/// Calling this function on a table that has not been allocated results in
/// [`undefined behavior`].
///
/// See also [`Bucket::as_ptr`] method, for more information about of properly removing
/// or saving `data element` from / into the [`RawTable`] / [`RawTableInner`].
///
/// [`Bucket::as_ptr`]: Bucket::as_ptr
/// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[allow(clippy::mut_mut)]
/// Create a new finder specific to SSE2 vectors and routines without
/// checking that SSE2 is available.
///
/// # Safety
///
/// Callers must guarantee that it is safe to execute `sse2` instructions
/// in the current environment.
///
/// Note that it is a common misconception that if one compiles for an
/// `x86_64` target, then they therefore automatically have access to SSE2
/// instructions. While this is almost always the case, it isn't true in
/// 100% of cases.
#[target_feature(enable = "sse2")]
/// Sets the length of a vector.
///
/// This will explicitly set the size of the vector, without actually modifying its buffers, so
/// it is up to the caller to ensure that the vector is actually the specified size.
///
/// # Safety
///
/// `new_len <= self.capacity()` must be true, and all the elements in the range `..self.len`
/// must be initialized.
#[inline]
/// Attempts to make a temporary directory inside of `env::temp_dir()` whose
/// name will have the prefix, `prefix`. The directory and
/// everything inside it will be automatically deleted once the
/// returned `TempDir` is destroyed.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `TempDir`.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use tempfile::Builder;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_dir = Builder::new().tempdir()?;
/// # Ok(())
/// # }
/// ```
///
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir(&self) -> io::Result<TempDir> {
/// Writes an 32-bit floating point type in little-endian order to the
/// underlying writer.
///
/// Equivalent to:
///
/// ```ignore
/// async fn write_f32_le(&mut self, n: f32) -> io::Result<()>;
/// ```
///
/// It is recommended to use a buffered writer to avoid excessive
/// syscalls.
///
/// # Errors
///
/// This method returns the same errors as [`AsyncWriteExt::write_all`].
///
/// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
///
/// # Examples
///
/// Write 32-bit floating point type to a `AsyncWrite`:
///
/// ```rust
/// use tokio::io::{self, AsyncWriteExt};
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let mut writer = Vec::new();
///
/// writer.write_f32_le(f32::MIN).await?;
///
/// assert_eq!(writer, vec![0xff, 0xff, 0x7f, 0xff]);
/// Ok(())
/// }
/// ```
fn write_f32_le(&mut self, n: f32) -> WriteF32Le;
/// Tries to reserve capacity for at least `additional` more elements to be inserted
/// in the given `HashTable`. The collection may reserve more space to avoid
/// frequent reallocations.
///
/// `hasher` is called if entries need to be moved or copied to a new table.
/// This must return the same hash value that each entry was inserted with.
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an error
/// is returned.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use ahash::AHasher;
/// use hashbrown::HashTable;
/// use std::hash::{BuildHasher, BuildHasherDefault};
///
/// let mut table: HashTable<i32> = HashTable::new();
/// let hasher = BuildHasherDefault::<AHasher>::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table
/// .try_reserve(10, hasher)
/// .expect("why is the test harness OOMing on 10 bytes?");
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn try_reserve(
/// Writes an signed 128-bit integer in big-endian order to the
/// underlying writer.
///
/// Equivalent to:
///
/// ```ignore
/// async fn write_i128(&mut self, n: i128) -> io::Result<()>;
/// ```
///
/// It is recommended to use a buffered writer to avoid excessive
/// syscalls.
///
/// # Errors
///
/// This method returns the same errors as [`AsyncWriteExt::write_all`].
///
/// [`AsyncWriteExt::write_all`]: AsyncWriteExt::write_all
///
/// # Examples
///
/// Write signed 128-bit integers to a `AsyncWrite`:
///
/// ```rust
/// use tokio::io::{self, AsyncWriteExt};
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let mut writer = Vec::new();
///
/// writer.write_i128(i128::MIN).await?;
///
/// assert_eq!(writer, vec![
/// 0x80, 0, 0, 0, 0, 0, 0, 0,
/// 0, 0, 0, 0, 0, 0, 0, 0
/// ]);
/// Ok(())
/// }
/// ```
fn write_i128(&mut self, n: i128) -> WriteI128;
/// Closes the inotify instance
///
/// Closes the file descriptor referring to the inotify instance. The user
/// usually doesn't have to call this function, as the underlying inotify
/// instance is closed automatically, when [`Inotify`] is dropped.
///
/// # Errors
///
/// Directly returns the error from the call to [`close`], without adding any
/// error conditions of its own.
///
/// # Examples
///
/// ```
/// use inotify::Inotify;
///
/// let mut inotify = Inotify::init()
/// .expect("Failed to initialize an inotify instance");
///
/// inotify.close()
/// .expect("Failed to close inotify instance");
/// ```
///
/// [`Inotify`]: struct.Inotify.html
/// [`close`]: ../libc/fn.close.html
pub fn close(self) -> io::Result<()> {
/// Attempts to send data on the socket to the remote address to which it
/// was previously `connect`ed.
///
/// The [`connect`] method will connect this socket to a remote address.
/// This method will fail if the socket is not connected.
///
/// Note that on multiple calls to a `poll_*` method in the send direction,
/// only the `Waker` from the `Context` passed to the most recent call will
/// be scheduled to receive a wakeup.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the socket is not available to write
/// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`connect`]: method@Self::connect
pub fn poll_send(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
/// Serialize a datetime into an integer number of nanoseconds since the epoch or none
///
/// Intended for use with `serde`s `serialize_with` attribute.
///
/// # Errors
///
/// An `i64` with nanosecond precision can span a range of ~584 years. This function returns an
/// error on an out of range `DateTime`.
///
/// The dates that can be represented as nanoseconds are between 1677-09-21T00:12:44.0 and
/// 2262-04-11T23:47:16.854775804.
///
/// # Example:
///
/// ```rust
/// # use chrono::naive::{NaiveDate, NaiveDateTime};
/// # use serde_derive::Serialize;
/// use chrono::naive::serde::ts_nanoseconds_option::serialize as to_nano_tsopt;
/// #[derive(Serialize)]
/// struct S {
/// #[serde(serialize_with = "to_nano_tsopt")]
/// time: Option<NaiveDateTime>,
/// }
///
/// let my_s = S {
/// time: Some(
/// NaiveDate::from_ymd_opt(2018, 5, 17)
/// .unwrap()
/// .and_hms_nano_opt(02, 04, 59, 918355733)
/// .unwrap(),
/// ),
/// };
/// let as_string = serde_json::to_string(&my_s)?;
/// assert_eq!(as_string, r#"{"time":1526522699918355733}"#);
/// # Ok::<(), serde_json::Error>(())
/// ```
pub fn serialize<S>(opt: &Option<NaiveDateTime>, serializer: S) -> Result<S::Ok, S::Error>
/// Writes a buffer into this writer, advancing the buffer's internal
/// cursor.
///
/// Equivalent to:
///
/// ```ignore
/// async fn write_buf<B: Buf>(&mut self, buf: &mut B) -> io::Result<usize>;
/// ```
///
/// This function will attempt to write the entire contents of `buf`, but
/// the entire write may not succeed, or the write may also generate an
/// error. After the operation completes, the buffer's
/// internal cursor is advanced by the number of bytes written. A
/// subsequent call to `write_buf` using the **same** `buf` value will
/// resume from the point that the first call to `write_buf` completed.
/// A call to `write_buf` represents *at most one* attempt to write to any
/// wrapped object.
///
/// # Return
///
/// If the return value is `Ok(n)` then it must be guaranteed that `n <=
/// buf.len()`. A return value of `0` typically means that the
/// underlying object is no longer able to accept bytes and will likely
/// not be able to in the future as well, or that the buffer provided is
/// empty.
///
/// # Errors
///
/// Each call to `write` may generate an I/O error indicating that the
/// operation could not be completed. If an error is returned then no bytes
/// in the buffer were written to this writer.
///
/// It is **not** considered an error if the entire buffer could not be
/// written to this writer.
///
/// # Cancel safety
///
/// This method is cancellation safe in the sense that if it is used as
/// the event in a [`tokio::select!`](crate::select) statement and some
/// other branch completes first, then it is guaranteed that no data was
/// written to this `AsyncWrite`.
///
/// # Examples
///
/// [`File`] implements [`AsyncWrite`] and [`Cursor`]`<&[u8]>` implements [`Buf`]:
///
/// [`File`]: crate::fs::File
/// [`Buf`]: bytes::Buf
/// [`Cursor`]: std::io::Cursor
///
/// ```no_run
/// use tokio::io::{self, AsyncWriteExt};
/// use tokio::fs::File;
///
/// use bytes::Buf;
/// use std::io::Cursor;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let mut file = File::create("foo.txt").await?;
/// let mut buffer = Cursor::new(b"data to write");
///
/// // Loop until the entire contents of the buffer are written to
/// // the file.
/// while buffer.has_remaining() {
/// // Writes some prefix of the byte string, not necessarily
/// // all of it.
/// file.write_buf(&mut buffer).await?;
/// }
///
/// Ok(())
/// }
/// ```
fn write_buf<'a, B>(&'a mut self, src: &'a mut B) -> WriteBuf<'a, Self, B>
/// Attempts to make a temporary directory with the specified prefix inside of
/// `env::temp_dir()`. The directory and everything inside it will be automatically
/// deleted once the returned `TempDir` is destroyed.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::{self, File};
/// use std::io::Write;
/// use tempfile::TempDir;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// // Create a directory inside of the current directory
/// let tmp_dir = TempDir::with_prefix("foo-")?;
/// let tmp_name = tmp_dir.path().file_name().unwrap().to_str().unwrap();
/// assert!(tmp_name.starts_with("foo-"));
/// # Ok(())
/// # }
/// ```
pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> io::Result<TempDir> {
/// Send a form body.
///
/// Sets the body to the url encoded serialization of the passed value,
/// and also sets the `Content-Type: application/x-www-form-urlencoded`
/// header.
///
/// ```rust
/// # use reqwest::Error;
/// # use std::collections::HashMap;
/// #
/// # async fn run() -> Result<(), Error> {
/// let mut params = HashMap::new();
/// params.insert("lang", "rust");
///
/// let client = reqwest::Client::new();
/// let res = client.post("http://httpbin.org")
/// .form(¶ms)
/// .send()
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// This method fails if the passed value cannot be serialized into
/// url encoded format
pub fn form<T: Serialize + ?Sized>(mut self, form: &T) -> RequestBuilder {
/// Returns a mutable reference to the underlying data.
///
/// Since this call borrows the lock mutably, no actual locking needs to take place.
///
/// # Errors
///
/// This method will return an error if the lock is poisoned. A lock gets poisoned when a write
/// operation panics.
///
/// # Examples
///
/// ```
/// use crossbeam_utils::sync::ShardedLock;
///
/// let mut lock = ShardedLock::new(0);
/// *lock.get_mut().unwrap() = 10;
/// assert_eq!(*lock.read().unwrap(), 10);
/// ```
pub fn get_mut(&mut self) -> LockResult<&mut T> {
/// Reads an unsigned 64-bit integer in big-endian order from the
/// underlying reader.
///
/// Equivalent to:
///
/// ```ignore
/// async fn read_u64(&mut self) -> io::Result<u64>;
/// ```
///
/// It is recommended to use a buffered reader to avoid excessive
/// syscalls.
///
/// # Errors
///
/// This method returns the same errors as [`AsyncReadExt::read_exact`].
///
/// [`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact
///
/// # Examples
///
/// Read unsigned 64-bit big-endian integers from a `AsyncRead`:
///
/// ```rust
/// use tokio::io::{self, AsyncReadExt};
///
/// use std::io::Cursor;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let mut reader = Cursor::new(vec![
/// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83
/// ]);
///
/// assert_eq!(918733457491587, reader.read_u64().await?);
/// Ok(())
/// }
/// ```
fn read_u64(&mut self) -> ReadU64;
/// Polls for read readiness.
///
/// If the unix stream is not currently ready for reading, this method will
/// store a clone of the `Waker` from the provided `Context`. When the unix
/// stream becomes ready for reading, `Waker::wake` will be called on the
/// waker.
///
/// Note that on multiple calls to `poll_read_ready` or `poll_read`, only
/// the `Waker` from the `Context` passed to the most recent call is
/// scheduled to receive a wakeup. (However, `poll_write_ready` retains a
/// second, independent waker.)
///
/// This function is intended for cases where creating and pinning a future
/// via [`readable`] is not feasible. Where possible, using [`readable`] is
/// preferred, as this supports polling from multiple tasks at once.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the unix stream is not ready for reading.
/// * `Poll::Ready(Ok(()))` if the unix stream is ready for reading.
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`readable`]: method@Self::readable
pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
/// Construct a [`CustomFormat`].
///
/// # Errors
///
/// Return an error if:
/// - The "decimal" is longer than 8 bytes
/// - The "infinity sign" is longer than 128 bytes
/// - The "minus sign" is longer than 8 bytes
/// - The "nan symbol" is longer than 64 bytes
/// - The "plus sign" is longer than 8 bytes
/// - The "separator" is longer than 8 bytes
///
/// [`CustomFormat`]: struct.CustomFormat.html
pub fn build(self) -> Result<CustomFormat, Error> {
/// Makes a new [`DateTime<Utc>`] from the number of non-leap milliseconds
/// since January 1, 1970 0:00:00.000 UTC (aka "UNIX timestamp").
///
/// This is guaranteed to round-trip with regard to [`timestamp_millis`](DateTime::timestamp_millis).
///
/// If you need to create a `DateTime` with a [`TimeZone`] different from [`Utc`], use
/// [`TimeZone::timestamp_millis_opt`] or [`DateTime::with_timezone`].
///
/// # Errors
///
/// Returns `None` on out-of-range number of milliseconds, otherwise returns `Some(DateTime {...})`.
///
/// # Example
///
/// ```
/// use chrono::{DateTime, Utc};
///
/// let dt: DateTime<Utc> = DateTime::<Utc>::from_timestamp_millis(947638923004).expect("invalid timestamp");
///
/// assert_eq!(dt.to_string(), "2000-01-12 01:02:03.004 UTC");
/// assert_eq!(DateTime::from_timestamp_millis(dt.timestamp_millis()).unwrap(), dt);
/// ```
#[inline]
/// Reads the metadata for this entry.
///
/// This function will traverse symbolic links to read the metadata.
///
/// If you want to read metadata without following symbolic links, use [`symlink_metadata()`]
/// instead.
///
/// # Errors
///
/// An error will be returned in the following situations:
///
/// * This entry does not point to an existing file or directory anymore.
/// * The current process lacks permissions to read the metadata.
/// * Some other I/O error occurred.
///
/// # Examples
///
/// ```no_run
/// use futures_lite::stream::StreamExt;
///
/// # futures_lite::future::block_on(async {
/// let mut dir = async_fs::read_dir(".").await?;
///
/// while let Some(entry) = dir.try_next().await? {
/// println!("{:?}", entry.metadata().await?);
/// }
/// # std::io::Result::Ok(()) });
/// ```
pub async fn metadata(&self) -> io::Result<Metadata> {
/// Creates a readable and executable memory map backed by a file.
///
/// # Errors
///
/// This method returns an error when the underlying system call fails, which can happen for a
/// variety of reasons, such as when the file is not open with read permissions.
pub unsafe fn map_exec<T: MmapAsRawDesc>(&self, file: T) -> Result<Mmap> {
/// Reads the exact number of bytes required to fill `buf`.
///
/// Equivalent to:
///
/// ```ignore
/// async fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<usize>;
/// ```
///
/// This function reads as many bytes as necessary to completely fill
/// the specified buffer `buf`.
///
/// # Errors
///
/// If the operation encounters an "end of file" before completely
/// filling the buffer, it returns an error of the kind
/// [`ErrorKind::UnexpectedEof`]. The contents of `buf` are unspecified
/// in this case.
///
/// If any other read error is encountered then the operation
/// immediately returns. The contents of `buf` are unspecified in this
/// case.
///
/// If this operation returns an error, it is unspecified how many bytes
/// it has read, but it will never read more than would be necessary to
/// completely fill the buffer.
///
/// # Examples
///
/// [`File`][crate::fs::File]s implement `Read`:
///
/// ```no_run
/// use tokio::fs::File;
/// use tokio::io::{self, AsyncReadExt};
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let mut f = File::open("foo.txt").await?;
/// let mut buffer = [0; 10];
///
/// // read exactly 10 bytes
/// f.read_exact(&mut buffer).await?;
/// Ok(())
/// }
/// ```
///
/// [`ErrorKind::UnexpectedEof`]: std::io::ErrorKind::UnexpectedEof
fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self>
/// Tries to reserve capacity for at least `additional` more elements to be inserted
/// in the given `HashTable`. The collection may reserve more space to avoid
/// frequent reallocations.
///
/// `hasher` is called if entries need to be moved or copied to a new table.
/// This must return the same hash value that each entry was inserted with.
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an error
/// is returned.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "nightly")]
/// # fn test() {
/// use ahash::AHasher;
/// use hashbrown::HashTable;
/// use std::hash::{BuildHasher, BuildHasherDefault};
///
/// let mut table: HashTable<i32> = HashTable::new();
/// let hasher = BuildHasherDefault::<AHasher>::default();
/// let hasher = |val: &_| hasher.hash_one(val);
/// table
/// .try_reserve(10, hasher)
/// .expect("why is the test harness OOMing on 10 bytes?");
/// # }
/// # fn main() {
/// # #[cfg(feature = "nightly")]
/// # test()
/// # }
/// ```
pub fn try_reserve(
/// Consumes this decoder, flushing the output stream.
///
/// This will flush the underlying data stream and then return the contained
/// writer if the flush succeeded.
///
/// Note that this function may not be suitable to call in a situation where
/// the underlying stream is an asynchronous I/O stream. To finish a stream
/// the `try_finish` (or `shutdown`) method should be used instead. To
/// re-acquire ownership of a stream it is safe to call this method after
/// `try_finish` or `shutdown` has returned `Ok`.
///
/// # Errors
///
/// This function will perform I/O to complete this stream, and any I/O
/// errors which occur will be returned from this function.
pub fn finish(mut self) -> io::Result<W> {
/// Parse format string into a `Vec` of formatting [`Item`]'s.
///
/// If you need to format or parse multiple values with the same format string, it is more
/// efficient to convert it to a `Vec` of formatting [`Item`]'s than to re-parse the format
/// string on every use.
///
/// The `format_with_items` methods on [`DateTime`], [`NaiveDateTime`], [`NaiveDate`] and
/// [`NaiveTime`] accept the result for formatting. [`format::parse()`] can make use of it for
/// parsing.
///
/// [`DateTime`]: crate::DateTime::format_with_items
/// [`NaiveDateTime`]: crate::NaiveDateTime::format_with_items
/// [`NaiveDate`]: crate::NaiveDate::format_with_items
/// [`NaiveTime`]: crate::NaiveTime::format_with_items
/// [`format::parse()`]: crate::format::parse()
///
/// # Errors
///
/// Returns an error if the format string contains an invalid or unrecognized formatting
/// specifier.
///
/// # Example
///
/// ```
/// use chrono::format::{parse, Parsed, StrftimeItems};
/// use chrono::NaiveDate;
///
/// let fmt_items = StrftimeItems::new("%e %b %Y %k.%M").parse()?;
/// let datetime = NaiveDate::from_ymd_opt(2023, 7, 11).unwrap().and_hms_opt(9, 0, 0).unwrap();
///
/// // Formatting
/// assert_eq!(
/// datetime.format_with_items(fmt_items.as_slice().iter()).to_string(),
/// "11 Jul 2023 9.00"
/// );
///
/// // Parsing
/// let mut parsed = Parsed::new();
/// parse(&mut parsed, "11 Jul 2023 9.00", fmt_items.as_slice().iter())?;
/// let parsed_dt = parsed.to_naive_datetime_with_offset(0)?;
/// assert_eq!(parsed_dt, datetime);
/// # Ok::<(), chrono::ParseError>(())
/// ```
#[cfg(any(feature = "alloc", feature = "std"))]
/// Reads an unsigned 128-bit integer in little-endian order from the
/// underlying reader.
///
/// Equivalent to:
///
/// ```ignore
/// async fn read_u128_le(&mut self) -> io::Result<u128>;
/// ```
///
/// It is recommended to use a buffered reader to avoid excessive
/// syscalls.
///
/// # Errors
///
/// This method returns the same errors as [`AsyncReadExt::read_exact`].
///
/// [`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact
///
/// # Examples
///
/// Read unsigned 128-bit little-endian integers from a `AsyncRead`:
///
/// ```rust
/// use tokio::io::{self, AsyncReadExt};
///
/// use std::io::Cursor;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let mut reader = Cursor::new(vec![
/// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83,
/// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83
/// ]);
///
/// assert_eq!(174826588484952389081207917399662330624, reader.read_u128_le().await?);
/// Ok(())
/// }
/// ```
fn read_u128_le(&mut self) -> ReadU128Le;
/// Opens a file at `path` with the options specified by `self`.
///
/// This is an async version of [`std::fs::OpenOptions::open`][std]
///
/// [std]: std::fs::OpenOptions::open
///
/// # Errors
///
/// This function will return an error under a number of different
/// circumstances. Some of these error conditions are listed here, together
/// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
/// the compatibility contract of the function, especially the `Other` kind
/// might change to more specific kinds in the future.
///
/// * [`NotFound`]: The specified file does not exist and neither `create`
/// or `create_new` is set.
/// * [`NotFound`]: One of the directory components of the file path does
/// not exist.
/// * [`PermissionDenied`]: The user lacks permission to get the specified
/// access rights for the file.
/// * [`PermissionDenied`]: The user lacks permission to open one of the
/// directory components of the specified path.
/// * [`AlreadyExists`]: `create_new` was specified and the file already
/// exists.
/// * [`InvalidInput`]: Invalid combinations of open options (truncate
/// without write access, no access mode set, etc.).
/// * [`Other`]: One of the directory components of the specified file path
/// was not, in fact, a directory.
/// * [`Other`]: Filesystem-level errors: full disk, write permission
/// requested on a read-only file system, exceeded disk quota, too many
/// open files, too long filename, too many symbolic links in the
/// specified path (Unix-like systems only), etc.
///
/// # Examples
///
/// ```no_run
/// use tokio::fs::OpenOptions;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let file = OpenOptions::new().open("foo.txt").await?;
/// Ok(())
/// }
/// ```
///
/// [`ErrorKind`]: std::io::ErrorKind
/// [`AlreadyExists`]: std::io::ErrorKind::AlreadyExists
/// [`InvalidInput`]: std::io::ErrorKind::InvalidInput
/// [`NotFound`]: std::io::ErrorKind::NotFound
/// [`Other`]: std::io::ErrorKind::Other
/// [`PermissionDenied`]: std::io::ErrorKind::PermissionDenied
pub async fn open(&self, path: impl AsRef<Path>) -> io::Result<File> {
/// Constructs an [`SeparatorStr`], ensuring that the length is less than the maximum for
/// a separator (8 bytes).
///
/// # Errors
///
/// Returns an error if the provided `&str`'s length is more than 8 bytes.
///
/// [`SeparatorStr`]: struct.SeparatorStr.html
pub fn new(s: &'a str) -> Result<SeparatorStr<'a>, Error> {
/// Returns true if and only if this regex matches the given haystack.
///
/// In the case of a backtracking regex engine, and unlike most other
/// regex engines in this crate, short circuiting isn't practical. However,
/// this routine may still be faster because it instructs backtracking to
/// not keep track of any capturing groups.
///
/// # Errors
///
/// This routine only errors if the search could not complete. For this
/// backtracking regex engine, this only occurs when the haystack length
/// exceeds [`BoundedBacktracker::max_haystack_len`].
///
/// When a search cannot complete, callers cannot know whether a match
/// exists or not.
///
/// # Example
///
/// ```
/// use regex_automata::nfa::thompson::backtrack::BoundedBacktracker;
///
/// let re = BoundedBacktracker::new("foo[0-9]+bar")?;
/// let mut cache = re.create_cache();
///
/// assert!(re.try_is_match(&mut cache, "foo12345bar")?);
/// assert!(!re.try_is_match(&mut cache, "foobar")?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Example: consistency with search APIs
///
/// `is_match` is guaranteed to return `true` whenever `find` returns a
/// match. This includes searches that are executed entirely within a
/// codepoint:
///
/// ```
/// use regex_automata::{
/// nfa::thompson::backtrack::BoundedBacktracker,
/// Input,
/// };
///
/// let re = BoundedBacktracker::new("a*")?;
/// let mut cache = re.create_cache();
///
/// assert!(!re.try_is_match(&mut cache, Input::new("☃").span(1..2))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Notice that when UTF-8 mode is disabled, then the above reports a
/// match because the restriction against zero-width matches that split a
/// codepoint has been lifted:
///
/// ```
/// use regex_automata::{
/// nfa::thompson::{backtrack::BoundedBacktracker, NFA},
/// Input,
/// };
///
/// let re = BoundedBacktracker::builder()
/// .thompson(NFA::config().utf8(false))
/// .build("a*")?;
/// let mut cache = re.create_cache();
///
/// assert!(re.try_is_match(&mut cache, Input::new("☃").span(1..2))?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[inline]
/// Makes a new value with the year number changed, while keeping the same month and day.
///
/// This method assumes you want to work on the date as a year-month-day value. Don't use it if
/// you want the ordinal to stay the same after changing the year, of if you want the week and
/// weekday values to stay the same.
///
/// # Errors
///
/// Returns `None` when:
///
/// - The resulting date does not exist (February 29 in a non-leap year).
/// - The year is out of range for [`NaiveDate`].
/// - In case of [`DateTime<Tz>`] if the resulting date and time fall within a timezone
/// transition such as from DST to standard time.
///
/// [`NaiveDate`]: crate::NaiveDate
/// [`DateTime<Tz>`]: crate::DateTime
///
/// # Examples
///
/// ```
/// use chrono::{Datelike, NaiveDate};
///
/// assert_eq!(
/// NaiveDate::from_ymd_opt(2020, 5, 13).unwrap().with_year(2023).unwrap(),
/// NaiveDate::from_ymd_opt(2023, 5, 13).unwrap()
/// );
/// // Resulting date 2023-02-29 does not exist:
/// assert!(NaiveDate::from_ymd_opt(2020, 2, 29).unwrap().with_year(2023).is_none());
///
/// // Don't use `with_year` if you want the ordinal date to stay the same:
/// assert_ne!(
/// NaiveDate::from_yo_opt(2020, 100).unwrap().with_year(2023).unwrap(),
/// NaiveDate::from_yo_opt(2023, 100).unwrap() // result is 2023-101
/// );
/// ```
fn with_year(&self, year: i32) -> Option<Self>;
/// Reads an unsigned 8 bit integer from the underlying reader.
///
/// Equivalent to:
///
/// ```ignore
/// async fn read_u8(&mut self) -> io::Result<u8>;
/// ```
///
/// It is recommended to use a buffered reader to avoid excessive
/// syscalls.
///
/// # Errors
///
/// This method returns the same errors as [`AsyncReadExt::read_exact`].
///
/// [`AsyncReadExt::read_exact`]: AsyncReadExt::read_exact
///
/// # Examples
///
/// Read unsigned 8 bit integers from an `AsyncRead`:
///
/// ```rust
/// use tokio::io::{self, AsyncReadExt};
///
/// use std::io::Cursor;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let mut reader = Cursor::new(vec![2, 5]);
///
/// assert_eq!(2, reader.read_u8().await?);
/// assert_eq!(5, reader.read_u8().await?);
///
/// Ok(())
/// }
/// ```
fn read_u8(&mut self) -> ReadU8;
/// Creates a new encoder, using the specified compression level and pre-trained
/// dictionary, which will read uncompressed data from the given stream and emit a
/// compressed stream.
///
/// Dictionaries provide better compression ratios for small files, but are required to
/// be present during decompression.
///
/// # Errors
///
/// Returns error when `dictionary` is not valid.
pub fn with_dict(inner: $inner, level: crate::Level, dictionary: &[u8]) -> ::std::io::Result<Self> {
/// Sends data on the socket to the socket's peer.
///
/// # Cancel safety
///
/// This method is cancel safe. If `send` is used as the event in a
/// [`tokio::select!`](crate::select) statement and some other branch
/// completes first, then it is guaranteed that the message was not sent.
///
/// # Examples
/// ```
/// # use std::error::Error;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn Error>> {
/// use tokio::net::UnixDatagram;
///
/// // Create the pair of sockets
/// let (sock1, sock2) = UnixDatagram::pair()?;
///
/// // Since the sockets are paired, the paired send/recv
/// // functions can be used
/// let bytes = b"hello world";
/// sock1.send(bytes).await?;
///
/// let mut buff = vec![0u8; 24];
/// let size = sock2.recv(&mut buff).await?;
///
/// let dgram = &buff[..size];
/// assert_eq!(dgram, bytes);
///
/// # Ok(())
/// # }
/// ```
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
/// Receives data from the socket.
///
/// # Cancel safety
///
/// This method is cancel safe. If `recv_from` is used as the event in a
/// [`tokio::select!`](crate::select) statement and some other branch
/// completes first, it is guaranteed that no messages were received on this
/// socket.
///
/// # Examples
/// ```
/// # use std::error::Error;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn Error>> {
/// use tokio::net::UnixDatagram;
/// use tempfile::tempdir;
///
/// // We use a temporary directory so that the socket
/// // files left by the bound sockets will get cleaned up.
/// let tmp = tempdir()?;
///
/// // Bind each socket to a filesystem path
/// let tx_path = tmp.path().join("tx");
/// let tx = UnixDatagram::bind(&tx_path)?;
/// let rx_path = tmp.path().join("rx");
/// let rx = UnixDatagram::bind(&rx_path)?;
///
/// let bytes = b"hello world";
/// tx.send_to(bytes, &rx_path).await?;
///
/// let mut buf = vec![0u8; 24];
/// let (size, addr) = rx.recv_from(&mut buf).await?;
///
/// let dgram = &buf[..size];
/// assert_eq!(dgram, bytes);
/// assert_eq!(addr.as_pathname().unwrap(), &tx_path);
///
/// # Ok(())
/// # }
/// ```
pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
/// Waits for channel capacity. Once capacity to send one message is
/// available, it is reserved for the caller.
///
/// If the channel is full, the function waits for the number of unreceived
/// messages to become less than the channel capacity. Capacity to send one
/// message is reserved for the caller. A [`Permit`] is returned to track
/// the reserved capacity. The [`send`] function on [`Permit`] consumes the
/// reserved capacity.
///
/// Dropping [`Permit`] without sending a message releases the capacity back
/// to the channel.
///
/// [`Permit`]: Permit
/// [`send`]: Permit::send
///
/// # Cancel safety
///
/// This channel uses a queue to ensure that calls to `send` and `reserve`
/// complete in the order they were requested. Cancelling a call to
/// `reserve` makes you lose your place in the queue.
///
/// # Examples
///
/// ```
/// use tokio::sync::mpsc;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = mpsc::channel(1);
///
/// // Reserve capacity
/// let permit = tx.reserve().await.unwrap();
///
/// // Trying to send directly on the `tx` will fail due to no
/// // available capacity.
/// assert!(tx.try_send(123).is_err());
///
/// // Sending on the permit succeeds
/// permit.send(456);
///
/// // The value sent on the permit is received
/// assert_eq!(rx.recv().await.unwrap(), 456);
/// }
/// ```
pub async fn reserve(&self) -> Result<Permit<'_, T>, SendError<()>> {
/// Waits for any of the requested ready states.
///
/// This function is usually paired with `try_recv()` or `try_send()`. It
/// can be used to concurrently `recv` / `send` to the same socket on a single
/// task without splitting the socket.
///
/// The function may complete without the socket being ready. This is a
/// false-positive and attempting an operation will return with
/// `io::ErrorKind::WouldBlock`. The function can also return with an empty
/// [`Ready`] set, so you should always check the returned value and possibly
/// wait again if the requested states are not set.
///
/// # Cancel safety
///
/// This method is cancel safe. Once a readiness event occurs, the method
/// will continue to return immediately until the readiness event is
/// consumed by an attempt to read or write that fails with `WouldBlock` or
/// `Poll::Pending`.
///
/// # Examples
///
/// Concurrently receive from and send to the socket on the same task
/// without splitting.
///
/// ```no_run
/// use tokio::io::{self, Interest};
/// use tokio::net::UdpSocket;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
/// socket.connect("127.0.0.1:8081").await?;
///
/// loop {
/// let ready = socket.ready(Interest::READABLE | Interest::WRITABLE).await?;
///
/// if ready.is_readable() {
/// // The buffer is **not** included in the async task and will only exist
/// // on the stack.
/// let mut data = [0; 1024];
/// match socket.try_recv(&mut data[..]) {
/// Ok(n) => {
/// println!("received {:?}", &data[..n]);
/// }
/// // False-positive, continue
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
/// Err(e) => {
/// return Err(e);
/// }
/// }
/// }
///
/// if ready.is_writable() {
/// // Write some data
/// match socket.try_send(b"hello world") {
/// Ok(n) => {
/// println!("sent {} bytes", n);
/// }
/// // False-positive, continue
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
/// Err(e) => {
/// return Err(e);
/// }
/// }
/// }
/// }
/// }
/// ```
pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
/// Waits for the socket to become readable.
///
/// This function is equivalent to `ready(Interest::READABLE)` and is usually
/// paired with `try_read()`.
///
/// This function is also equivalent to [`TcpStream::ready`].
///
/// # Cancel safety
///
/// This method is cancel safe. Once a readiness event occurs, the method
/// will continue to return immediately until the readiness event is
/// consumed by an attempt to read that fails with `WouldBlock` or
/// `Poll::Pending`.
pub async fn readable(&self) -> io::Result<()> {
/// Accepts a new incoming connection to this listener.
///
/// # Cancel safety
///
/// This method is cancel safe. If the method is used as the event in a
/// [`tokio::select!`](crate::select) statement and some other branch
/// completes first, then it is guaranteed that no new connections were
/// accepted by this method.
pub async fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
/// Receives the next value for this receiver.
///
/// This method returns `None` if the channel has been closed and there are
/// no remaining messages in the channel's buffer. This indicates that no
/// further values can ever be received from this `Receiver`. The channel is
/// closed when all senders have been dropped, or when [`close`] is called.
///
/// If there are no messages in the channel's buffer, but the channel has
/// not yet been closed, this method will sleep until a message is sent or
/// the channel is closed.
///
/// # Cancel safety
///
/// This method is cancel safe. If `recv` is used as the event in a
/// [`tokio::select!`](crate::select) statement and some other branch
/// completes first, it is guaranteed that no messages were received on this
/// channel.
///
/// [`close`]: Self::close
///
/// # Examples
///
/// ```
/// use tokio::sync::mpsc;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = mpsc::unbounded_channel();
///
/// tokio::spawn(async move {
/// tx.send("hello").unwrap();
/// });
///
/// assert_eq!(Some("hello"), rx.recv().await);
/// assert_eq!(None, rx.recv().await);
/// }
/// ```
///
/// Values are buffered:
///
/// ```
/// use tokio::sync::mpsc;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = mpsc::unbounded_channel();
///
/// tx.send("hello").unwrap();
/// tx.send("world").unwrap();
///
/// assert_eq!(Some("hello"), rx.recv().await);
/// assert_eq!(Some("world"), rx.recv().await);
/// }
/// ```
pub async fn recv(&mut self) -> Option<T> {
/// Locks this `RwLock` with exclusive write access, causing the current
/// task to yield until the lock has been acquired.
///
/// The calling task will yield while other writers or readers currently
/// have access to the lock.
///
/// This method is identical to [`RwLock::write`], except that the returned
/// guard references the `RwLock` with an [`Arc`] rather than by borrowing
/// it. Therefore, the `RwLock` must be wrapped in an `Arc` to call this
/// method, and the guard will live for the `'static` lifetime, as it keeps
/// the `RwLock` alive by holding an `Arc`.
///
/// Returns an RAII guard which will drop the write access of this `RwLock`
/// when dropped.
///
/// # Cancel safety
///
/// This method uses a queue to fairly distribute locks in the order they
/// were requested. Cancelling a call to `write_owned` makes you lose your
/// place in the queue.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use tokio::sync::RwLock;
///
/// #[tokio::main]
/// async fn main() {
/// let lock = Arc::new(RwLock::new(1));
///
/// let mut n = lock.write_owned().await;
/// *n = 2;
///}
/// ```
pub async fn write_owned(self: Arc<Self>) -> OwnedRwLockWriteGuard<T> {
/// Reads the exact number of bytes required to fill `buf`.
///
/// Equivalent to:
///
/// ```ignore
/// async fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<usize>;
/// ```
///
/// This function reads as many bytes as necessary to completely fill
/// the specified buffer `buf`.
///
/// # Errors
///
/// If the operation encounters an "end of file" before completely
/// filling the buffer, it returns an error of the kind
/// [`ErrorKind::UnexpectedEof`]. The contents of `buf` are unspecified
/// in this case.
///
/// If any other read error is encountered then the operation
/// immediately returns. The contents of `buf` are unspecified in this
/// case.
///
/// If this operation returns an error, it is unspecified how many bytes
/// it has read, but it will never read more than would be necessary to
/// completely fill the buffer.
///
/// # Cancel safety
///
/// This method is not cancellation safe. If the method is used as the
/// event in a [`tokio::select!`](crate::select) statement and some
/// other branch completes first, then some data may already have been
/// read into `buf`.
///
/// # Examples
///
/// [`File`][crate::fs::File]s implement `Read`:
///
/// ```no_run
/// use tokio::fs::File;
/// use tokio::io::{self, AsyncReadExt};
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let mut f = File::open("foo.txt").await?;
/// let len = 10;
/// let mut buffer = vec![0; len];
///
/// // read exactly 10 bytes
/// f.read_exact(&mut buffer).await?;
/// Ok(())
/// }
/// ```
///
/// [`ErrorKind::UnexpectedEof`]: std::io::ErrorKind::UnexpectedEof
fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self>
/// Waits for the socket to become readable.
///
/// This function is equivalent to `ready(Interest::READABLE)` and is usually
/// paired with `try_read()`.
///
/// This function is also equivalent to [`TcpStream::ready`].
///
/// # Cancel safety
///
/// This method is cancel safe. Once a readiness event occurs, the method
/// will continue to return immediately until the readiness event is
/// consumed by an attempt to read that fails with `WouldBlock` or
/// `Poll::Pending`.
pub async fn readable(&self) -> io::Result<()> {
/// Waits for any of the requested ready states.
///
/// This function is usually paired with `try_read()` or `try_write()`. It
/// can be used to concurrently read / write to the same socket on a single
/// task without splitting the socket.
///
/// The function may complete without the socket being ready. This is a
/// false-positive and attempting an operation will return with
/// `io::ErrorKind::WouldBlock`. The function can also return with an empty
/// [`Ready`] set, so you should always check the returned value and possibly
/// wait again if the requested states are not set.
///
/// This function is equivalent to [`TcpStream::ready`].
///
/// # Cancel safety
///
/// This method is cancel safe. Once a readiness event occurs, the method
/// will continue to return immediately until the readiness event is
/// consumed by an attempt to read or write that fails with `WouldBlock` or
/// `Poll::Pending`.
pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
/// Completes when the receiver has dropped.
///
/// This allows the producers to get notified when interest in the produced
/// values is canceled and immediately stop doing work.
///
/// # Cancel safety
///
/// This method is cancel safe. Once the channel is closed, it stays closed
/// forever and all future calls to `closed` will return immediately.
///
/// # Examples
///
/// ```
/// use tokio::sync::mpsc;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx1, rx) = mpsc::unbounded_channel::<()>();
/// let tx2 = tx1.clone();
/// let tx3 = tx1.clone();
/// let tx4 = tx1.clone();
/// let tx5 = tx1.clone();
/// tokio::spawn(async move {
/// drop(rx);
/// });
///
/// futures::join!(
/// tx1.closed(),
/// tx2.closed(),
/// tx3.closed(),
/// tx4.closed(),
/// tx5.closed()
/// );
//// println!("Receiver dropped");
/// }
/// ```
pub async fn closed(&self) {
/// Acquires a permit from the semaphore.
///
/// If the semaphore has been closed, this returns an [`AcquireError`].
/// Otherwise, this returns a [`SemaphorePermit`] representing the
/// acquired permit.
///
/// # Cancel safety
///
/// This method uses a queue to fairly distribute permits in the order they
/// were requested. Cancelling a call to `acquire` makes you lose your place
/// in the queue.
///
/// # Examples
///
/// ```
/// use tokio::sync::Semaphore;
///
/// #[tokio::main]
/// async fn main() {
/// let semaphore = Semaphore::new(2);
///
/// let permit_1 = semaphore.acquire().await.unwrap();
/// assert_eq!(semaphore.available_permits(), 1);
///
/// let permit_2 = semaphore.acquire().await.unwrap();
/// assert_eq!(semaphore.available_permits(), 0);
///
/// drop(permit_1);
/// assert_eq!(semaphore.available_permits(), 1);
/// }
/// ```
///
/// [`AcquireError`]: crate::sync::AcquireError
/// [`SemaphorePermit`]: crate::sync::SemaphorePermit
pub async fn acquire(&self) -> Result<SemaphorePermit<'_>, AcquireError> {
/// Waits for channel capacity. Once capacity to send one message is
/// available, it is reserved for the caller.
///
/// If the channel is full, the function waits for the number of unreceived
/// messages to become less than the channel capacity. Capacity to send one
/// message is reserved for the caller. A [`Permit`] is returned to track
/// the reserved capacity. The [`send`] function on [`Permit`] consumes the
/// reserved capacity.
///
/// Dropping [`Permit`] without sending a message releases the capacity back
/// to the channel.
///
/// [`Permit`]: Permit
/// [`send`]: Permit::send
///
/// # Cancel safety
///
/// This channel uses a queue to ensure that calls to `send` and `reserve`
/// complete in the order they were requested. Cancelling a call to
/// `reserve` makes you lose your place in the queue.
///
/// # Examples
///
/// ```
/// use tokio::sync::mpsc;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, mut rx) = mpsc::channel(1);
///
/// // Reserve capacity
/// let permit = tx.reserve().await.unwrap();
///
/// // Trying to send directly on the `tx` will fail due to no
/// // available capacity.
/// assert!(tx.try_send(123).is_err());
///
/// // Sending on the permit succeeds
/// permit.send(456);
///
/// // The value sent on the permit is received
/// assert_eq!(rx.recv().await.unwrap(), 456);
/// }
/// ```
pub async fn reserve(&self) -> Result<Permit<'_, T>, SendError<()>> {
/// Locks this mutex, causing the current task to yield until the lock has
/// been acquired. When the lock has been acquired, this returns an
/// [`OwnedMutexGuard`].
///
/// If the mutex is available to be acquired immediately, then this call
/// will typically not yield to the runtime. However, this is not guaranteed
/// under all circumstances.
///
/// This method is identical to [`Mutex::lock`], except that the returned
/// guard references the `Mutex` with an [`Arc`] rather than by borrowing
/// it. Therefore, the `Mutex` must be wrapped in an `Arc` to call this
/// method, and the guard will live for the `'static` lifetime, as it keeps
/// the `Mutex` alive by holding an `Arc`.
///
/// # Cancel safety
///
/// This method uses a queue to fairly distribute locks in the order they
/// were requested. Cancelling a call to `lock_owned` makes you lose your
/// place in the queue.
///
/// # Examples
///
/// ```
/// use tokio::sync::Mutex;
/// use std::sync::Arc;
///
/// #[tokio::main]
/// async fn main() {
/// let mutex = Arc::new(Mutex::new(1));
///
/// let mut n = mutex.clone().lock_owned().await;
/// *n = 2;
/// }
/// ```
///
/// [`Arc`]: std::sync::Arc
pub async fn lock_owned(self: Arc<Self>) -> OwnedMutexGuard<T> {
/// Locks this mutex, causing the current task to yield until the lock has
/// been acquired. When the lock has been acquired, function returns a
/// [`MutexGuard`].
///
/// # Cancel safety
///
/// This method uses a queue to fairly distribute locks in the order they
/// were requested. Cancelling a call to `lock` makes you lose your place in
/// the queue.
///
/// # Examples
///
/// ```
/// use tokio::sync::Mutex;
///
/// #[tokio::main]
/// async fn main() {
/// let mutex = Mutex::new(1);
///
/// let mut n = mutex.lock().await;
/// *n = 2;
/// }
/// ```
pub async fn lock(&self) -> MutexGuard<'_, T> {
/// Pulls some bytes from this source into the specified buffer,
/// returning how many bytes were read.
///
/// Equivalent to:
///
/// ```ignore
/// async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
/// ```
///
/// This method does not provide any guarantees about whether it
/// completes immediately or asynchronously.
///
/// # Return
///
/// If the return value of this method is `Ok(n)`, then it must be
/// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
/// that the buffer `buf` has been filled in with `n` bytes of data from
/// this source. If `n` is `0`, then it can indicate one of two
/// scenarios:
///
/// 1. This reader has reached its "end of file" and will likely no longer
/// be able to produce bytes. Note that this does not mean that the
/// reader will *always* no longer be able to produce bytes.
/// 2. The buffer specified was 0 bytes in length.
///
/// No guarantees are provided about the contents of `buf` when this
/// function is called, implementations cannot rely on any property of the
/// contents of `buf` being `true`. It is recommended that *implementations*
/// only write data to `buf` instead of reading its contents.
///
/// Correspondingly, however, *callers* of this method may not assume
/// any guarantees about how the implementation uses `buf`. It is
/// possible that the code that's supposed to write to the buffer might
/// also read from it. It is your responsibility to make sure that `buf`
/// is initialized before calling `read`.
///
/// # Errors
///
/// If this function encounters any form of I/O or other error, an error
/// variant will be returned. If an error is returned then it must be
/// guaranteed that no bytes were read.
///
/// # Cancel safety
///
/// This method is cancel safe. If you use it as the event in a
/// [`tokio::select!`](crate::select) statement and some other branch
/// completes first, then it is guaranteed that no data was read.
///
/// # Examples
///
/// [`File`][crate::fs::File]s implement `Read`:
///
/// ```no_run
/// use tokio::fs::File;
/// use tokio::io::{self, AsyncReadExt};
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let mut f = File::open("foo.txt").await?;
/// let mut buffer = [0; 10];
///
/// // read up to 10 bytes
/// let n = f.read(&mut buffer[..]).await?;
///
/// println!("The bytes: {:?}", &buffer[..n]);
/// Ok(())
/// }
/// ```
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>
/// Sends data on the socket to the given address. On success, returns the
/// number of bytes written.
///
/// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
/// documentation for concrete examples.
///
/// It is possible for `addr` to yield multiple addresses, but `send_to`
/// will only send data to the first address yielded by `addr`.
///
/// This will return an error when the IP version of the local socket does
/// not match that returned from [`ToSocketAddrs`].
///
/// [`ToSocketAddrs`]: crate::net::ToSocketAddrs
///
/// # Cancel safety
///
/// This method is cancel safe. If `send_to` is used as the event in a
/// [`tokio::select!`](crate::select) statement and some other branch
/// completes first, then it is guaranteed that the message was not sent.
///
/// # Example
///
/// ```no_run
/// use tokio::net::UdpSocket;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
/// let len = socket.send_to(b"hello world", "127.0.0.1:8081").await?;
///
/// println!("Sent {} bytes", len);
///
/// Ok(())
/// }
/// ```
pub async fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], target: A) -> io::Result<usize> {
/// Waits for the socket to become writable.
///
/// This function is equivalent to `ready(Interest::WRITABLE)` and is
/// usually paired with `try_send()` or `try_send_to()`.
///
/// The function may complete without the socket being writable. This is a
/// false-positive and attempting a `try_send()` will return with
/// `io::ErrorKind::WouldBlock`.
///
/// # Cancel safety
///
/// This method is cancel safe. Once a readiness event occurs, the method
/// will continue to return immediately until the readiness event is
/// consumed by an attempt to write that fails with `WouldBlock` or
/// `Poll::Pending`.
///
/// # Examples
///
/// ```no_run
/// use tokio::net::UdpSocket;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// // Bind socket
/// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
/// socket.connect("127.0.0.1:8081").await?;
///
/// loop {
/// // Wait for the socket to be writable
/// socket.writable().await?;
///
/// // Try to send data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match socket.try_send(b"hello world") {
/// Ok(n) => {
/// break;
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue;
/// }
/// Err(e) => {
/// return Err(e);
/// }
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub async fn writable(&self) -> io::Result<()> {
/// Waits for the socket to become readable.
///
/// This function is equivalent to `ready(Interest::READABLE)` and is usually
/// paired with `try_read()`.
///
/// This function is also equivalent to [`TcpStream::ready`].
///
/// # Cancel safety
///
/// This method is cancel safe. Once a readiness event occurs, the method
/// will continue to return immediately until the readiness event is
/// consumed by an attempt to read that fails with `WouldBlock` or
/// `Poll::Pending`.
pub async fn readable(&self) -> io::Result<()> {
/// Waits for any of the requested ready states.
///
/// This function is usually paired with [`try_read()`]. It can be used instead
/// of [`readable()`] to check the returned ready set for [`Ready::READABLE`]
/// and [`Ready::READ_CLOSED`] events.
///
/// The function may complete without the socket being ready. This is a
/// false-positive and attempting an operation will return with
/// `io::ErrorKind::WouldBlock`. The function can also return with an empty
/// [`Ready`] set, so you should always check the returned value and possibly
/// wait again if the requested states are not set.
///
/// This function is equivalent to [`TcpStream::ready`].
///
/// [`try_read()`]: Self::try_read
/// [`readable()`]: Self::readable
///
/// # Cancel safety
///
/// This method is cancel safe. Once a readiness event occurs, the method
/// will continue to return immediately until the readiness event is
/// consumed by an attempt to read or write that fails with `WouldBlock` or
/// `Poll::Pending`.
pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
/// Receives a single datagram message on the socket from the remote address
/// to which it is connected. On success, returns the number of bytes read.
///
/// The function must be called with valid byte array `buf` of sufficient
/// size to hold the message bytes. If a message is too long to fit in the
/// supplied buffer, excess bytes may be discarded.
///
/// The [`connect`] method will connect this socket to a remote address.
/// This method will fail if the socket is not connected.
///
/// # Cancel safety
///
/// This method is cancel safe. If `recv` is used as the event in a
/// [`tokio::select!`](crate::select) statement and some other branch
/// completes first, it is guaranteed that no messages were received on this
/// socket.
///
/// [`connect`]: method@Self::connect
///
/// ```no_run
/// use tokio::net::UdpSocket;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// // Bind socket
/// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
/// socket.connect("127.0.0.1:8081").await?;
///
/// let mut buf = vec![0; 10];
/// let n = socket.recv(&mut buf).await?;
///
/// println!("received {} bytes {:?}", n, &buf[..n]);
///
/// Ok(())
/// }
/// ```
pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
/// An extension trait which adds utility methods to [`AsyncBufRead`] types.
///
/// [`AsyncBufRead`]: crate::io::AsyncBufRead
pub trait AsyncBufReadExt: AsyncBufRead {
/// Reads all bytes into `buf` until the delimiter `byte` or EOF is reached.
///
/// Equivalent to:
///
/// ```ignore
/// async fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize>;
/// ```
///
/// This function will read bytes from the underlying stream until the
/// delimiter or EOF is found. Once found, all bytes up to, and including,
/// the delimiter (if found) will be appended to `buf`.
///
/// If successful, this function will return the total number of bytes read.
///
/// If this function returns `Ok(0)`, the stream has reached EOF.
///
/// # Errors
///
/// This function will ignore all instances of [`ErrorKind::Interrupted`] and
/// will otherwise return any errors returned by [`fill_buf`].
///
/// If an I/O error is encountered then all bytes read so far will be
/// present in `buf` and its length will have been adjusted appropriately.
///
/// [`fill_buf`]: AsyncBufRead::poll_fill_buf
/// [`ErrorKind::Interrupted`]: std::io::ErrorKind::Interrupted
///
/// # Cancel safety
///
/// If the method is used as the event in a
/// [`tokio::select!`](crate::select) statement and some other branch
/// completes first, then some data may have been partially read. Any
/// partially read bytes are appended to `buf`, and the method can be
/// called again to continue reading until `byte`.
///
/// This method returns the total number of bytes read. If you cancel
/// the call to `read_until` and then call it again to continue reading,
/// the counter is reset.
///
/// # Examples
///
/// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
/// this example, we use [`Cursor`] to read all the bytes in a byte slice
/// in hyphen delimited segments:
///
/// [`Cursor`]: std::io::Cursor
///
/// ```
/// use tokio::io::AsyncBufReadExt;
///
/// use std::io::Cursor;
///
/// #[tokio::main]
/// async fn main() {
/// let mut cursor = Cursor::new(b"lorem-ipsum");
/// let mut buf = vec![];
///
/// // cursor is at 'l'
/// let num_bytes = cursor.read_until(b'-', &mut buf)
/// .await
/// .expect("reading from cursor won't fail");
///
/// assert_eq!(num_bytes, 6);
/// assert_eq!(buf, b"lorem-");
/// buf.clear();
///
/// // cursor is at 'i'
/// let num_bytes = cursor.read_until(b'-', &mut buf)
/// .await
/// .expect("reading from cursor won't fail");
///
/// assert_eq!(num_bytes, 5);
/// assert_eq!(buf, b"ipsum");
/// buf.clear();
///
/// // cursor is at EOF
/// let num_bytes = cursor.read_until(b'-', &mut buf)
/// .await
/// .expect("reading from cursor won't fail");
/// assert_eq!(num_bytes, 0);
/// assert_eq!(buf, b"");
/// }
/// ```
fn read_until<'a>(&'a mut self, byte: u8, buf: &'a mut Vec<u8>) -> ReadUntil<'a, Self>
/// Completes when the receiver has dropped.
///
/// This allows the producers to get notified when interest in the produced
/// values is canceled and immediately stop doing work.
///
/// # Cancel safety
///
/// This method is cancel safe. Once the channel is closed, it stays closed
/// forever and all future calls to `closed` will return immediately.
///
/// # Examples
///
/// ```
/// use tokio::sync::mpsc;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx1, rx) = mpsc::channel::<()>(1);
/// let tx2 = tx1.clone();
/// let tx3 = tx1.clone();
/// let tx4 = tx1.clone();
/// let tx5 = tx1.clone();
/// tokio::spawn(async move {
/// drop(rx);
/// });
///
/// futures::join!(
/// tx1.closed(),
/// tx2.closed(),
/// tx3.closed(),
/// tx4.closed(),
/// tx5.closed()
/// );
/// println!("Receiver dropped");
/// }
/// ```
pub async fn closed(&self) {
/// Waits for any of the requested ready states.
///
/// This function is usually paired with `try_read()` or `try_write()`. It
/// can be used to concurrently read / write to the same socket on a single
/// task without splitting the socket.
///
/// The function may complete without the socket being ready. This is a
/// false-positive and attempting an operation will return with
/// `io::ErrorKind::WouldBlock`. The function can also return with an empty
/// [`Ready`] set, so you should always check the returned value and possibly
/// wait again if the requested states are not set.
///
/// # Cancel safety
///
/// This method is cancel safe. Once a readiness event occurs, the method
/// will continue to return immediately until the readiness event is
/// consumed by an attempt to read or write that fails with `WouldBlock` or
/// `Poll::Pending`.
///
/// # Examples
///
/// Concurrently read and write to the stream on the same task without
/// splitting.
///
/// ```no_run
/// use tokio::io::Interest;
/// use tokio::net::UnixStream;
/// use std::error::Error;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn Error>> {
/// let dir = tempfile::tempdir().unwrap();
/// let bind_path = dir.path().join("bind_path");
/// let stream = UnixStream::connect(bind_path).await?;
///
/// loop {
/// let ready = stream.ready(Interest::READABLE | Interest::WRITABLE).await?;
///
/// if ready.is_readable() {
/// let mut data = vec![0; 1024];
/// // Try to read data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match stream.try_read(&mut data) {
/// Ok(n) => {
/// println!("read {} bytes", n);
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue;
/// }
/// Err(e) => {
/// return Err(e.into());
/// }
/// }
///
/// }
///
/// if ready.is_writable() {
/// // Try to write data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match stream.try_write(b"hello world") {
/// Ok(n) => {
/// println!("write {} bytes", n);
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue;
/// }
/// Err(e) => {
/// return Err(e.into());
/// }
/// }
/// }
/// }
/// }
/// ```
pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
/// Sends data on the socket to the socket's peer.
///
/// # Cancel safety
///
/// This method is cancel safe. If `send` is used as the event in a
/// [`tokio::select!`](crate::select) statement and some other branch
/// completes first, then it is guaranteed that the message was not sent.
///
/// # Examples
/// ```
/// # use std::error::Error;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn Error>> {
/// use tokio::net::UnixDatagram;
///
/// // Create the pair of sockets
/// let (sock1, sock2) = UnixDatagram::pair()?;
///
/// // Since the sockets are paired, the paired send/recv
/// // functions can be used
/// let bytes = b"hello world";
/// sock1.send(bytes).await?;
///
/// let mut buff = vec![0u8; 24];
/// let size = sock2.recv(&mut buff).await?;
///
/// let dgram = &buff[..size];
/// assert_eq!(dgram, bytes);
///
/// # Ok(())
/// # }
/// ```
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
/// Locks this `RwLock` with exclusive write access, causing the current
/// task to yield until the lock has been acquired.
///
/// The calling task will yield while other writers or readers currently
/// have access to the lock.
///
/// Returns an RAII guard which will drop the write access of this `RwLock`
/// when dropped.
///
/// # Cancel safety
///
/// This method uses a queue to fairly distribute locks in the order they
/// were requested. Cancelling a call to `write` makes you lose your place
/// in the queue.
///
/// # Examples
///
/// ```
/// use tokio::sync::RwLock;
///
/// #[tokio::main]
/// async fn main() {
/// let lock = RwLock::new(1);
///
/// let mut n = lock.write().await;
/// *n = 2;
///}
/// ```
pub async fn write(&self) -> RwLockWriteGuard<'_, T> {
/// Locks this mutex, causing the current task to yield until the lock has
/// been acquired. When the lock has been acquired, this returns an
/// [`OwnedMutexGuard`].
///
/// If the mutex is available to be acquired immediately, then this call
/// will typically not yield to the runtime. However, this is not guaranteed
/// under all circumstances.
///
/// This method is identical to [`Mutex::lock`], except that the returned
/// guard references the `Mutex` with an [`Arc`] rather than by borrowing
/// it. Therefore, the `Mutex` must be wrapped in an `Arc` to call this
/// method, and the guard will live for the `'static` lifetime, as it keeps
/// the `Mutex` alive by holding an `Arc`.
///
/// # Cancel safety
///
/// This method uses a queue to fairly distribute locks in the order they
/// were requested. Cancelling a call to `lock_owned` makes you lose your
/// place in the queue.
///
/// # Examples
///
/// ```
/// use tokio::sync::Mutex;
/// use std::sync::Arc;
///
/// #[tokio::main]
/// async fn main() {
/// let mutex = Arc::new(Mutex::new(1));
///
/// let mut n = mutex.clone().lock_owned().await;
/// *n = 2;
/// }
/// ```
///
/// [`Arc`]: std::sync::Arc
pub async fn lock_owned(self: Arc<Self>) -> OwnedMutexGuard<T> {
/// Set parameters configuring TCP keepalive probes for this socket.
///
/// The supported parameters depend on the operating system, and are
/// configured using the [`TcpKeepalive`] struct. At a minimum, all systems
/// support configuring the [keepalive time]: the time after which the OS
/// will start sending keepalive messages on an idle connection.
///
/// [keepalive time]: TcpKeepalive::with_time
///
/// # Notes
///
/// * This will enable `SO_KEEPALIVE` on this socket, if it is not already
/// enabled.
/// * On some platforms, such as Windows, any keepalive parameters *not*
/// configured by the `TcpKeepalive` struct passed to this function may be
/// overwritten with their default values. Therefore, this function should
/// either only be called once per socket, or the same parameters should
/// be passed every time it is called.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// use socket2::{Socket, TcpKeepalive, Domain, Type};
///
/// # fn main() -> std::io::Result<()> {
/// let socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;
/// let keepalive = TcpKeepalive::new()
/// .with_time(Duration::from_secs(4));
/// // Depending on the target operating system, we may also be able to
/// // configure the keepalive probe interval and/or the number of
/// // retries here as well.
///
/// socket.set_tcp_keepalive(&keepalive)?;
/// # Ok(()) }
/// ```
///
pub fn set_tcp_keepalive(&self, params: &TcpKeepalive) -> io::Result<()> {
/// Return the committer as configured by this repository, which is determined by…
///
/// * …the git configuration `committer.name|email`…
/// * …the `GIT_COMMITTER_(NAME|EMAIL|DATE)` environment variables…
/// * …the configuration for `user.name|email` as fallback…
///
/// …and in that order, or `None` if no committer name or email was configured, or `Some(Err(…))`
/// if the committer date could not be parsed.
///
/// # Note
///
/// The values are cached when the repository is instantiated.
pub fn committer(&self) -> Option<Result<gix_actor::SignatureRef<'_>, config::time::Error>> {
/// Attempts to receive a single datagram on the socket.
///
/// Note that on multiple calls to a `poll_*` method in the recv direction, only the
/// `Waker` from the `Context` passed to the most recent call will be scheduled to
/// receive a wakeup.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the socket is not ready to read
/// * `Poll::Ready(Ok(addr))` reads data from `addr` into `ReadBuf` if the socket is ready
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// # Notes
/// Note that the socket address **cannot** be implicitly trusted, because it is relatively
/// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
/// Because UDP is stateless and does not validate the origin of a packet,
/// the attacker does not need to be able to intercept traffic in order to interfere.
/// It is important to be aware of this when designing your application-level protocol.
///
/// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
pub fn poll_recv_from(
/// Returns true if the event contains error readiness.
///
/// Error events occur when the socket enters an error state. In this case,
/// the socket will also receive a readable or writable event. Reading or
/// writing to the socket will result in an error.
///
/// # Notes
///
/// Method is available on all platforms, but not all platforms trigger the
/// error event.
///
/// The table below shows what flags are checked on what OS.
///
/// | [OS selector] | Flag(s) checked |
/// |---------------|-----------------|
/// | [epoll] | `EPOLLERR` |
/// | [kqueue] | `EV_ERROR` and `EV_EOF` with `fflags` set to `0`. |
///
/// [OS selector]: ../struct.Poll.html#implementation-notes
/// [epoll]: https://man7.org/linux/man-pages/man7/epoll.7.html
/// [kqueue]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
pub fn is_error(&self) -> bool {
/// Searches for an empty or deleted bucket which is suitable for inserting
/// a new element, returning the `index` for the new [`Bucket`].
///
/// This function does not make any changes to the `data` part of the table, or any
/// changes to the `items` or `growth_left` field of the table.
///
/// The table must have at least 1 empty or deleted `bucket`, otherwise this function
/// will never return (will go into an infinite loop) for tables larger than the group
/// width, or return an index outside of the table indices range if the table is less
/// than the group width.
///
/// # Note
///
/// Calling this function is always safe, but attempting to write data at
/// the index returned by this function when the table is less than the group width
/// and if there was not at least one empty bucket in the table will cause immediate
/// [`undefined behavior`]. This is because in this case the function will return
/// `self.bucket_mask + 1` as an index due to the trailing EMPTY control bytes outside
/// the table range.
///
/// [`undefined behavior`]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[inline]
/// Execute an I/O operation ensuring that the socket receives more events
/// if it hits a [`WouldBlock`] error.
///
/// # Notes
///
/// This method is required to be called for **all** I/O operations to
/// ensure the user will receive events once the socket is ready again after
/// returning a [`WouldBlock`] error.
///
/// [`WouldBlock`]: io::ErrorKind::WouldBlock
///
/// # Examples
///
#[cfg_attr(unix, doc = "```no_run")]
/// Creates a new `PKey` containing an HMAC key.
///
/// # Note
///
/// To compute HMAC values, use the `sign` module.
#[corresponds(EVP_PKEY_new_mac_key)]
/// Returns the number of active receivers
///
/// An active receiver is a [`Receiver`] handle returned from [`channel`] or
/// [`subscribe`]. These are the handles that will receive values sent on
/// this [`Sender`].
///
/// # Note
///
/// It is not guaranteed that a sent message will reach this number of
/// receivers. Active receivers may never call [`recv`] again before
/// dropping.
///
/// [`recv`]: crate::sync::broadcast::Receiver::recv
/// [`Receiver`]: crate::sync::broadcast::Receiver
/// [`Sender`]: crate::sync::broadcast::Sender
/// [`subscribe`]: crate::sync::broadcast::Sender::subscribe
/// [`channel`]: crate::sync::broadcast::channel
///
/// # Examples
///
/// ```
/// use tokio::sync::broadcast;
///
/// #[tokio::main]
/// async fn main() {
/// let (tx, _rx1) = broadcast::channel(16);
///
/// assert_eq!(1, tx.receiver_count());
///
/// let mut _rx2 = tx.subscribe();
///
/// assert_eq!(2, tx.receiver_count());
///
/// tx.send(10).unwrap();
/// }
/// ```
pub fn receiver_count(&self) -> usize {
/// Runs a future to completion on the provided runtime, driving any local
/// futures spawned on this task set on the current thread.
///
/// This runs the given future on the runtime, blocking until it is
/// complete, and yielding its resolved result. Any tasks or timers which
/// the future spawns internally will be executed on the runtime. The future
/// may also call [`spawn_local`] to spawn_local additional local futures on the
/// current thread.
///
/// This method should not be called from an asynchronous context.
///
/// # Panics
///
/// This function panics if the executor is at capacity, if the provided
/// future panics, or if called within an asynchronous execution context.
///
/// # Notes
///
/// Since this function internally calls [`Runtime::block_on`], and drives
/// futures in the local task set inside that call to `block_on`, the local
/// futures may not use [in-place blocking]. If a blocking call needs to be
/// issued from a local task, the [`spawn_blocking`] API may be used instead.
///
/// For example, this will panic:
/// ```should_panic
/// use tokio::runtime::Runtime;
/// use tokio::task;
///
/// let rt = Runtime::new().unwrap();
/// let local = task::LocalSet::new();
/// local.block_on(&rt, async {
/// let join = task::spawn_local(async {
/// let blocking_result = task::block_in_place(|| {
/// // ...
/// });
/// // ...
/// });
/// join.await.unwrap();
/// })
/// ```
/// This, however, will not panic:
/// ```
/// use tokio::runtime::Runtime;
/// use tokio::task;
///
/// let rt = Runtime::new().unwrap();
/// let local = task::LocalSet::new();
/// local.block_on(&rt, async {
/// let join = task::spawn_local(async {
/// let blocking_result = task::spawn_blocking(|| {
/// // ...
/// }).await;
/// // ...
/// });
/// join.await.unwrap();
/// })
/// ```
///
/// [`spawn_local`]: fn@spawn_local
/// [`Runtime::block_on`]: method@crate::runtime::Runtime::block_on
/// [in-place blocking]: fn@crate::task::block_in_place
/// [`spawn_blocking`]: fn@crate::task::spawn_blocking
#[track_caller]
/// Receives data from the socket. On success, returns the number of bytes
/// read and the address from whence the data came.
///
/// # Notes
///
/// On Windows, if the data is larger than the buffer specified, the buffer
/// is filled with the first part of the data, and recv_from returns the error
/// WSAEMSGSIZE(10040). The excess data is lost.
/// Make sure to always use a sufficiently large buffer to hold the
/// maximum UDP packet size, which can be up to 65536 bytes in size.
///
/// # Examples
///
/// ```no_run
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use mio::net::UdpSocket;
///
/// let socket = UdpSocket::bind("127.0.0.1:0".parse()?)?;
///
/// // We must check if the socket is readable before calling recv_from,
/// // or we could run into a WouldBlock error.
///
/// let mut buf = [0; 9];
/// let (num_recv, from_addr) = socket.recv_from(&mut buf)?;
/// println!("Received {:?} -> {:?} bytes from {:?}", buf, num_recv, from_addr);
/// #
/// # Ok(())
/// # }
/// ```
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
/// Unwrap the `Choice` wrapper to reveal the underlying `u8`.
///
/// # Note
///
/// This function only exists as an **escape hatch** for the rare case
/// where it's not possible to use one of the `subtle`-provided
/// trait impls.
///
/// **To convert a `Choice` to a `bool`, use the `From` implementation instead.**
#[inline]
/// Retrieve the sender of the data at the head of the input queue,
/// scheduling a wakeup if empty.
///
/// This is equivalent to calling [`poll_peek_from`] with a zero-sized buffer,
/// but suppresses the `WSAEMSGSIZE` error on Windows and the "invalid argument" error on macOS.
///
/// # Notes
///
/// Note that on multiple calls to a `poll_*` method in the `recv` direction, only the
/// `Waker` from the `Context` passed to the most recent call will be scheduled to
/// receive a wakeup.
///
/// Note that the socket address **cannot** be implicitly trusted, because it is relatively
/// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
/// Because UDP is stateless and does not validate the origin of a packet,
/// the attacker does not need to be able to intercept traffic in order to interfere.
/// It is important to be aware of this when designing your application-level protocol.
///
/// [`poll_peek_from`]: method@Self::poll_peek_from
/// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
pub fn poll_peek_sender(&self, cx: &mut Context<'_>) -> Poll<io::Result<SocketAddr>> {
/// Returns a unique mutable reference to the `value`.
///
/// # Safety
///
/// See [`NonNull::as_mut`] for safety concerns.
///
/// # Note
///
/// [`Hash`] and [`Eq`] on the new `T` value and its borrowed form *must* match
/// those for the old `T` value, as the map will not re-evaluate where the new
/// value should go, meaning the value may become "lost" if their location
/// does not reflect their state.
///
/// [`NonNull::as_mut`]: https://doc.rust-lang.org/core/ptr/struct.NonNull.html#method.as_mut
/// [`Hash`]: https://doc.rust-lang.org/core/hash/trait.Hash.html
/// [`Eq`]: https://doc.rust-lang.org/core/cmp/trait.Eq.html
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "raw")]
/// # fn test() {
/// use core::hash::{BuildHasher, Hash};
/// use hashbrown::raw::{Bucket, RawTable};
///
/// type NewHashBuilder = core::hash::BuildHasherDefault<ahash::AHasher>;
///
/// fn make_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
/// use core::hash::Hasher;
/// let mut state = hash_builder.build_hasher();
/// key.hash(&mut state);
/// state.finish()
/// }
///
/// let hash_builder = NewHashBuilder::default();
/// let mut table = RawTable::new();
///
/// let value: (&str, String) = ("A pony", "is a small horse".to_owned());
/// let hash = make_hash(&hash_builder, &value.0);
///
/// table.insert(hash, value.clone(), |val| make_hash(&hash_builder, &val.0));
///
/// let bucket: Bucket<(&str, String)> = table.find(hash, |(k, _)| k == &value.0).unwrap();
///
/// unsafe {
/// bucket
/// .as_mut()
/// .1
/// .push_str(" less than 147 cm at the withers")
/// };
/// assert_eq!(
/// unsafe { bucket.as_ref() },
/// &(
/// "A pony",
/// "is a small horse less than 147 cm at the withers".to_owned()
/// )
/// );
/// # }
/// # fn main() {
/// # #[cfg(feature = "raw")]
/// # test()
/// # }
/// ```
#[inline]
/// Receives data from the socket, without removing it from the input queue.
/// On success, returns the number of bytes read and the address from whence
/// the data came.
///
/// # Notes
///
/// On Windows, if the data is larger than the buffer specified, the buffer
/// is filled with the first part of the data, and `peek_from` returns the error
/// `WSAEMSGSIZE(10040)`. The excess data is lost.
/// Make sure to always use a sufficiently large buffer to hold the
/// maximum UDP packet size, which can be up to 65536 bytes in size.
///
/// MacOS will return an error if you pass a zero-sized buffer.
///
/// If you're merely interested in learning the sender of the data at the head of the queue,
/// try [`peek_sender`].
///
/// Note that the socket address **cannot** be implicitly trusted, because it is relatively
/// trivial to send a UDP datagram with a spoofed origin in a [packet injection attack].
/// Because UDP is stateless and does not validate the origin of a packet,
/// the attacker does not need to be able to intercept traffic in order to interfere.
/// It is important to be aware of this when designing your application-level protocol.
///
/// # Examples
///
/// ```no_run
/// use tokio::net::UdpSocket;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
///
/// let mut buf = vec![0u8; 32];
/// let (len, addr) = socket.peek_from(&mut buf).await?;
///
/// println!("peeked {:?} bytes from {:?}", len, addr);
///
/// Ok(())
/// }
/// ```
///
/// [`peek_sender`]: method@Self::peek_sender
/// [packet injection attack]: https://en.wikipedia.org/wiki/Packet_injection
pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
/// Returns the remaining number of bytes that can be
/// read before this instance will return EOF.
///
/// # Note
///
/// This instance may reach `EOF` after reading fewer bytes than indicated by
/// this method if the underlying [`AsyncRead`] instance reaches EOF.
pub fn limit(&self) -> u64 {
/// Dissolve this instance into its write and read handles without any message-writing side-effect as in [`RequestWriter::into_read()`].
///
/// Furthermore, the writer will not encode everything it writes as packetlines, but write everything verbatim into the
/// underlying channel.
///
/// # Note
///
/// It's of utmost importance to drop the request writer before reading the response as these might be inter-dependent, depending on
/// the underlying transport mechanism. Failure to do so may result in a deadlock depending on how the write and read mechanism
/// is implemented.
pub fn into_parts(self) -> (Box<dyn io::Write + 'a>, Box<dyn ExtendedBufRead<'a> + Unpin + 'a>) {
/// Set value for the `SO_LINGER` option on this socket.
///
/// If `linger` is not `None`, a close(2) or shutdown(2) will not return
/// until all queued messages for the socket have been successfully sent or
/// the linger timeout has been reached. Otherwise, the call returns
/// immediately and the closing is done in the background. When the socket
/// is closed as part of exit(2), it always lingers in the background.
///
/// # Notes
///
/// On most OSs the duration only has a precision of seconds and will be
/// silently truncated.
///
/// On Apple platforms (e.g. macOS, iOS, etc) this uses `SO_LINGER_SEC`.
pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
/// Sends a `Request` on the associated connection.
///
/// Returns a future that if successful, yields the `Response`.
///
/// # Note
///
/// There are some key differences in what automatic things the `Client`
/// does for you that will not be done here:
///
/// - `Client` requires absolute-form `Uri`s, since the scheme and
/// authority are needed to connect. They aren't required here.
/// - Since the `Client` requires absolute-form `Uri`s, it can add
/// the `Host` header based on it. You must add a `Host` header yourself
/// before calling this method.
/// - Since absolute-form `Uri`s are not required, if received, they will
/// be serialized as-is.
pub fn send_request(
/// Converts this type to its ASCII upper case equivalent in-place.
///
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
/// but non-ASCII letters are unchanged.
///
/// To return a new uppercased value without modifying the existing one, use
/// [`to_ascii_uppercase`].
///
/// # Note
///
/// This method is deprecated in favor of the identically-named
/// inherent methods on `u8`, `char`, `[u8]` and `str`.
///
/// [`to_ascii_uppercase`]: AsciiExt::to_ascii_uppercase
#[stable(feature = "ascii", since = "1.9.0")]
/// Returns true if the event contains LIO readiness.
///
/// # Notes
///
/// Method is available on all platforms, but only FreeBSD supports LIO. On
/// FreeBSD this method checks the `EVFILT_LIO` flag.
pub fn is_lio(&self) -> bool {
/// Returns the length of the IV used with this cipher.
///
/// # Note
///
/// Ciphers that do not use an IV have an IV length of 0.
#[corresponds(EVP_CIPHER_iv_length)]
/// Insert the `file_id, path` pair into the set.
///
/// # Note
/// Multiple [`FileId`] can be mapped to the same [`VfsPath`], and vice-versa.
pub fn insert(&mut self, file_id: FileId, path: VfsPath) {
/// Creates new [`UnixStream`] from a [`std::os::unix::net::UnixStream`].
///
/// This function is intended to be used to wrap a `UnixStream` from the
/// standard library in the Tokio equivalent.
///
/// # Notes
///
/// The caller is responsible for ensuring that the stream is in
/// non-blocking mode. Otherwise all I/O operations on the stream
/// will block the thread, which will cause unexpected behavior.
/// Non-blocking mode can be set using [`set_nonblocking`].
///
/// [`set_nonblocking`]: std::os::unix::net::UnixStream::set_nonblocking
///
/// # Examples
///
/// ```no_run
/// use tokio::net::UnixStream;
/// use std::os::unix::net::UnixStream as StdUnixStream;
/// # use std::error::Error;
///
/// # async fn dox() -> Result<(), Box<dyn Error>> {
/// let std_stream = StdUnixStream::connect("/path/to/the/socket")?;
/// std_stream.set_nonblocking(true)?;
/// let stream = UnixStream::from_std(std_stream)?;
/// # Ok(())
/// # }
/// ```
///
/// # Panics
///
/// This function panics if it is not called from within a runtime with
/// IO enabled.
///
/// The runtime is usually set implicitly when this function is called
/// from a future driven by a tokio runtime, otherwise runtime can be set
/// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
#[track_caller]
/// Returns a reference to the [`RawTable`] used underneath [`HashSet`].
/// This function is only available if the `raw` feature of the crate is enabled.
///
/// # Note
///
/// Calling this function is safe, but using the raw hash table API may require
/// unsafe functions or blocks.
///
/// `RawTable` API gives the lowest level of control under the set that can be useful
/// for extending the HashSet's API, but may lead to *[undefined behavior]*.
///
/// [`HashSet`]: struct.HashSet.html
/// [`RawTable`]: crate::raw::RawTable
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[cfg(feature = "raw")]
/// Try to acquire the lock of this value.
///
/// If the lock is already acquired by someone else, this returns
/// `None`. You can try to acquire again whenever you want, perhaps
/// by spinning a few times, or by using some other means of
/// notification.
///
/// # Note
///
/// The default memory ordering is to use `Acquire` to lock, and `Release`
/// to unlock. If different ordering is required, use
/// [`try_lock_explicit`](TryLock::try_lock_explicit) or
/// [`try_lock_explicit_unchecked`](TryLock::try_lock_explicit_unchecked).
#[inline]
/// Returns an array of the same size as `self`, with function `f` applied to each element
/// in order.
///
/// If you don't necessarily need a new fixed-size array, consider using
/// [`Iterator::map`] instead.
///
///
/// # Note on performance and stack usage
///
/// Unfortunately, usages of this method are currently not always optimized
/// as well as they could be. This mainly concerns large arrays, as mapping
/// over small arrays seem to be optimized just fine. Also note that in
/// debug mode (i.e. without any optimizations), this method can use a lot
/// of stack space (a few times the size of the array or more).
///
/// Therefore, in performance-critical code, try to avoid using this method
/// on large arrays or check the emitted code. Also try to avoid chained
/// maps (e.g. `arr.map(...).map(...)`).
///
/// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
/// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
/// really need a new array of the same size as the result. Rust's lazy
/// iterators tend to get optimized very well.
///
///
/// # Examples
///
/// ```
/// let x = [1, 2, 3];
/// let y = x.map(|v| v + 1);
/// assert_eq!(y, [2, 3, 4]);
///
/// let x = [1, 2, 3];
/// let mut temp = 0;
/// let y = x.map(|v| { temp += 1; v * temp });
/// assert_eq!(y, [1, 4, 9]);
///
/// let x = ["Ferris", "Bueller's", "Day", "Off"];
/// let y = x.map(|v| v.len());
/// assert_eq!(y, [6, 9, 3, 3]);
/// ```
#[stable(feature = "array_map", since = "1.55.0")]
/// Modifies the readonly flag for this set of permissions. If the
/// `readonly` argument is `true`, using the resulting `Permission` will
/// update file permissions to forbid writing. Conversely, if it's `false`,
/// using the resulting `Permission` will update file permissions to allow
/// writing.
///
/// This operation does **not** modify the files attributes. This only
/// changes the in-memory value of these attributes for this `Permissions`
/// instance. To modify the files attributes use the [`set_permissions`]
/// function which commits these attribute changes to the file.
///
/// # Note
///
/// `set_readonly(false)` makes the file *world-writable* on Unix.
/// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
///
/// It also does not take Access Control Lists (ACLs) or Unix group
/// membership into account.
///
/// # Windows
///
/// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
/// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
/// but the user may still have permission to change this flag. If
/// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
/// the user does not have permission to write to the file.
///
/// In Windows 7 and earlier this attribute prevents deleting empty
/// directories. It does not prevent modifying the directory contents.
/// On later versions of Windows this attribute is ignored for directories.
///
/// # Unix (including macOS)
///
/// On Unix-based platforms this sets or clears the write access bit for
/// the owner, group *and* others, equivalent to `chmod a+w <file>`
/// or `chmod a-w <file>` respectively. The latter will grant write access
/// to all users! You can use the [`PermissionsExt`] trait on Unix
/// to avoid this issue.
///
/// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
///
/// fn main() -> std::io::Result<()> {
/// let f = File::create("foo.txt")?;
/// let metadata = f.metadata()?;
/// let mut permissions = metadata.permissions();
///
/// permissions.set_readonly(true);
///
/// // filesystem doesn't change, only the in memory state of the
/// // readonly permission
/// assert_eq!(false, metadata.permissions().readonly());
///
/// // just this particular `permissions`.
/// assert_eq!(true, permissions.readonly());
/// Ok(())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// Sets the maximum number of bytes that can be written.
///
/// # Note
///
/// If the inner `BufMut` has fewer bytes than `lim` then that is the actual
/// number of available bytes.
pub fn set_limit(&mut self, lim: usize) {
/// Tries to send data on the socket to the given address, but if the send is
/// blocked this will return right away.
///
/// This function is usually paired with `writable()`.
///
/// # Returns
///
/// If successful, returns the number of bytes sent
///
/// Users should ensure that when the remote cannot receive, the
/// [`ErrorKind::WouldBlock`] is properly handled. An error can also occur
/// if the IP version of the socket does not match that of `target`.
///
/// [`ErrorKind::WouldBlock`]: std::io::ErrorKind::WouldBlock
///
/// # Example
///
/// ```no_run
/// use tokio::net::UdpSocket;
/// use std::error::Error;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn Error>> {
/// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
///
/// let dst = "127.0.0.1:8081".parse()?;
///
/// loop {
/// socket.writable().await?;
///
/// match socket.try_send_to(&b"hello world"[..], dst) {
/// Ok(sent) => {
/// println!("sent {} bytes", sent);
/// break;
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// // Writable false positive.
/// continue;
/// }
/// Err(e) => return Err(e.into()),
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub fn try_send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
/// Tries to write a buffer to the stream, returning how many bytes were
/// written.
///
/// The function will attempt to write the entire contents of `buf`, but
/// only part of the buffer may be written.
///
/// This function is usually paired with `writable()`.
///
/// # Return
///
/// If data is successfully written, `Ok(n)` is returned, where `n` is the
/// number of bytes written. If the stream is not ready to write data,
/// `Err(io::ErrorKind::WouldBlock)` is returned.
pub fn try_write(&self, buf: &[u8]) -> io::Result<usize> {
/// Creates a new socket configured for IPv6.
///
/// Calls `socket(2)` with `AF_INET6` and `SOCK_STREAM`.
///
/// # Returns
///
/// On success, the newly created `TcpSocket` is returned. If an error is
/// encountered, it is returned instead.
///
/// # Examples
///
/// Create a new IPv6 socket and start listening.
///
/// ```no_run
/// use tokio::net::TcpSocket;
///
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// let addr = "[::1]:8080".parse().unwrap();
/// let socket = TcpSocket::new_v6()?;
/// socket.bind(addr)?;
///
/// let listener = socket.listen(128)?;
/// # drop(listener);
/// Ok(())
/// }
/// ```
pub fn new_v6() -> io::Result<TcpSocket> {
/// Spawn the provided task with this builder's settings and store it in the
/// [`JoinSet`], returning an [`AbortHandle`] that can be used to remotely
/// cancel the task.
///
/// # Returns
///
/// An [`AbortHandle`] that can be used to remotely cancel the task.
///
/// # Panics
///
/// This method panics if called outside of a Tokio runtime.
///
/// [`AbortHandle`]: crate::task::AbortHandle
#[track_caller]
/// Determine whether `self > other`.
///
/// The bitwise-NOT of the return value of this function should be usable to
/// determine if `self <= other`.
///
/// This function should execute in constant time.
///
/// # Returns
///
/// A `Choice` with a set bit if `self > other`, and with no set bits
/// otherwise.
///
/// # Example
///
/// ```
/// use subtle::ConstantTimeGreater;
///
/// let x: u8 = 13;
/// let y: u8 = 42;
///
/// let x_gt_y = x.ct_gt(&y);
///
/// assert_eq!(x_gt_y.unwrap_u8(), 0);
///
/// let y_gt_x = y.ct_gt(&x);
///
/// assert_eq!(y_gt_x.unwrap_u8(), 1);
///
/// let x_gt_x = x.ct_gt(&x);
///
/// assert_eq!(x_gt_x.unwrap_u8(), 0);
/// ```
fn ct_gt(&self, other: &Self) -> Choice;
/// Attempts to receive a single datagram message on the socket from the remote
/// address to which it is `connect`ed.
///
/// The [`connect`] method will connect this socket to a remote address. This method
/// resolves to an error if the socket is not connected.
///
/// Note that on multiple calls to a `poll_*` method in the recv direction, only the
/// `Waker` from the `Context` passed to the most recent call will be scheduled to
/// receive a wakeup.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the socket is not ready to read
/// * `Poll::Ready(Ok(()))` reads data `ReadBuf` if the socket is ready
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`connect`]: method@Self::connect
pub fn poll_recv(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
/// Polls for write readiness.
///
/// If the tcp stream is not currently ready for writing, this method will
/// store a clone of the `Waker` from the provided `Context`. When the tcp
/// stream becomes ready for writing, `Waker::wake` will be called on the
/// waker.
///
/// Note that on multiple calls to `poll_write_ready` or `poll_write`, only
/// the `Waker` from the `Context` passed to the most recent call is
/// scheduled to receive a wakeup. (However, `poll_read_ready` retains a
/// second, independent waker.)
///
/// This function is intended for cases where creating and pinning a future
/// via [`writable`] is not feasible. Where possible, using [`writable`] is
/// preferred, as this supports polling from multiple tasks at once.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the tcp stream is not ready for writing.
/// * `Poll::Ready(Ok(()))` if the tcp stream is ready for writing.
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`writable`]: method@Self::writable
pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
/// Polls for write readiness.
///
/// If the pipe is not currently ready for writing, this method will
/// store a clone of the `Waker` from the provided `Context`. When the pipe
/// becomes ready for writing, `Waker::wake` will be called on the waker.
///
/// Note that on multiple calls to `poll_write_ready` or `poll_write`, only
/// the `Waker` from the `Context` passed to the most recent call is
/// scheduled to receive a wakeup. (However, `poll_read_ready` retains a
/// second, independent waker.)
///
/// This function is intended for cases where creating and pinning a future
/// via [`writable`] is not feasible. Where possible, using [`writable`] is
/// preferred, as this supports polling from multiple tasks at once.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the pipe is not ready for writing.
/// * `Poll::Ready(Ok(()))` if the pipe is ready for writing.
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`writable`]: method@Self::writable
pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
/// Tries to write a buffer to the stream, returning how many bytes were
/// written.
///
/// The function will attempt to write the entire contents of `buf`, but
/// only part of the buffer may be written.
///
/// This function is usually paired with `writable()`.
///
/// # Return
///
/// If data is successfully written, `Ok(n)` is returned, where `n` is the
/// number of bytes written. If the stream is not ready to write data,
/// `Err(io::ErrorKind::WouldBlock)` is returned.
pub fn try_write(&self, buf: &[u8]) -> io::Result<usize> {
/// Creates a new Unix datagram socket.
///
/// Calls `socket(2)` with `AF_UNIX` and `SOCK_DGRAM`.
///
/// # Returns
///
/// On success, the newly created [`UnixSocket`] is returned. If an error is
/// encountered, it is returned instead.
pub fn new_datagram() -> io::Result<UnixSocket> {
/// Attempts to send data to the specified address.
///
/// Note that on multiple calls to a `poll_*` method in the send direction, only the
/// `Waker` from the `Context` passed to the most recent call will be scheduled to
/// receive a wakeup.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the socket is not ready to write
/// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent.
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
pub fn poll_send_to<P>(
/// Spawn the provided task on the provided [`LocalSet`] with this builder's
/// settings, and store it in the [`JoinSet`].
///
/// # Returns
///
/// An [`AbortHandle`] that can be used to remotely cancel the task.
///
/// [`LocalSet`]: crate::task::LocalSet
/// [`AbortHandle`]: crate::task::AbortHandle
#[track_caller]
/// Attempts to receive a single datagram message on the socket from the remote
/// address to which it is `connect`ed.
///
/// The [`connect`] method will connect this socket to a remote address. This method
/// resolves to an error if the socket is not connected.
///
/// Note that on multiple calls to a `poll_*` method in the recv direction, only the
/// `Waker` from the `Context` passed to the most recent call will be scheduled to
/// receive a wakeup.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the socket is not ready to read
/// * `Poll::Ready(Ok(()))` reads data `ReadBuf` if the socket is ready
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`connect`]: method@Self::connect
pub fn poll_recv(&self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
/// Puts a mapping into the topmost namespace if this stack does not already contain one.
///
/// Returns a boolean flag indicating whether the insertion has completed successfully.
/// Note that both key and value are matched and the mapping is inserted if either
/// namespace prefix is not already mapped, or if it is mapped, but to a different URI.
///
/// # Parameters
/// * `prefix` --- namespace prefix;
/// * `uri` --- namespace URI.
///
/// # Return value
/// `true` if `prefix` has been inserted successfully; `false` if the `prefix`
/// was already present in the namespace stack.
pub fn put_checked<P, U>(&mut self, prefix: P, uri: U) -> bool
/// Attempts to send data on the socket to the remote address to which it
/// was previously `connect`ed.
///
/// The [`connect`] method will connect this socket to a remote address.
/// This method will fail if the socket is not connected.
///
/// Note that on multiple calls to a `poll_*` method in the send direction,
/// only the `Waker` from the `Context` passed to the most recent call will
/// be scheduled to receive a wakeup.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the socket is not available to write
/// * `Poll::Ready(Ok(n))` `n` is the number of bytes sent
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`connect`]: method@Self::connect
pub fn poll_send(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
/// Polls for write readiness.
///
/// If the pipe is not currently ready for writing, this method will
/// store a clone of the `Waker` from the provided `Context`. When the pipe
/// becomes ready for writing, `Waker::wake` will be called on the waker.
///
/// Note that on multiple calls to `poll_write_ready` or `poll_write`, only
/// the `Waker` from the `Context` passed to the most recent call is
/// scheduled to receive a wakeup. (However, `poll_read_ready` retains a
/// second, independent waker.)
///
/// This function is intended for cases where creating and pinning a future
/// via [`writable`] is not feasible. Where possible, using [`writable`] is
/// preferred, as this supports polling from multiple tasks at once.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the pipe is not ready for writing.
/// * `Poll::Ready(Ok(()))` if the pipe is ready for writing.
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`writable`]: method@Self::writable
pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
/// Polls for write readiness.
///
/// If the unix stream is not currently ready for writing, this method will
/// store a clone of the `Waker` from the provided `Context`. When the unix
/// stream becomes ready for writing, `Waker::wake` will be called on the
/// waker.
///
/// Note that on multiple calls to `poll_write_ready` or `poll_write`, only
/// the `Waker` from the `Context` passed to the most recent call is
/// scheduled to receive a wakeup. (However, `poll_read_ready` retains a
/// second, independent waker.)
///
/// This function is intended for cases where creating and pinning a future
/// via [`writable`] is not feasible. Where possible, using [`writable`] is
/// preferred, as this supports polling from multiple tasks at once.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the unix stream is not ready for writing.
/// * `Poll::Ready(Ok(()))` if the unix stream is ready for writing.
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`writable`]: method@Self::writable
pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
/// Tries to read data from the stream into the provided buffer, advancing the
/// buffer's internal cursor, returning how many bytes were read.
///
/// Receives any pending data from the socket but does not wait for new data
/// to arrive. On success, returns the number of bytes read. Because
/// `try_read_buf()` is non-blocking, the buffer does not have to be stored by
/// the async task and can exist entirely on the stack.
///
/// Usually, [`readable()`] or [`ready()`] is used with this function.
///
/// [`readable()`]: Self::readable()
/// [`ready()`]: Self::ready()
///
/// # Return
///
/// If data is successfully read, `Ok(n)` is returned, where `n` is the
/// number of bytes read. `Ok(0)` indicates the stream's read half is closed
/// and will no longer yield data. If the stream is not ready to read data
pub fn try_read_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
/// Tries to write several buffers to the stream, returning how many bytes
/// were written.
///
/// Data is written from each buffer in order, with the final buffer read
/// from possible being only partially consumed. This method behaves
/// equivalently to a single call to [`try_write()`] with concatenated
/// buffers.
///
/// This function is usually paired with `writable()`.
///
/// [`try_write()`]: TcpStream::try_write()
///
/// # Return
///
/// If data is successfully written, `Ok(n)` is returned, where `n` is the
/// number of bytes written. If the stream is not ready to write data,
/// `Err(io::ErrorKind::WouldBlock)` is returned.
///
/// # Examples
///
/// ```no_run
/// use tokio::net::TcpStream;
/// use std::error::Error;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn Error>> {
/// // Connect to a peer
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// let bufs = [io::IoSlice::new(b"hello "), io::IoSlice::new(b"world")];
///
/// loop {
/// // Wait for the socket to be writable
/// stream.writable().await?;
///
/// // Try to write data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match stream.try_write_vectored(&bufs) {
/// Ok(n) => {
/// break;
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue;
/// }
/// Err(e) => {
/// return Err(e.into());
/// }
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub fn try_write_vectored(&self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
/// Spawn the provided task on the provided [`LocalSet`] with this builder's
/// settings, and store it in the [`JoinSet`].
///
/// # Returns
///
/// An [`AbortHandle`] that can be used to remotely cancel the task.
///
/// [`LocalSet`]: crate::task::LocalSet
/// [`AbortHandle`]: crate::task::AbortHandle
#[track_caller]
/// Sends data on the socket to the remote address that the socket is
/// connected to.
///
/// The [`connect`] method will connect this socket to a remote address.
/// This method will fail if the socket is not connected.
///
/// [`connect`]: method@Self::connect
///
/// # Return
///
/// On success, the number of bytes sent is returned, otherwise, the
/// encountered error is returned.
///
/// # Examples
///
/// ```no_run
/// use tokio::io;
/// use tokio::net::UdpSocket;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// // Bind socket
/// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
/// socket.connect("127.0.0.1:8081").await?;
///
/// // Send a message
/// socket.send(b"hello world").await?;
///
/// Ok(())
/// }
/// ```
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
/// Tries to read data from the stream into the provided buffer, advancing the
/// buffer's internal cursor, returning how many bytes were read.
///
/// Receives any pending data from the pipe but does not wait for new data
/// to arrive. On success, returns the number of bytes read. Because
/// `try_read_buf()` is non-blocking, the buffer does not have to be stored by
/// the async task and can exist entirely on the stack.
///
/// Usually, [`readable()`] or [`ready()`] is used with this function.
///
/// [`readable()`]: NamedPipeClient::readable()
/// [`ready()`]: NamedPipeClient::ready()
///
/// # Return
///
/// If data is successfully read, `Ok(n)` is returned, where `n` is the
/// number of bytes read. `Ok(0)` indicates the stream's read half is closed
/// and will no longer yield data. If the stream is not ready to read data
/// `Err(io::ErrorKind::WouldBlock)` is returned.
///
/// # Examples
///
/// ```no_run
/// use tokio::net::windows::named_pipe;
/// use std::error::Error;
/// use std::io;
///
/// const PIPE_NAME: &str = r"\\.\pipe\tokio-named-pipe-client-readable";
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn Error>> {
/// let client = named_pipe::ClientOptions::new().open(PIPE_NAME)?;
///
/// loop {
/// // Wait for the pipe to be readable
/// client.readable().await?;
///
/// let mut buf = Vec::with_capacity(4096);
///
/// // Try to read data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match client.try_read_buf(&mut buf) {
/// Ok(0) => break,
/// Ok(n) => {
/// println!("read {} bytes", n);
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue;
/// }
/// Err(e) => {
/// return Err(e.into());
/// }
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub fn try_read_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
/// Waits until one of the tasks in the map completes and returns its
/// output, along with the key corresponding to that task.
///
/// Returns `None` if the map is empty.
///
/// # Cancel Safety
///
/// This method is cancel safe. If `join_next` is used as the event in a [`tokio::select!`]
/// statement and some other branch completes first, it is guaranteed that no tasks were
/// removed from this `JoinMap`.
///
/// # Returns
///
/// This function returns:
///
/// * `Some((key, Ok(value)))` if one of the tasks in this `JoinMap` has
/// completed. The `value` is the return value of that ask, and `key` is
/// the key associated with the task.
/// * `Some((key, Err(err))` if one of the tasks in this `JoinMap` has
/// panicked or been aborted. `key` is the key associated with the task
/// that panicked or was aborted.
/// * `None` if the `JoinMap` is empty.
///
/// [`tokio::select!`]: tokio::select
pub async fn join_next(&mut self) -> Option<(K, Result<V, JoinError>)> {
/// Tries to read data from the pipe into the provided buffer, advancing the
/// buffer's internal cursor, returning how many bytes were read.
///
/// Reads any pending data from the pipe but does not wait for new data
/// to arrive. On success, returns the number of bytes read. Because
/// `try_read_buf()` is non-blocking, the buffer does not have to be stored by
/// the async task and can exist entirely on the stack.
///
/// Usually, [`readable()`] or [`ready()`] is used with this function.
///
/// [`readable()`]: Self::readable
/// [`ready()`]: Self::ready
///
/// # Return
///
/// If data is successfully read, `Ok(n)` is returned, where `n` is the
/// number of bytes read. `Ok(0)` indicates the pipe's writing end is
/// closed and will no longer write data. If the pipe is not ready to read
/// data `Err(io::ErrorKind::WouldBlock)` is returned.
///
/// # Examples
///
/// ```no_run
/// use tokio::net::unix::pipe;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// // Open a reading end of a fifo
/// let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?;
///
/// loop {
/// // Wait for the pipe to be readable
/// rx.readable().await?;
///
/// let mut buf = Vec::with_capacity(4096);
///
/// // Try to read data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match rx.try_read_buf(&mut buf) {
/// Ok(0) => break,
/// Ok(n) => {
/// println!("read {} bytes", n);
/// }
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue;
/// }
/// Err(e) => {
/// return Err(e.into());
/// }
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub fn try_read_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
/// Polls for write readiness.
///
/// If the tcp stream is not currently ready for writing, this method will
/// store a clone of the `Waker` from the provided `Context`. When the tcp
/// stream becomes ready for writing, `Waker::wake` will be called on the
/// waker.
///
/// Note that on multiple calls to `poll_write_ready` or `poll_write`, only
/// the `Waker` from the `Context` passed to the most recent call is
/// scheduled to receive a wakeup. (However, `poll_read_ready` retains a
/// second, independent waker.)
///
/// This function is intended for cases where creating and pinning a future
/// via [`writable`] is not feasible. Where possible, using [`writable`] is
/// preferred, as this supports polling from multiple tasks at once.
///
/// # Return value
///
/// The function returns:
///
/// * `Poll::Pending` if the tcp stream is not ready for writing.
/// * `Poll::Ready(Ok(()))` if the tcp stream is ready for writing.
/// * `Poll::Ready(Err(e))` if an error is encountered.
///
/// # Errors
///
/// This function may encounter any standard I/O error except `WouldBlock`.
///
/// [`writable`]: method@Self::writable
pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
/// Spawn the provided task on the provided [runtime handle] with this
/// builder's settings, and store it in the [`JoinSet`].
///
/// # Returns
///
/// An [`AbortHandle`] that can be used to remotely cancel the task.
///
///
/// [`AbortHandle`]: crate::task::AbortHandle
/// [runtime handle]: crate::runtime::Handle
#[track_caller]
/// Tries to write several buffers to the stream, returning how many bytes
/// were written.
///
/// Data is written from each buffer in order, with the final buffer read
/// from possible being only partially consumed. This method behaves
/// equivalently to a single call to [`try_write()`] with concatenated
/// buffers.
///
/// This function is usually paired with `writable()`.
///
/// [`try_write()`]: Self::try_write()
///
/// # Return
///
/// If data is successfully written, `Ok(n)` is returned, where `n` is the
/// number of bytes written. If the stream is not ready to write data,
/// `Err(io::ErrorKind::WouldBlock)` is returned.
pub fn try_write_vectored(&self, buf: &[io::IoSlice<'_>]) -> io::Result<usize> {
/// Tries to write a buffer to the pipe, returning how many bytes were
/// written.
///
/// The function will attempt to write the entire contents of `buf`, but
/// only part of the buffer may be written. If the length of `buf` is not
/// greater than `PIPE_BUF` (an OS constant, 4096 under Linux), then the
/// write is guaranteed to be atomic, i.e. either the entire content of
/// `buf` will be written or this method will fail with `WouldBlock`. There
/// is no such guarantee if `buf` is larger than `PIPE_BUF`.
///
/// This function is usually paired with [`writable`].
///
/// [`writable`]: Self::writable
///
/// # Return
///
/// If data is successfully written, `Ok(n)` is returned, where `n` is the
/// number of bytes written. If the pipe is not ready to write data,
/// `Err(io::ErrorKind::WouldBlock)` is returned.
///
/// # Examples
///
/// ```no_run
/// use tokio::net::unix::pipe;
/// use std::io;
///
/// #[tokio::main]
/// async fn main() -> io::Result<()> {
/// // Open a writing end of a fifo
/// let tx = pipe::OpenOptions::new().open_sender("path/to/a/fifo")?;
///
/// loop {
/// // Wait for the pipe to be writable
/// tx.writable().await?;
///
/// // Try to write data, this may still fail with `WouldBlock`
/// // if the readiness event is a false positive.
/// match tx.try_write(b"hello world") {
/// Ok(n) => {
/// break;
/// }
/// Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
/// continue;
/// }
/// Err(e) => {
/// return Err(e.into());
/// }
/// }
/// }
///
/// Ok(())
/// }
/// ```
pub fn try_write(&self, buf: &[u8]) -> io::Result<usize> {
/// Create a new message queue attribute
///
/// # Arguments
///
/// - `mq_flags`: Either `0` or `O_NONBLOCK`.
/// - `mq_maxmsg`: Maximum number of messages on the queue.
/// - `mq_msgsize`: Maximum message size in bytes.
/// - `mq_curmsgs`: Number of messages currently in the queue.
pub fn new(
/// Create a new StringChunkedBuilder
///
/// # Arguments
///
/// * `capacity` - Number of string elements in the final array.
/// * `bytes_capacity` - Number of bytes needed to store the string values.
pub fn new(name: &str, capacity: usize) -> Self {
/// Register an [`event::Source`] with the `Poll` instance.
///
/// Once registered, the `Poll` instance will monitor the event source for
/// readiness state changes. When it notices a state change, it will return
/// a readiness event for the handle the next time [`poll`] is called.
///
/// See [`Poll`] docs for a high level overview.
///
/// # Arguments
///
/// `source: &mut S: event::Source`: This is the source of events that the
/// `Poll` instance should monitor for readiness state changes.
///
/// `token: Token`: The caller picks a token to associate with the socket.
/// When [`poll`] returns an event for the handle, this token is included.
/// This allows the caller to map the event to its source. The token
/// associated with the `event::Source` can be changed at any time by
/// calling [`reregister`].
///
/// See documentation on [`Token`] for an example showing how to pick
/// [`Token`] values.
///
/// `interest: Interest`: Specifies which operations `Poll` should monitor
/// for readiness. `Poll` will only return readiness events for operations
/// specified by this argument.
///
/// If a socket is registered with readable interest and the socket becomes
/// writable, no event will be returned from [`poll`].
///
/// The readiness interest for an `event::Source` can be changed at any time
/// by calling [`reregister`].
///
/// # Notes
///
/// Callers must ensure that if a source being registered with a `Poll`
/// instance was previously registered with that `Poll` instance, then a
/// call to [`deregister`] has already occurred. Consecutive calls to
/// `register` is unspecified behavior.
///
/// Unless otherwise specified, the caller should assume that once an event
/// source is registered with a `Poll` instance, it is bound to that `Poll`
/// instance for the lifetime of the event source. This remains true even
/// if the event source is deregistered from the poll instance using
/// [`deregister`].
///
/// [`event::Source`]: ./event/trait.Source.html
/// [`poll`]: struct.Poll.html#method.poll
/// [`reregister`]: struct.Registry.html#method.reregister
/// [`deregister`]: struct.Registry.html#method.deregister
/// [`Token`]: struct.Token.html
///
/// # Examples
///
#[cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
/// Requests a connection to a physical device, creating a logical device.
///
/// Returns the [`Device`] together with a [`Queue`] that executes command buffers.
///
/// # Arguments
///
/// - `desc` - Description of the features and limits requested from the given device.
/// - `trace_path` - Can be used for API call tracing, if that feature is
/// enabled in `wgpu-core`.
///
/// # Panics
///
/// - Features specified by `desc` are not supported by this adapter.
/// - Unsafe features were requested but not enabled when requesting the adapter.
/// - Limits requested exceed the values provided by the adapter.
/// - Adapter does not support all features wgpu requires to safely operate.
pub fn request_device(
/// Unsafe constructor from a variable length source
///
/// Some C APIs from provide `len`, and others do not. If it's provided it
/// will be validated. If not, it will be guessed based on the family.
///
/// # Arguments
///
/// - `addr`: raw pointer to something that can be cast to a
/// `libc::sockaddr`. For example, `libc::sockaddr_in`,
/// `libc::sockaddr_in6`, etc.
/// - `len`: For fixed-width types like `sockaddr_in`, it will be
/// validated if present and ignored if not. For variable-width
/// types it is required and must be the total length of valid
/// data. For example, if `addr` points to a
/// named `sockaddr_un`, then `len` must be the length of the
/// structure up to but not including the trailing NUL.
///
/// # Safety
///
/// `addr` must be valid for the specific type of sockaddr. `len`, if
/// present, must not exceed the length of valid data in `addr`.
unsafe fn from_raw(
/// Performs method lookup. If lookup is successful, it will return the callee
/// and store an appropriate adjustment for the self-expr. In some cases it may
/// report an error (e.g., invoking the `drop` method).
///
/// # Arguments
///
/// Given a method call like `foo.bar::<T1,...Tn>(a, b + 1, ...)`:
///
/// * `self`: the surrounding `FnCtxt` (!)
/// * `self_ty`: the (unadjusted) type of the self expression (`foo`)
/// * `segment`: the name and generic arguments of the method (`bar::<T1, ...Tn>`)
/// * `span`: the span for the method call
/// * `call_expr`: the complete method call: (`foo.bar::<T1,...Tn>(...)`)
/// * `self_expr`: the self expression (`foo`)
/// * `args`: the expressions of the arguments (`a, b + 1, ...`)
#[instrument(level = "debug", skip(self))]
/// Creates a new suballocation within the [region].
///
/// # Arguments
///
/// - `layout` - The layout of the allocation.
///
/// - `allocation_type` - The type of resources that can be bound to the allocation.
///
/// - `buffer_image_granularity` - The [buffer-image granularity] device property.
///
/// This is provided as an argument here rather than on construction of the allocator to
/// allow for optimizations: if you are only ever going to be creating allocations with the
/// same `allocation_type` using this allocator, then you may hard-code this to
/// [`DeviceAlignment::MIN`], in which case, after inlining, the logic for aligning the
/// allocation to the buffer-image-granularity based on the allocation type of surrounding
/// allocations can be optimized out.
///
/// You don't need to consider the buffer-image granularity for instance when suballocating a
/// buffer, or when suballocating a [`DeviceMemory`] block that's only ever going to be used
/// for optimal images. However, if you do allocate both linear and non-linear resources and
/// don't specify the buffer-image granularity device property here, **you will get undefined
/// behavior down the line**. Note that [`AllocationType::Unknown`] counts as both linear and
/// non-linear at the same time: if you always use this as the `allocation_type` using this
/// allocator, then it is valid to set this to `DeviceAlignment::MIN`, but **you must ensure
/// all allocations are aligned to the buffer-image granularity at minimum**.
///
/// [region]: Self#regions
/// [buffer-image granularity]: super#buffer-image-granularity
/// [`DeviceMemory`]: crate::memory::DeviceMemory
fn allocate(
/// Create new parameters.
///
/// # Arguments
/// - `m_cost`: memory size in 1 KiB blocks. Between 8\*`p_cost` and (2^32)-1.
/// - `t_cost`: number of iterations. Between 1 and (2^32)-1.
/// - `p_cost`: degree of parallelism. Between 1 and (2^24)-1.
/// - `output_len`: size of the KDF output in bytes. Default 32.
pub const fn new(
/// Construct alternative trees
///
/// # Arguments
/// `threshold` - threshold value for many trees (more than that is many)
/// `exprs` - expressions iterator
fn new(threshold: usize, exprs: impl Iterator<Item = Expr>) -> AlternativeExprs {
/// Repeats the embedded parser, calling `g` to gather the results
///
/// This stops before `n` when the parser returns [`ErrMode::Backtrack`]. To instead chain an error up, see
/// [`cut_err`][crate::combinator::cut_err].
///
/// # Arguments
/// * `init` A function returning the initial value.
/// * `g` The function that combines a result of `f` with
/// the current accumulator.
///
/// **Warning:** If the parser passed to `fold` accepts empty inputs
/// (like `alpha0` or `digit0`), `fold_repeat` will return an error,
/// to prevent going into an infinite loop.
///
/// # Example
///
/// Zero or more repetitions:
/// ```rust
/// # use winnow::{error::ErrMode, error::ErrorKind, error::Needed};
/// # use winnow::prelude::*;
/// use winnow::combinator::repeat;
///
/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
/// repeat(
/// 0..,
/// "abc"
/// ).fold(
/// Vec::new,
/// |mut acc: Vec<_>, item| {
/// acc.push(item);
/// acc
/// }
/// ).parse_peek(s)
/// }
///
/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
/// assert_eq!(parser("123123"), Ok(("123123", vec![])));
/// assert_eq!(parser(""), Ok(("", vec![])));
/// ```
///
/// One or more repetitions:
/// ```rust
/// # use winnow::{error::ErrMode, error::{InputError, ErrorKind}, error::Needed};
/// # use winnow::prelude::*;
/// use winnow::combinator::repeat;
///
/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
/// repeat(
/// 1..,
/// "abc",
/// ).fold(
/// Vec::new,
/// |mut acc: Vec<_>, item| {
/// acc.push(item);
/// acc
/// }
/// ).parse_peek(s)
/// }
///
/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
/// assert_eq!(parser("123123"), Err(ErrMode::Backtrack(InputError::new("123123", ErrorKind::Many))));
/// assert_eq!(parser(""), Err(ErrMode::Backtrack(InputError::new("", ErrorKind::Many))));
/// ```
///
/// Arbitrary number of repetitions:
/// ```rust
/// # use winnow::{error::ErrMode, error::ErrorKind, error::Needed};
/// # use winnow::prelude::*;
/// use winnow::combinator::repeat;
///
/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {
/// repeat(
/// 0..=2,
/// "abc",
/// ).fold(
/// Vec::new,
/// |mut acc: Vec<_>, item| {
/// acc.push(item);
/// acc
/// }
/// ).parse_peek(s)
/// }
///
/// assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
/// assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
/// assert_eq!(parser("123123"), Ok(("123123", vec![])));
/// assert_eq!(parser(""), Ok(("", vec![])));
/// assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));
/// ```
#[doc(alias = "fold_many0")]
/// Returns the number of tasks the given worker thread has polled.
///
/// The worker poll count starts at zero when the runtime is created and
/// increases by one each time the worker polls a scheduled task.
///
/// The counter is monotonically increasing. It is never decremented or
/// reset to zero.
///
/// # Arguments
///
/// `worker` is the index of the worker being queried. The given value must
/// be between 0 and `num_workers()`. The index uniquely identifies a single
/// worker and will continue to identify the worker throughout the lifetime
/// of the runtime instance.
///
/// # Panics
///
/// The method panics when `worker` represents an invalid worker, i.e. is
/// greater than or equal to `num_workers()`.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Handle;
///
/// #[tokio::main]
/// async fn main() {
/// let metrics = Handle::current().metrics();
///
/// let n = metrics.worker_poll_count(0);
/// println!("worker 0 has polled {} tasks", n);
/// }
/// ```
pub fn worker_poll_count(&self, worker: usize) -> u64 {
///
/// Unpivot a `DataFrame` from wide to long format.
///
/// # Example
///
/// # Arguments
///
/// * `id_vars` - String slice that represent the columns to use as id variables.
/// * `value_vars` - String slice that represent the columns to use as value variables.
///
/// If `value_vars` is empty all columns that are not in `id_vars` will be used.
///
/// ```ignore
/// # use polars_core::prelude::*;
/// let df = df!("A" => &["a", "b", "a"],
/// "B" => &[1, 3, 5],
/// "C" => &[10, 11, 12],
/// "D" => &[2, 4, 6]
/// )?;
///
/// let melted = df.melt(&["A", "B"], &["C", "D"])?;
/// println!("{:?}", df);
/// println!("{:?}", melted);
/// # Ok::<(), PolarsError>(())
/// ```
/// Outputs:
/// ```text
/// +-----+-----+-----+-----+
/// | A | B | C | D |
/// | --- | --- | --- | --- |
/// | str | i32 | i32 | i32 |
/// +=====+=====+=====+=====+
/// | "a" | 1 | 10 | 2 |
/// +-----+-----+-----+-----+
/// | "b" | 3 | 11 | 4 |
/// +-----+-----+-----+-----+
/// | "a" | 5 | 12 | 6 |
/// +-----+-----+-----+-----+
///
/// +-----+-----+----------+-------+
/// | A | B | variable | value |
/// | --- | --- | --- | --- |
/// | str | i32 | str | i32 |
/// +=====+=====+==========+=======+
/// | "a" | 1 | "C" | 10 |
/// +-----+-----+----------+-------+
/// | "b" | 3 | "C" | 11 |
/// +-----+-----+----------+-------+
/// | "a" | 5 | "C" | 12 |
/// +-----+-----+----------+-------+
/// | "a" | 1 | "D" | 2 |
/// +-----+-----+----------+-------+
/// | "b" | 3 | "D" | 4 |
/// +-----+-----+----------+-------+
/// | "a" | 5 | "D" | 6 |
/// +-----+-----+----------+-------+
/// ```
pub fn melt<I, J>(&self, id_vars: I, value_vars: J) -> PolarsResult<Self>
/// Builds the PKCS #12 object
///
/// # Arguments
///
/// * `password` - the password used to encrypt the key and certificate
/// * `friendly_name` - user defined name for the certificate
/// * `pkey` - key to store
/// * `cert` - certificate to store
#[corresponds(PKCS12_create)]
/// Sets the readiness on this `ScheduledIo` by invoking the given closure on
/// the current value, returning the previous readiness value.
///
/// # Arguments
/// - `tick`: whether setting the tick or trying to clear readiness for a
/// specific tick.
/// - `f`: a closure returning a new readiness value given the previous
/// readiness.
pub(super) fn set_readiness(&self, tick: Tick, f: impl Fn(Ready) -> Ready) {
/// Set the CSV reader to infer the schema of the file
///
/// # Arguments
/// * `max_records` - Maximum number of rows read for schema inference.
/// Setting this to `None` will do a full table scan (slow).
pub fn infer_schema(mut self, max_records: Option<usize>) -> Self {
/// Sets the readiness on this `ScheduledIo` by invoking the given closure on
/// the current value, returning the previous readiness value.
///
/// # Arguments
/// - `tick`: whether setting the tick or trying to clear readiness for a
/// specific tick.
/// - `f`: a closure returning a new readiness value given the previous
/// readiness.
pub(super) fn set_readiness(&self, tick: Tick, f: impl Fn(Ready) -> Ready) {
/// Performs the correct padding for an integer which has already been
/// emitted into a str. The str should *not* contain the sign for the
/// integer, that will be added by this method.
///
/// # Arguments
///
/// * is_nonnegative - whether the original integer was either positive or zero.
/// * prefix - if the '#' character (Alternate) is provided, this
/// is the prefix to put in front of the number.
/// * buf - the byte array that the number has been formatted into
///
/// This function will correctly account for the flags provided as well as
/// the minimum width. It will not take precision into account.
///
/// # Examples
///
/// ```
/// use std::fmt;
///
/// struct Foo { nb: i32 }
///
/// impl Foo {
/// fn new(nb: i32) -> Foo {
/// Foo {
/// nb,
/// }
/// }
/// }
///
/// impl fmt::Display for Foo {
/// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
/// // We need to remove "-" from the number output.
/// let tmp = self.nb.abs().to_string();
///
/// formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
/// }
/// }
///
/// assert_eq!(format!("{}", Foo::new(2)), "2");
/// assert_eq!(format!("{}", Foo::new(-1)), "-1");
/// assert_eq!(format!("{}", Foo::new(0)), "0");
/// assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
/// assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// Returns the number of times the given worker thread unparked but
/// performed no work before parking again.
///
/// The worker no-op count starts at zero when the runtime is created and
/// increases by one each time the worker unparks the thread but finds no
/// new work and goes back to sleep. This indicates a false-positive wake up.
///
/// The counter is monotonically increasing. It is never decremented or
/// reset to zero.
///
/// # Arguments
///
/// `worker` is the index of the worker being queried. The given value must
/// be between 0 and `num_workers()`. The index uniquely identifies a single
/// worker and will continue to identify the worker throughout the lifetime
/// of the runtime instance.
///
/// # Panics
///
/// The method panics when `worker` represents an invalid worker, i.e. is
/// greater than or equal to `num_workers()`.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Handle;
///
/// #[tokio::main]
/// async fn main() {
/// let metrics = Handle::current().metrics();
///
/// let n = metrics.worker_noop_count(0);
/// println!("worker 0 had {} no-op unparks", n);
/// }
/// ```
pub fn worker_noop_count(&self, worker: usize) -> u64 {
/// Create a new `AioRead`, placing the data in a mutable slice.
///
/// # Arguments
///
/// * `fd`: File descriptor to read from
/// * `offs`: File offset
/// * `buf`: A memory buffer. It must outlive the `AioRead`.
/// * `prio`: If POSIX Prioritized IO is supported, then the
/// operation will be prioritized at the process's
/// priority level minus `prio`
/// * `sigev_notify`: Determines how you will be notified of event
/// completion.
pub fn new(
///
/// # Arguments
/// `id` - (branch, id)
/// Used to make sure that the dot boxes are distinct.
/// branch is an id per join/union branch
/// id is incremented by the depth traversal of the tree.
pub fn dot(
/// Insert an entry into the timing wheel.
///
/// # Arguments
///
/// * `item`: The item to insert into the wheel.
///
/// # Return
///
/// Returns `Ok` when the item is successfully inserted, `Err` otherwise.
///
/// `Err(Elapsed)` indicates that `when` represents an instant that has
/// already passed. In this case, the caller should fire the timeout
/// immediately.
///
/// `Err(Invalid)` indicates an invalid `when` argument as been supplied.
///
/// # Safety
///
/// This function registers item into an intrusive linked list. The caller
/// must ensure that `item` is pinned and will not be dropped without first
/// being deregistered.
pub(crate) unsafe fn insert(
/// Returns the total number of times the given worker thread has parked.
///
/// The worker park count starts at zero when the runtime is created and
/// increases by one each time the worker parks the thread waiting for new
/// inbound events to process. This usually means the worker has processed
/// all pending work and is currently idle.
///
/// The counter is monotonically increasing. It is never decremented or
/// reset to zero.
///
/// # Arguments
///
/// `worker` is the index of the worker being queried. The given value must
/// be between 0 and `num_workers()`. The index uniquely identifies a single
/// worker and will continue to identify the worker throughout the lifetime
/// of the runtime instance.
///
/// # Panics
///
/// The method panics when `worker` represents an invalid worker, i.e. is
/// greater than or equal to `num_workers()`.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Handle;
///
/// #[tokio::main]
/// async fn main() {
/// let metrics = Handle::current().metrics();
///
/// let n = metrics.worker_park_count(0);
/// println!("worker 0 parked {} times", n);
/// }
/// ```
pub fn worker_park_count(&self, worker: usize) -> u64 {
/// Get items in every sublist by multiple indexes.
///
/// # Arguments
/// - `null_on_oob`: Return a null when an index is out of bounds.
/// This behavior is more expensive than defaulting to returning an `Error`.
#[cfg(feature = "list_gather")]
/// Returns the number of tasks currently scheduled in the given worker's
/// local queue.
///
/// Tasks that are spawned or notified from within a runtime thread are
/// scheduled using that worker's local queue. This metric returns the
/// **current** number of tasks pending in the worker's local queue. As
/// such, the returned value may increase or decrease as new tasks are
/// scheduled and processed.
///
/// # Arguments
///
/// `worker` is the index of the worker being queried. The given value must
/// be between 0 and `num_workers()`. The index uniquely identifies a single
/// worker and will continue to identify the worker throughout the lifetime
/// of the runtime instance.
///
/// # Panics
///
/// The method panics when `worker` represents an invalid worker, i.e. is
/// greater than or equal to `num_workers()`.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Handle;
///
/// #[tokio::main]
/// async fn main() {
/// let metrics = Handle::current().metrics();
///
/// let n = metrics.worker_local_queue_depth(0);
/// println!("{} tasks currently pending in worker 0's local queue", n);
/// }
/// ```
pub fn worker_local_queue_depth(&self, worker: usize) -> usize {
/// Returns the number of tasks the given worker thread stole from
/// another worker thread.
///
/// This metric only applies to the **multi-threaded** runtime and will
/// always return `0` when using the current thread runtime.
///
/// The worker steal count starts at zero when the runtime is created and
/// increases by `N` each time the worker has processed its scheduled queue
/// and successfully steals `N` more pending tasks from another worker.
///
/// The counter is monotonically increasing. It is never decremented or
/// reset to zero.
///
/// # Arguments
///
/// `worker` is the index of the worker being queried. The given value must
/// be between 0 and `num_workers()`. The index uniquely identifies a single
/// worker and will continue to identify the worker throughout the lifetime
/// of the runtime instance.
///
/// # Panics
///
/// The method panics when `worker` represents an invalid worker, i.e. is
/// greater than or equal to `num_workers()`.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Handle;
///
/// #[tokio::main]
/// async fn main() {
/// let metrics = Handle::current().metrics();
///
/// let n = metrics.worker_steal_count(0);
/// println!("worker 0 has stolen {} tasks", n);
/// }
/// ```
pub fn worker_steal_count(&self, worker: usize) -> u64 {
/// Constructs a new V2 `Ingredient`.
///
/// # Arguments
///
/// * `title` - A user-displayable name for this ingredient (often a filename).
/// * `format` - The MIME media type of the ingredient - i.e. `image/jpeg`.
///
/// # Examples
///
/// ```
/// use c2pa::Ingredient;
/// let ingredient = Ingredient::new_v2("title", "image/jpeg");
/// ```
pub fn new_v2<S1, S2>(title: S1, format: S2) -> Self
/// # Arguments
/// - `aggregated` sets if the Series is a list due to aggregation (could also be a list because its
/// the columns dtype)
pub(crate) fn with_series(
/// Returns the number of tasks currently scheduled in the given worker's
/// local queue.
///
/// Tasks that are spawned or notified from within a runtime thread are
/// scheduled using that worker's local queue. This metric returns the
/// **current** number of tasks pending in the worker's local queue. As
/// such, the returned value may increase or decrease as new tasks are
/// scheduled and processed.
///
/// # Arguments
///
/// `worker` is the index of the worker being queried. The given value must
/// be between 0 and `num_workers()`. The index uniquely identifies a single
/// worker and will continue to identify the worker throughout the lifetime
/// of the runtime instance.
///
/// # Panics
///
/// The method panics when `worker` represents an invalid worker, i.e. is
/// greater than or equal to `num_workers()`.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Handle;
///
/// #[tokio::main]
/// async fn main() {
/// let metrics = Handle::current().metrics();
///
/// let n = metrics.worker_local_queue_depth(0);
/// println!("{} tasks currently pending in worker 0's local queue", n);
/// }
/// ```
pub fn worker_local_queue_depth(&self, worker: usize) -> usize {
/// A pattern in a local binding, function signature, match expression, or
/// various other places.
///
/// *This type is available only if Syn is built with the `"full"` feature.*
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// A single predicate in a `where` clause: `T: Deserialize<'de>`.
///
/// *This type is available only if Syn is built with the `"derive"` or `"full"`
/// feature.*
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// The possible types that a Rust value could have.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// A single predicate in a `where` clause: `T: Deserialize<'de>`.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// Things that can appear directly inside of a module or scope.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// A pattern in a local binding, function signature, match expression, or
/// various other places.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// A single predicate in a `where` clause: `T: Deserialize<'de>`.
///
/// *This type is available only if Syn is built with the `"derive"` or `"full"`
/// feature.*
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// The possible types that a Rust value could have.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: crate::expr::Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// An item within an `extern` block.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// The possible types that a Rust value could have.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// Content of a compile-time structured attribute.
///
/// ## Path
///
/// A meta path is like the `test` in `#[test]`.
///
/// ## List
///
/// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`.
///
/// ## NameValue
///
/// A name-value meta is like the `path = "..."` in `#[path =
/// "sys/windows.rs"]`.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// A suffix of an import tree in a `use` item: `Type as Renamed` or `*`.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// An item within an `extern` block.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// A suffix of an import tree in a `use` item: `Type as Renamed` or `*`.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// A generic type parameter, lifetime, or const generic: `T: Into<String>`,
/// `'a: 'b`, `const LEN: usize`.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// The storage of a struct, enum or union data structure.
///
/// *This type is available only if Syn is built with the `"derive"` feature.*
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
/// The visibility level of an item: inherited or `pub` or
/// `pub(restricted)`.
///
/// *This type is available only if Syn is built with the `"derive"` or `"full"`
/// feature.*
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// A Rust expression.
///
/// *This type is available only if Syn is built with the `"derive"` or `"full"`
/// feature, but most of the variants are not available unless "full" is enabled.*
///
/// # Syntax tree enums
///
/// This type is a syntax tree enum. In Syn this and other syntax tree enums
/// are designed to be traversed using the following rebinding idiom.
///
/// ```
/// # use syn::Expr;
/// #
/// # fn example(expr: Expr) {
/// # const IGNORE: &str = stringify! {
/// let expr: Expr = /* ... */;
/// # };
/// match expr {
/// Expr::MethodCall(expr) => {
/// /* ... */
/// }
/// Expr::Cast(expr) => {
/// /* ... */
/// }
/// Expr::If(expr) => {
/// /* ... */
/// }
///
/// /* ... */
/// # _ => {}
/// # }
/// # }
/// ```
///
/// We begin with a variable `expr` of type `Expr` that has no fields
/// (because it is an enum), and by matching on it and rebinding a variable
/// with the same name `expr` we effectively imbue our variable with all of
/// the data fields provided by the variant that it turned out to be. So for
/// example above if we ended up in the `MethodCall` case then we get to use
/// `expr.receiver`, `expr.args` etc; if we ended up in the `If` case we get
/// to use `expr.cond`, `expr.then_branch`, `expr.else_branch`.
///
/// This approach avoids repeating the variant names twice on every line.
///
/// ```
/// # use syn::{Expr, ExprMethodCall};
/// #
/// # fn example(expr: Expr) {
/// // Repetitive; recommend not doing this.
/// match expr {
/// Expr::MethodCall(ExprMethodCall { method, args, .. }) => {
/// # }
/// # _ => {}
/// # }
/// # }
/// ```
///
/// In general, the name to which a syntax tree enum variant is bound should
/// be a suitable name for the complete syntax tree enum type.
///
/// ```
/// # use syn::{Expr, ExprField};
/// #
/// # fn example(discriminant: ExprField) {
/// // Binding is called `base` which is the name I would use if I were
/// // assigning `*discriminant.base` without an `if let`.
/// if let Expr::Tuple(base) = *discriminant.base {
/// # }
/// # }
/// ```
///
/// A sign that you may not be choosing the right variable names is if you
/// see names getting repeated in your code, like accessing
/// `receiver.receiver` or `pat.pat` or `cond.cond`.
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// An item declaration within the definition of a trait.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// Data stored within an enum variant or struct.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// The visibility level of an item: inherited or `pub` or
/// `pub(restricted)`.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// An item within an impl block.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// A generic type parameter, lifetime, or const generic: `T: Into<String>`,
/// `'a: 'b`, `const LEN: usize`.
///
/// *This type is available only if Syn is built with the `"derive"` or `"full"`
/// feature.*
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// An item within an `extern` block.
///
/// *This type is available only if Syn is built with the `"full"` feature.*
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// The visibility level of an item: inherited or `pub` or
/// `pub(restricted)`.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// A suffix of an import tree in a `use` item: `Type as Renamed` or `*`.
///
/// *This type is available only if Syn is built with the `"full"` feature.*
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// A pattern in a local binding, function signature, match expression, or
/// various other places.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// An item declaration within the definition of a trait.
///
/// # Syntax tree enum
///
/// This type is a [syntax tree enum].
///
/// [syntax tree enum]: Expr#syntax-tree-enums
#[cfg_attr(doc_cfg, doc(cfg(feature = "full")))]
/// Advance the internal cursor of the BufMut
///
/// The next call to `chunk_mut` will return a slice starting `cnt` bytes
/// further into the underlying buffer.
///
/// This function is unsafe because there is no guarantee that the bytes
/// being advanced past have been initialized.
///
/// # Examples
///
/// ```
/// use bytes::BufMut;
///
/// let mut buf = Vec::with_capacity(16);
///
/// // Write some data
/// buf.chunk_mut()[0..2].copy_from_slice(b"he");
/// unsafe { buf.advance_mut(2) };
///
/// // write more bytes
/// buf.chunk_mut()[0..3].copy_from_slice(b"llo");
///
/// unsafe { buf.advance_mut(3); }
///
/// assert_eq!(5, buf.len());
/// assert_eq!(buf, b"hello");
/// ```
///
/// # Panics
///
/// This function **may** panic if `cnt > self.remaining_mut()`.
///
/// # Implementer notes
///
/// It is recommended for implementations of `advance_mut` to panic if
/// `cnt > self.remaining_mut()`. If the implementation does not panic,
/// the call must behave as if `cnt == self.remaining_mut()`.
///
/// A call with `cnt == 0` should never panic and be a no-op.
unsafe fn advance_mut(&mut self, cnt: usize);
/// Slices this [`Array`].
/// # Implementation
/// This operation is `O(1)` over `len`.
/// # Panic
/// This function panics iff `offset + length > self.len()`.
fn slice_typed(&self, offset: usize, length: usize) -> Self
/// Returns a mutable slice starting at the current BufMut position and of
/// length between 0 and `BufMut::remaining_mut()`. Note that this *can* be shorter than the
/// whole remainder of the buffer (this allows non-continuous implementation).
///
/// This is a lower level function. Most operations are done with other
/// functions.
///
/// The returned byte slice may represent uninitialized memory.
///
/// # Examples
///
/// ```
/// use bytes::BufMut;
///
/// let mut buf = Vec::with_capacity(16);
///
/// unsafe {
/// // MaybeUninit::as_mut_ptr
/// buf.bytes_mut()[0].as_mut_ptr().write(b'h');
/// buf.bytes_mut()[1].as_mut_ptr().write(b'e');
///
/// buf.advance_mut(2);
///
/// buf.bytes_mut()[0].as_mut_ptr().write(b'l');
/// buf.bytes_mut()[1].as_mut_ptr().write(b'l');
/// buf.bytes_mut()[2].as_mut_ptr().write(b'o');
///
/// buf.advance_mut(3);
/// }
///
/// assert_eq!(5, buf.len());
/// assert_eq!(buf, b"hello");
/// ```
///
/// # Implementer notes
///
/// This function should never panic. `bytes_mut` should return an empty
/// slice **if and only if** `remaining_mut` returns 0. In other words,
/// `bytes_mut` returning an empty slice implies that `remaining_mut` will
/// return 0 and `remaining_mut` returning 0 implies that `bytes_mut` will
/// return an empty slice.
fn bytes_mut(&mut self) -> &mut [MaybeUninit<u8>];
/// Fills `dst` with potentially multiple slices starting at `self`'s
/// current position.
///
/// If the `Buf` is backed by disjoint slices of bytes, `chunk_vectored` enables
/// fetching more than one slice at once. `dst` is a slice of `IoSlice`
/// references, enabling the slice to be directly used with [`writev`]
/// without any further conversion. The sum of the lengths of all the
/// buffers in `dst` will be less than or equal to `Buf::remaining()`.
///
/// The entries in `dst` will be overwritten, but the data **contained** by
/// the slices **will not** be modified. If `chunk_vectored` does not fill every
/// entry in `dst`, then `dst` is guaranteed to contain all remaining slices
/// in `self.
///
/// This is a lower level function. Most operations are done with other
/// functions.
///
/// # Implementer notes
///
/// This function should never panic. Once the end of the buffer is reached,
/// i.e., `Buf::remaining` returns 0, calls to `chunk_vectored` must return 0
/// without mutating `dst`.
///
/// Implementations should also take care to properly handle being called
/// with `dst` being a zero length slice.
///
/// [`writev`]: http://man7.org/linux/man-pages/man2/readv.2.html
#[cfg(feature = "std")]
/// Slices this [`StructArray`].
/// # Panics
/// * `offset + length` must be smaller than `self.len()`.
/// # Implementation
/// This operation is `O(F)` where `F` is the number of fields.
pub fn slice(&mut self, offset: usize, length: usize) {
/// Sorts the slice in parallel with a key extraction function.
///
/// During sorting, the key function is called at most once per element, by using
/// temporary storage to remember the results of key evaluation.
/// The key function is called in parallel, so the order of calls is completely unspecified.
///
/// This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* + *n* \* log(*n*))
/// worst-case, where the key function is *O*(*m*).
///
/// For simple key functions (e.g., functions that are property accesses or
/// basic operations), [`par_sort_by_key`](#method.par_sort_by_key) is likely to be
/// faster.
///
/// # Current implementation
///
/// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
/// which combines the fast average case of randomized quicksort with the fast worst case of
/// heapsort, while achieving linear time on slices with certain patterns. It uses some
/// randomization to avoid degenerate cases, but with a fixed seed to always provide
/// deterministic behavior.
///
/// In the worst case, the algorithm allocates temporary storage in a `Vec<(K, usize)>` the
/// length of the slice.
///
/// All quicksorts work in two stages: partitioning into two halves followed by recursive
/// calls. The partitioning phase is sequential, but the two recursive calls are performed in
/// parallel. Finally, after sorting the cached keys, the item positions are updated sequentially.
///
/// [pdqsort]: https://github.com/orlp/pdqsort
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let mut v = [-5i32, 4, 32, -3, 2];
///
/// v.par_sort_by_cached_key(|k| k.to_string());
/// assert!(v == [-3, -5, 2, 32, 4]);
/// ```
fn par_sort_by_cached_key<K, F>(&mut self, f: F)
/// Sorts the slice in parallel, but might not preserve the order of equal elements.
///
/// This sort is unstable (i.e., may reorder equal elements), in-place
/// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
///
/// # Current implementation
///
/// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
/// which combines the fast average case of randomized quicksort with the fast worst case of
/// heapsort, while achieving linear time on slices with certain patterns. It uses some
/// randomization to avoid degenerate cases, but with a fixed seed to always provide
/// deterministic behavior.
///
/// It is typically faster than stable sorting, except in a few special cases, e.g., when the
/// slice consists of several concatenated sorted sequences.
///
/// All quicksorts work in two stages: partitioning into two halves followed by recursive
/// calls. The partitioning phase is sequential, but the two recursive calls are performed in
/// parallel.
///
/// [pdqsort]: https://github.com/orlp/pdqsort
///
/// # Examples
///
/// ```
/// use rayon::prelude::*;
///
/// let mut v = [-5, 4, 1, -3, 2];
///
/// v.par_sort_unstable();
/// assert_eq!(v, [-5, -3, 1, 2, 4]);
/// ```
fn par_sort_unstable(&mut self)
/// Returns a [`MutableUtf8Array`] created from its internal representation.
///
/// # Errors
/// This function returns an error iff:
/// * The last offset is not equal to the values' length.
/// * the validity's length is not equal to `offsets.len()`.
/// * The `data_type`'s [`crate::datatypes::PhysicalType`] is not equal to either `Utf8` or `LargeUtf8`.
/// * The `values` between two consecutive `offsets` are not valid utf8
/// # Implementation
/// This function is `O(N)` - checking utf8 is `O(N)`
pub fn try_new(
/// Returns this array sliced.
/// # Implementation
/// This function is `O(1)`.
/// # Panics
/// iff `offset + length > self.len()`.
#[inline]
/// Reorder the slice such that the element at `index` after the reordering is at its final sorted position.
///
/// This reordering has the additional property that any value at position `i < index` will be
/// less than or equal to any value at a position `j > index`. Additionally, this reordering is
/// unstable (i.e. any number of equal elements may end up at position `index`), in-place
/// (i.e. does not allocate), and runs in *O*(*n*) time.
/// This function is also known as "kth element" in other libraries.
///
/// It returns a triplet of the following from the reordered slice:
/// the subslice prior to `index`, the element at `index`, and the subslice after `index`;
/// accordingly, the values in those two subslices will respectively all be less-than-or-equal-to
/// and greater-than-or-equal-to the value of the element at `index`.
///
/// # Current implementation
///
/// The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also
/// the basis for [`sort_unstable`]. The fallback algorithm is Median of Medians using Tukey's Ninther for
/// pivot selection, which guarantees linear runtime for all inputs.
///
/// [`sort_unstable`]: slice::sort_unstable
///
/// # Panics
///
/// Panics when `index >= len()`, meaning it always panics on empty slices.
///
/// # Examples
///
/// ```
/// let mut v = [-5i32, 4, 2, -3, 1];
///
/// // Find the items less than or equal to the median, the median, and greater than or equal to
/// // the median.
/// let (lesser, median, greater) = v.select_nth_unstable(2);
///
/// assert!(lesser == [-3, -5] || lesser == [-5, -3]);
/// assert_eq!(median, &mut 1);
/// assert!(greater == [4, 2] || greater == [2, 4]);
///
/// // We are only guaranteed the slice will be one of the following, based on the way we sort
/// // about the specified index.
/// assert!(v == [-3, -5, 1, 2, 4] ||
/// v == [-5, -3, 1, 2, 4] ||
/// v == [-3, -5, 1, 4, 2] ||
/// v == [-5, -3, 1, 4, 2]);
/// ```
#[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
/// Grows the `Block` linked list by allocating and appending a new block.
///
/// The next block in the linked list is returned. This may or may not be
/// the one allocated by the function call.
///
/// # Implementation
///
/// It is assumed that `self.next` is null. A new block is allocated with
/// `start_index` set to be the next block. A compare-and-swap is performed
/// with AcqRel memory ordering. If the compare-and-swap is successful, the
/// newly allocated block is released to other threads walking the block
/// linked list. If the compare-and-swap fails, the current thread acquires
/// the next block in the linked list, allowing the current thread to access
/// the slots.
pub(crate) fn grow(&self) -> NonNull<Block<T>> {
/// Fills `dst` with potentially multiple slices starting at `self`'s
/// current position.
///
/// If the `Buf` is backed by disjoint slices of bytes, `chunk_vectored` enables
/// fetching more than one slice at once. `dst` is a slice of `IoSlice`
/// references, enabling the slice to be directly used with [`writev`]
/// without any further conversion. The sum of the lengths of all the
/// buffers in `dst` will be less than or equal to `Buf::remaining()`.
///
/// The entries in `dst` will be overwritten, but the data **contained** by
/// the slices **will not** be modified. If `chunk_vectored` does not fill every
/// entry in `dst`, then `dst` is guaranteed to contain all remaining slices
/// in `self.
///
/// This is a lower level function. Most operations are done with other
/// functions.
///
/// # Implementer notes
///
/// This function should never panic. Once the end of the buffer is reached,
/// i.e., `Buf::remaining` returns 0, calls to `chunk_vectored` must return 0
/// without mutating `dst`.
///
/// Implementations should also take care to properly handle being called
/// with `dst` being a zero length slice.
///
/// [`writev`]: http://man7.org/linux/man-pages/man2/readv.2.html
#[cfg(feature = "std")]
/// Advance the internal cursor of the BufMut
///
/// The next call to `chunk_mut` will return a slice starting `cnt` bytes
/// further into the underlying buffer.
///
/// This function is unsafe because there is no guarantee that the bytes
/// being advanced past have been initialized.
///
/// # Examples
///
/// ```
/// use bytes::BufMut;
///
/// let mut buf = Vec::with_capacity(16);
///
/// // Write some data
/// buf.chunk_mut()[0..2].copy_from_slice(b"he");
/// unsafe { buf.advance_mut(2) };
///
/// // write more bytes
/// buf.chunk_mut()[0..3].copy_from_slice(b"llo");
///
/// unsafe { buf.advance_mut(3); }
///
/// assert_eq!(5, buf.len());
/// assert_eq!(buf, b"hello");
/// ```
///
/// # Panics
///
/// This function **may** panic if `cnt > self.remaining_mut()`.
///
/// # Implementer notes
///
/// It is recommended for implementations of `advance_mut` to panic if
/// `cnt > self.remaining_mut()`. If the implementation does not panic,
/// the call must behave as if `cnt == self.remaining_mut()`.
///
/// A call with `cnt == 0` should never panic and be a no-op.
unsafe fn advance_mut(&mut self, cnt: usize);
/// Returns the bounds on the remaining length of the async iterator.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
/// A [`None`] here means that either there is no known upper bound, or the
/// upper bound is larger than [`usize`].
///
/// # Implementation notes
///
/// It is not enforced that an async iterator implementation yields the declared
/// number of elements. A buggy async iterator may yield less than the lower bound
/// or more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the async iterator, but must not be
/// trusted to e.g., omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
/// That said, the implementation should provide a correct estimation,
/// because otherwise it would be a violation of the trait's protocol.
///
/// The default implementation returns <code>(0, [None])</code> which is correct for any
/// async iterator.
#[inline]
/// Returns a slice of this [`UnionArray`].
/// # Implementation
/// This operation is `O(F)` where `F` is the number of fields.
/// # Panic
/// This function panics iff `offset + length >= self.len()`.
#[inline]
/// Returns `true` when all slots have their `ready` bits set.
///
/// This indicates that the block is in its final state and will no longer
/// be mutated.
///
/// # Implementation
///
/// The implementation walks each slot checking the `ready` flag. It might
/// be that it would make more sense to coalesce ready flags as bits in a
/// single atomic cell. However, this could have negative impact on cache
/// behavior as there would be many more mutations to a single slot.
pub(crate) fn is_final(&self) -> bool {
/// Reorder the slice with a key extraction function such that the element at `index` after the reordering is
/// at its final sorted position.
///
/// This reordering has the additional property that any value at position `i < index` will be
/// less than or equal to any value at a position `j > index` using the key extraction function.
/// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
/// position `index`), in-place (i.e. does not allocate), and runs in *O*(*n*) time.
/// This function is also known as "kth element" in other libraries.
///
/// It returns a triplet of the following from
/// the slice reordered according to the provided key extraction function: the subslice prior to
/// `index`, the element at `index`, and the subslice after `index`; accordingly, the values in
/// those two subslices will respectively all be less-than-or-equal-to and greater-than-or-equal-to
/// the value of the element at `index`.
///
/// # Current implementation
///
/// The current algorithm is an introselect implementation based on Pattern Defeating Quicksort, which is also
/// the basis for [`sort_unstable`]. The fallback algorithm is Median of Medians using Tukey's Ninther for
/// pivot selection, which guarantees linear runtime for all inputs.
///
/// [`sort_unstable`]: slice::sort_unstable
///
/// # Panics
///
/// Panics when `index >= len()`, meaning it always panics on empty slices.
///
/// # Examples
///
/// ```
/// let mut v = [-5i32, 4, 1, -3, 2];
///
/// // Find the items less than or equal to the median, the median, and greater than or equal to
/// // the median as if the slice were sorted according to absolute value.
/// let (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());
///
/// assert!(lesser == [1, 2] || lesser == [2, 1]);
/// assert_eq!(median, &mut -3);
/// assert!(greater == [4, -5] || greater == [-5, 4]);
///
/// // We are only guaranteed the slice will be one of the following, based on the way we sort
/// // about the specified index.
/// assert!(v == [1, 2, -3, 4, -5] ||
/// v == [1, 2, -3, -5, 4] ||
/// v == [2, 1, -3, 4, -5] ||
/// v == [2, 1, -3, -5, 4]);
/// ```
#[stable(feature = "slice_select_nth_unstable", since = "1.49.0")]
/// Returns a [`MutableUtf8ValuesArray`] created from its internal representation.
///
/// # Errors
/// This function returns an error iff:
/// * The last offset is not equal to the values' length.
/// * The `data_type`'s [`crate::datatypes::PhysicalType`] is not equal to either `Utf8` or `LargeUtf8`.
/// * The `values` between two consecutive `offsets` are not valid utf8
/// # Implementation
/// This function is `O(N)` - checking utf8 is `O(N)`
pub fn try_new(
/// Count the number of key-values that can be visited.
///
/// # Implementation notes
///
/// A source that knows the number of key-values upfront may provide a more
/// efficient implementation.
///
/// A subsequent call to `visit` should yield the same number of key-values.
fn count(&self) -> usize {
/// Creates a (non-null) [`PrimitiveArray`] from an iterator of values.
/// # Implementation
/// This does not assume that the iterator has a known length.
pub fn from_values<I: IntoIterator<Item = T>>(iter: I) -> Self {
/// Count the number of key-value pairs that can be visited.
///
/// # Implementation notes
///
/// A source that knows the number of key-value pairs upfront may provide a more
/// efficient implementation.
///
/// A subsequent call to `visit` should yield the same number of key-value pairs
/// to the visitor, unless that visitor fails part way through.
fn count(&self) -> usize {
/// Returns the number of bytes between the current position and the end of
/// the buffer.
///
/// This value is greater than or equal to the length of the slice returned
/// by `chunk()`.
///
/// # Examples
///
/// ```
/// use bytes::Buf;
///
/// let mut buf = &b"hello world"[..];
///
/// assert_eq!(buf.remaining(), 11);
///
/// buf.get_u8();
///
/// assert_eq!(buf.remaining(), 10);
/// ```
///
/// # Implementer notes
///
/// Implementations of `remaining` should ensure that the return value does
/// not change unless a call is made to `advance` or any other function that
/// is documented to change the `Buf`'s current position.
fn remaining(&self) -> usize;
/// Returns a slice of this [`UnionArray`].
/// # Implementation
/// This operation is `O(F)` where `F` is the number of fields.
///
/// # Safety
/// The caller must ensure that `offset + length <= self.len()`.
#[inline]
/// Slices the [`Array`].
/// # Implementation
/// This operation is `O(1)`.
///
/// # Safety
/// The caller must ensure that `offset + length <= self.len()`
unsafe fn slice_unchecked(&mut self, offset: usize, length: usize);
/// Slices this [`FixedSizeBinaryArray`].
/// # Implementation
/// This operation is `O(1)`.
///
/// # Safety
/// The caller must ensure that `offset + length <= self.len()`.
pub unsafe fn slice_unchecked(&mut self, offset: usize, length: usize) {
/// The canonical method to create a [`PrimitiveArray`] out of its internal components.
/// # Implementation
/// This function is `O(1)`.
///
/// # Errors
/// This function errors iff:
/// * The validity is not `None` and its length is different from `values`'s length
/// * The `data_type`'s [`PhysicalType`] is not equal to [`PhysicalType::Primitive(T::PRIMITIVE)`]
pub fn try_new(
/// Visit key-values.
///
/// A source doesn't have to guarantee any ordering or uniqueness of key-values.
/// If the given visitor returns an error then the source may early-return with it,
/// even if there are more key-values.
///
/// # Implementation notes
///
/// A source should yield the same key-values to a subsequent visitor unless
/// that visitor itself fails.
fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error>;
/// Returns a [`MutableBinaryValuesArray`] created from its internal representation.
///
/// # Errors
/// This function returns an error iff:
/// * The last offset is not equal to the values' length.
/// * The `data_type`'s [`crate::datatypes::PhysicalType`] is not equal to either `Binary` or `LargeBinary`.
/// # Implementation
/// This function is `O(1)`
pub fn try_new(
/// Initiates a client-side TLS handshake.
///
/// # Warning
///
/// OpenSSL's default configuration is insecure. It is highly recommended to use
/// `SslConnector` rather than `Ssl` directly, as it manages that configuration.
#[corresponds(SSL_connect)]
/// Returns a mutable reference to the underlying stream.
///
/// # Warning
///
/// It is inadvisable to read from or write to the underlying stream as it
/// will most likely corrupt the SSL session.
pub fn get_mut(&mut self) -> &mut S {
/// Display the diagnostic while not aborting macro execution.
///
/// # Warnings
///
/// Warnings are ignored on stable/beta
pub fn emit(self) {
/// The SSL 3.0 protocol.
///
/// # Warning
///
/// SSL 3.0 has severe security flaws, and should not be used unless absolutely necessary. If
/// you are not sure if you need to enable this protocol, you should not.
Sslv3,
/// The TLS 1.0 protocol.
Tlsv10,
/// The TLS 1.1 protocol.
Tlsv11,
/// The TLS 1.2 protocol.
Tlsv12,
/// Configures the use of hostname verification when connecting.
///
/// Defaults to `true`.
///
/// # Warning
///
/// You should think very carefully before you use this method. If hostname verification is not
/// used, *any* valid certificate for *any* site will be trusted for use from any other. This
/// introduces a significant vulnerability to man-in-the-middle attacks.
pub fn set_verify_hostname(&mut self, verify_hostname: bool) {
/// Controls the use of certificate validation.
///
/// Defaults to `false`.
///
/// # Warning
///
/// You should think very carefully before using this method. If invalid certificates are trusted, *any*
/// certificate for *any* site will be trusted for use. This includes expired certificates. This introduces
/// significant vulnerabilities, and should only be used as a last resort.
pub fn danger_accept_invalid_certs(
/// This is an iterator over a [`ListChunked`] that save allocations.
/// A Series is:
/// 1. [`Arc<ChunkedArray>`]
/// ChunkedArray is:
/// 2. Vec< 3. ArrayRef>
///
/// The ArrayRef we indicated with 3. will be updated during iteration.
/// The Series will be pinned in memory, saving an allocation for
/// 1. Arc<..>
/// 2. Vec<...>
///
/// # Warning
/// Though memory safe in the sense that it will not read unowned memory, UB, or memory leaks
/// this function still needs precautions. The returned should never be cloned or taken longer
/// than a single iteration, as every call on `next` of the iterator will change the contents of
/// that Series.
///
/// # Safety
/// The lifetime of [UnstableSeries] is bound to the iterator. Keeping it alive
/// longer than the iterator is UB.
pub unsafe fn amortized_iter(
/// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
/// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
/// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
/// it is obviously not reserved for future use.
///
/// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
///
/// # Warning
///
/// As IANA assigns new addresses, this method will be
/// updated. This may result in non-reserved addresses being
/// treated as reserved in code that relies on an outdated version
/// of this method.
///
/// # Examples
///
/// ```
/// #![feature(ip)]
/// use std::net::Ipv4Addr;
///
/// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
/// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
///
/// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
/// // The broadcast address is not considered as reserved for future use by this implementation
/// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
/// ```
#[cfg_attr(
/// The SSL 3.0 protocol.
///
/// # Warning
///
/// SSL 3.0 has severe security flaws, and should not be used unless absolutely necessary. If
/// you are not sure if you need to enable this protocol, you should not.
Sslv3,
/// The TLS 1.0 protocol.
Tlsv10,
/// The TLS 1.1 protocol.
Tlsv11,
/// The TLS 1.2 protocol.
Tlsv12,
/// Initiates a client-side TLS handshake.
///
/// # Warning
///
/// OpenSSL's default configuration is insecure. It is highly recommended to use
/// `SslConnector` rather than `Ssl` directly, as it manages that configuration.
#[corresponds(SSL_connect)]
/// Returns a mutable reference to the underlying stream.
///
/// # Warning
///
/// It is inadvisable to read from or write to the underlying stream as it
/// will most likely corrupt the SSL session.
pub fn get_mut(&mut self) -> &mut S {
/// Effectively forwards to the parent [`StreamingPeekableIter::peek_line()`], allowing to see what would be returned
/// next on a call to [`read_line()`][io::BufRead::read_line()].
///
/// # Warning
///
/// This skips all sideband handling and may return an unprocessed line with sidebands still contained in it.
pub fn peek_data_line(&mut self) -> Option<io::Result<Result<&[u8], crate::decode::Error>>> {
/// Puts the signal information inside the slot.
///
/// It needs to somehow store the relevant information and the fact that a signal happened.
///
/// # Warning
///
/// This will be called inside the signal handler. It needs to be async-signal-safe. In
/// particular, very small amount of operations are allowed in there. This namely does
/// *not* include any locking nor allocation.
///
/// It is also possible that multiple store methods are called concurrently; it is up to
/// the implementor to deal with that.
fn store(&self, slot: &Self::Storage, signal: c_int, info: &siginfo_t);
/// Initiates a server-side TLS handshake.
///
/// This corresponds to [`SSL_accept`].
///
/// # Warning
///
/// OpenSSL's default configuration is insecure. It is highly recommended to use
/// `SslAcceptor` rather than `Ssl` directly, as it manages that configuration.
///
/// [`SSL_accept`]: https://www.openssl.org/docs/manmaster/man3/SSL_accept.html
#[corresponds(SSL_accept)]
/// Initiates a server-side TLS handshake.
///
/// This corresponds to [`SSL_accept`].
///
/// # Warning
///
/// OpenSSL's default configuration is insecure. It is highly recommended to use
/// `SslAcceptor` rather than `Ssl` directly, as it manages that configuration.
///
/// [`SSL_accept`]: https://www.openssl.org/docs/manmaster/man3/SSL_accept.html
#[corresponds(SSL_accept)]
/// Initiates a client-side TLS handshake.
///
/// This corresponds to [`SSL_connect`].
///
/// # Warning
///
/// OpenSSL's default configuration is insecure. It is highly recommended to use
/// `SslConnector` rather than `Ssl` directly, as it manages that configuration.
///
/// [`SSL_connect`]: https://www.openssl.org/docs/manmaster/man3/SSL_connect.html
#[corresponds(SSL_connect)]
/// An object which calculates a SHA1 hash of some data.
///
/// # Warning
///
/// SHA1 is known to be insecure - it should not be used unless required for
/// compatibility with existing systems.
#[derive(Clone)]
/// Run an expression over a sliding window that increases `1` slot every iteration.
///
/// # Warning
/// This can be really slow as it can have `O(n^2)` complexity. Don't use this for operations
/// that visit all elements.
fn cumulative_eval(self, expr: Expr, min_periods: usize, parallel: bool) -> Expr {
/// An object which calculates a SHA1 hash of some data.
///
/// # Warning
///
/// SHA1 is known to be insecure - it should not be used unless required for
/// compatibility with existing systems.
#[derive(Clone)]
/// Read a packet line from the underlying packet reader, returning empty lines if a stop-packetline was reached.
///
/// # Warning
///
/// This skips all sideband handling and may return an unprocessed line with sidebands still contained in it.
pub async fn read_data_line(&mut self) -> Option<std::io::Result<Result<PacketLineRef<'_>, decode::Error>>> {
/// Format for this is `(host, port)`.
Tcp(String, u16),
/// Format for this is `(host, port)`.
TcpTls {
/// Hostname
host: String,
/// Port
port: u16,
/// Disable hostname verification when connecting.
///
/// # Warning
///
/// You should think very carefully before you use this method. If hostname
/// verification is not used, any valid certificate for any site will be
/// trusted for use from any other. This introduces a significant
/// vulnerability to man-in-the-middle attacks.
insecure: bool,
/// Initiates a server-side TLS handshake.
///
/// # Warning
///
/// OpenSSL's default configuration is insecure. It is highly recommended to use
/// `SslAcceptor` rather than `Ssl` directly, as it manages that configuration.
#[corresponds(SSL_accept)]
/// Add a new column at index 0 that counts the rows.
///
/// `name` is the name of the new column. `offset` is where to start counting from; if
/// `None`, it is set to `0`.
///
/// # Warning
/// This can have a negative effect on query performance. This may for instance block
/// predicate pushdown optimization.
pub fn with_row_index(mut self, name: &str, offset: Option<IdxSize>) -> LazyFrame {
/// Initiate a connection on this socket to the specified address, only
/// only waiting for a certain period of time for the connection to be
/// established.
///
/// Unlike many other methods on `Socket`, this does *not* correspond to a
/// single C function. It sets the socket to nonblocking mode, connects via
/// connect(2), and then waits for the connection to complete with poll(2)
/// on Unix and select on Windows. When the connection is complete, the
/// socket is set back to blocking mode. On Unix, this will loop over
/// `EINTR` errors.
///
/// # Warnings
///
/// The nonblocking state of the socket is overridden by this function -
/// it will be returned in blocking mode on success, and in an indeterminate
/// state on failure.
///
/// If the connection request times out, it may still be processing in the
/// background - a second call to `connect` or `connect_timeout` may fail.
pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> {
/// Read a whole packetline from the underlying reader, with empty lines indicating a stop packetline.
///
/// # Warning
///
/// This skips all sideband handling and may return an unprocessed line with sidebands still contained in it.
pub fn read_data_line(&mut self) -> Option<io::Result<Result<PacketLineRef<'_>, crate::decode::Error>>> {
/// Get access to the underlying SQLite database connection handle.
///
/// # Warning
///
/// You should not need to use this function. If you do need to, please
/// [open an issue on the rusqlite repository](https://github.com/rusqlite/rusqlite/issues) and describe
/// your use case.
///
/// # Safety
///
/// This function is unsafe because it gives you raw access
/// to the SQLite connection, and what you do with it could impact the
/// safety of this `Connection`.
#[inline]
/// Initiates a client-side TLS handshake.
///
/// This corresponds to [`SSL_connect`].
///
/// # Warning
///
/// OpenSSL's default configuration is insecure. It is highly recommended to use
/// `SslConnector` rather than `Ssl` directly, as it manages that configuration.
///
/// [`SSL_connect`]: https://www.openssl.org/docs/manmaster/man3/SSL_connect.html
#[corresponds(SSL_connect)]
/// Returns a mutable reference to the underlying stream.
///
/// # Warning
///
/// It is inadvisable to read from or write to the underlying stream as it
/// will most likely corrupt the SSL session.
pub fn get_mut(&mut self) -> &mut S {
/// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
/// to hash the keys.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashMap to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut map = HashMap::with_capacity_and_hasher(10, s);
/// assert_eq!(map.len(), 0);
/// assert!(map.capacity() >= 10);
///
/// map.insert(1, 2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates a new empty hash set which will use the given hasher to hash
/// keys.
///
/// The hash set is initially created with a capacity of 0, so it will not
/// allocate until it is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashSet to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut set = HashSet::with_hasher(s);
/// set.insert(2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet`.
///
/// The hash set is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`], for example with
/// [`with_hasher`](HashSet::with_hasher) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// let set: HashSet<i32> = HashSet::new();
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates a new empty hash set which will use the given hasher to hash
/// keys.
///
/// The hash set is initially created with a capacity of 0, so it will not
/// allocate until it is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashSet to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut set = HashSet::with_hasher(s);
/// set.insert(2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet` with the specified capacity.
///
/// The hash set will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash set will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`], for example with
/// [`with_capacity_and_hasher`](HashSet::with_capacity_and_hasher) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// let set: HashSet<i32> = HashSet::with_capacity(10);
/// assert!(set.capacity() >= 10);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` which will use the given hash builder to hash
/// keys. It will be allocated with the given allocator.
///
/// The hash map is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`].
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut map = HashMap::with_hasher(s);
/// map.insert(1, 2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates a new empty hash set which will use the given hasher to hash
/// keys.
///
/// The hash set is initially created with a capacity of 0, so it will not
/// allocate until it is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashSet to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut set = HashSet::with_hasher(s);
/// set.insert(2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` using the given allocator.
///
/// The hash map is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`], for example with
/// [`with_hasher_in`](HashMap::with_hasher_in) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use bumpalo::Bump;
///
/// let bump = Bump::new();
/// let mut map = HashMap::new_in(&bump);
///
/// // The created HashMap holds none elements
/// assert_eq!(map.len(), 0);
///
/// // The created HashMap also doesn't allocate memory
/// assert_eq!(map.capacity(), 0);
///
/// // Now we insert element inside created HashMap
/// map.insert("One", 1);
/// // We can see that the HashMap holds 1 element
/// assert_eq!(map.len(), 1);
/// // And it also allocates some capacity
/// assert!(map.capacity() > 1);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet`.
///
/// The hash set is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`], for example with
/// [`with_hasher_in`](HashSet::with_hasher_in) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// let set: HashSet<i32> = HashSet::new();
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet` with the specified capacity, using
/// `hasher` to hash the keys.
///
/// The hash set will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash set will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashSet to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut set = HashSet::with_capacity_and_hasher(10, s);
/// set.insert(1);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` which will use the given hash builder to hash
/// keys. It will be allocated with the given allocator.
///
/// The hash map is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`].
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut map = HashMap::with_hasher(s);
/// map.insert(1, 2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet` with the specified capacity.
///
/// The hash set will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash set will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`], for example with
/// [`with_capacity_and_hasher`](HashSet::with_capacity_and_hasher) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// let set: HashSet<i32> = HashSet::with_capacity(10);
/// assert!(set.capacity() >= 10);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet` with the specified capacity, using
/// `hasher` to hash the keys.
///
/// The hash set will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash set will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashSet to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut set = HashSet::with_capacity_and_hasher(10, s);
/// set.insert(1);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap`.
///
/// The hash map is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`], for example with
/// [`with_hasher`](HashMap::with_hasher) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// let mut map: HashMap<&str, i32> = HashMap::new();
/// assert_eq!(map.len(), 0);
/// assert_eq!(map.capacity(), 0);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
/// to hash the keys.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashMap to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut map = HashMap::with_capacity_and_hasher(10, s);
/// assert_eq!(map.len(), 0);
/// assert!(map.capacity() >= 10);
///
/// map.insert(1, 2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet` with the specified capacity, using
/// `hasher` to hash the keys.
///
/// The hash set will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash set will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashSet to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut set = HashSet::with_capacity_and_hasher(10, s);
/// set.insert(1);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet` with the specified capacity, using
/// `hasher` to hash the keys.
///
/// The hash set will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash set will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashSet to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut set = HashSet::with_capacity_and_hasher(10, s);
/// set.insert(1);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet` with the specified capacity.
///
/// The hash set will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash set will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`], for example with
/// [`with_capacity_and_hasher_in`](HashSet::with_capacity_and_hasher_in) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// let set: HashSet<i32> = HashSet::with_capacity(10);
/// assert!(set.capacity() >= 10);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
/// to hash the keys.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashMap to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut map = HashMap::with_capacity_and_hasher(10, s);
/// assert_eq!(map.len(), 0);
/// assert!(map.capacity() >= 10);
///
/// map.insert(1, 2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` with the specified capacity.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`], for example with
/// [`with_capacity_and_hasher`](HashMap::with_capacity_and_hasher) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
/// assert_eq!(map.len(), 0);
/// assert!(map.capacity() >= 10);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` with the specified capacity using the given allocator.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`], for example with
/// [`with_capacity_and_hasher_in`](HashMap::with_capacity_and_hasher_in) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use bumpalo::Bump;
///
/// let bump = Bump::new();
/// let mut map = HashMap::with_capacity_in(5, &bump);
///
/// // The created HashMap holds none elements
/// assert_eq!(map.len(), 0);
/// // But it can hold at least 5 elements without reallocating
/// let empty_map_capacity = map.capacity();
/// assert!(empty_map_capacity >= 5);
///
/// // Now we insert some 5 elements inside created HashMap
/// map.insert("One", 1);
/// map.insert("Two", 2);
/// map.insert("Three", 3);
/// map.insert("Four", 4);
/// map.insert("Five", 5);
///
/// // We can see that the HashMap holds 5 elements
/// assert_eq!(map.len(), 5);
/// // But its capacity isn't changed
/// assert_eq!(map.capacity(), empty_map_capacity)
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet` with the specified capacity, using
/// `hasher` to hash the keys.
///
/// The hash set will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash set will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashSet to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut set = HashSet::with_capacity_and_hasher(10, s);
/// set.insert(1);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
/// to hash the keys.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`].
///
/// The `hash_builder` passed should implement the [`BuildHasher`] trait for
/// the HashMap to be useful, see its documentation for details.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
/// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut map = HashMap::with_capacity_and_hasher(10, s);
/// assert_eq!(map.len(), 0);
/// assert!(map.capacity() >= 10);
///
/// map.insert(1, 2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
/// to hash the keys. It will be allocated with the given allocator.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`].
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use hashbrown::hash_map::DefaultHashBuilder;
///
/// let s = DefaultHashBuilder::default();
/// let mut map = HashMap::with_capacity_and_hasher(10, s);
/// map.insert(1, 2);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashSet`.
///
/// The hash set is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashSet`], for example with
/// [`with_hasher`](HashSet::with_hasher) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
/// let set: HashSet<i32> = HashSet::new();
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` with the specified capacity.
///
/// The hash map will be able to hold at least `capacity` elements without
/// reallocating. If `capacity` is 0, the hash map will not allocate.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`], for example with
/// [`with_capacity_and_hasher`](HashMap::with_capacity_and_hasher) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
/// assert_eq!(map.len(), 0);
/// assert!(map.capacity() >= 10);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap` using the given allocator.
///
/// The hash map is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`], for example with
/// [`with_hasher_in`](HashMap::with_hasher_in) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// use bumpalo::Bump;
///
/// let bump = Bump::new();
/// let mut map = HashMap::new_in(&bump);
///
/// // The created HashMap holds none elements
/// assert_eq!(map.len(), 0);
///
/// // The created HashMap also doesn't allocate memory
/// assert_eq!(map.capacity(), 0);
///
/// // Now we insert element inside created HashMap
/// map.insert("One", 1);
/// // We can see that the HashMap holds 1 element
/// assert_eq!(map.len(), 1);
/// // And it also allocates some capacity
/// assert!(map.capacity() > 1);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Creates an empty `HashMap`.
///
/// The hash map is initially created with a capacity of 0, so it will not allocate until it
/// is first inserted into.
///
/// # HashDoS resistance
///
/// The `hash_builder` normally use a fixed key by default and that does
/// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
/// Users who require HashDoS resistance should explicitly use
/// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
/// as the hasher when creating a [`HashMap`], for example with
/// [`with_hasher`](HashMap::with_hasher) method.
///
/// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
/// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
///
/// # Examples
///
/// ```
/// use hashbrown::HashMap;
/// let mut map: HashMap<&str, i32> = HashMap::new();
/// assert_eq!(map.len(), 0);
/// assert_eq!(map.capacity(), 0);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
/// Execute an INSERT and return the ROWID.
///
/// # Note
///
/// This function is a convenience wrapper around
/// [`execute()`](Statement::execute) intended for queries that insert a
/// single item. It is possible to misuse this function in a way that it
/// cannot detect, such as by calling it on a statement which _updates_
/// a single item rather than inserting one. Please don't do that.
///
/// # Failure
///
/// Will return `Err` if no row is inserted or many rows are inserted.
#[inline]
/// Read data from a BLOB incrementally. Will return Ok(0) if the end of
/// the blob has been reached.
///
/// # Failure
///
/// Will return `Err` if the underlying SQLite read call fails.
#[inline]
/// Consumes the statement.
///
/// Functionally equivalent to the `Drop` implementation, but allows
/// callers to see any errors that occur.
///
/// # Failure
///
/// Will return `Err` if the underlying SQLite call fails.
#[inline]
/// Attempts to back up the given number of pages. If `num_pages` is
/// negative, will attempt to back up all remaining pages. This will hold a
/// lock on the source database for the duration, so it is probably not
/// what you want for databases that are currently active (see
/// [`run_to_completion`](Backup::run_to_completion) for a better
/// alternative).
///
/// # Failure
///
/// Will return `Err` if the underlying `sqlite3_backup_step` call returns
/// an error code other than `DONE`, `OK`, `BUSY`, or `LOCKED`. `BUSY` and
/// `LOCKED` are transient errors and are therefore returned as possible
/// `Ok` values.
#[inline]
/// Convenience method to prepare and execute a single SQL statement.
///
/// On success, returns the number of rows that were changed or inserted or
/// deleted (via `sqlite3_changes`).
///
/// ## Example
///
/// ### With positional params
///
/// ```rust,no_run
/// # use rusqlite::{Connection};
/// fn update_rows(conn: &Connection) {
/// match conn.execute("UPDATE foo SET bar = 'baz' WHERE qux = ?1", [1i32]) {
/// Ok(updated) => println!("{} rows were updated", updated),
/// Err(err) => println!("update failed: {}", err),
/// }
/// }
/// ```
///
/// ### With positional params of varying types
///
/// ```rust,no_run
/// # use rusqlite::{params, Connection};
/// fn update_rows(conn: &Connection) {
/// match conn.execute(
/// "UPDATE foo SET bar = 'baz' WHERE qux = ?1 AND quux = ?2",
/// params![1i32, 1.5f64],
/// ) {
/// Ok(updated) => println!("{} rows were updated", updated),
/// Err(err) => println!("update failed: {}", err),
/// }
/// }
/// ```
///
/// ### With named params
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// fn insert(conn: &Connection) -> Result<usize> {
/// conn.execute(
/// "INSERT INTO test (name) VALUES (:name)",
/// &[(":name", "one")],
/// )
/// }
/// ```
///
/// # Failure
///
/// Will return `Err` if `sql` cannot be converted to a C-compatible string
/// or if the underlying SQLite call fails.
#[inline]
/// Open a new connection to an in-memory SQLite database.
///
/// # Failure
///
/// Will return `Err` if the underlying SQLite open call fails.
#[inline]
/// Prepares a key for decryption.
///
/// # Failure
///
/// Returns an error if the key is not 128, 192, or 256 bits.
#[corresponds(AES_set_decrypt_key)]
/// Prepare a SQL statement for execution.
///
/// ## Example
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// fn insert_new_people(conn: &Connection) -> Result<()> {
/// let mut stmt = conn.prepare("INSERT INTO People (name) VALUES (?1)")?;
/// stmt.execute(["Joe Smith"])?;
/// stmt.execute(["Bob Jones"])?;
/// Ok(())
/// }
/// ```
///
/// # Failure
///
/// Will return `Err` if `sql` cannot be converted to a C-compatible string
/// or if the underlying SQLite call fails.
#[inline]
/// Constructs a `SockAddr` with the family `AF_UNIX` and the provided path.
///
/// # Failure
///
/// Returns an error if the path is longer than `SUN_LEN`.
#[cfg(feature = "all")]
/// Restore the given source path into the
/// `name` database. If `progress` is not `None`, it will be
/// called periodically until the restore completes.
///
/// For more fine-grained control over the restore process (e.g.,
/// to sleep periodically during the restore or to restore from an
/// already-open database connection), see the `backup` module.
///
/// # Failure
///
/// Will return `Err` if the destination path cannot be opened
/// or if the restore fails.
pub fn restore<P: AsRef<Path>, F: Fn(Progress)>(
/// Move a BLOB handle to a new row.
///
/// # Failure
///
/// Will return `Err` if the underlying SQLite BLOB reopen call fails.
#[inline]
/// Convenience method to run multiple SQL statements (that cannot take any
/// parameters).
///
/// ## Example
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// fn create_tables(conn: &Connection) -> Result<()> {
/// conn.execute_batch(
/// "BEGIN;
/// CREATE TABLE foo(x INTEGER);
/// CREATE TABLE bar(y TEXT);
/// COMMIT;",
/// )
/// }
/// ```
///
/// # Failure
///
/// Will return `Err` if `sql` cannot be converted to a C-compatible string
/// or if the underlying SQLite call fails.
pub fn execute_batch(&self, sql: &str) -> Result<()> {
/// Open a handle to the BLOB located in `row_id`,
/// `column`, `table` in database `db`.
///
/// # Failure
///
/// Will return `Err` if `db`/`table`/`column` cannot be converted to a
/// C-compatible string or if the underlying SQLite BLOB open call
/// fails.
#[inline]
/// Returns the column index in the result set for a given column name.
///
/// If there is no AS clause then the name of the column is unspecified and
/// may change from one release of SQLite to the next.
///
/// If associated DB schema can be altered concurrently, you should make
/// sure that current statement has already been stepped once before
/// calling this method.
///
/// # Failure
///
/// Will return an `Error::InvalidColumnName` when there is no column with
/// the specified `name`.
#[inline]
/// Back up the `name` database to the given
/// destination path.
///
/// If `progress` is not `None`, it will be called periodically
/// until the backup completes.
///
/// For more fine-grained control over the backup process (e.g.,
/// to sleep periodically during the backup or to back up to an
/// already-open database connection), see the `backup` module.
///
/// # Failure
///
/// Will return `Err` if the destination path cannot be opened
/// or if the backup fails.
pub fn backup<P: AsRef<Path>>(
/// Executes the prepared statement and maps a function over the resulting
/// rows, where the function returns a `Result` with `Error` type
/// implementing `std::convert::From<Error>` (so errors can be unified).
///
/// This is equivalent to `stmt.query(params)?.and_then(f)`.
///
/// ## Example
///
/// ### Use with named params
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// struct Person {
/// name: String,
/// };
///
/// fn name_to_person(name: String) -> Result<Person> {
/// // ... check for valid name
/// Ok(Person { name })
/// }
///
/// fn get_names(conn: &Connection) -> Result<Vec<Person>> {
/// let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
/// let rows = stmt.query_and_then(&[(":id", "one")], |row| name_to_person(row.get(0)?))?;
///
/// let mut persons = Vec::new();
/// for person_result in rows {
/// persons.push(person_result?);
/// }
///
/// Ok(persons)
/// }
/// ```
///
/// ### Use with positional params
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// fn get_names(conn: &Connection) -> Result<Vec<String>> {
/// let mut stmt = conn.prepare("SELECT name FROM people WHERE id = ?1")?;
/// let rows = stmt.query_and_then(["one"], |row| row.get::<_, String>(0))?;
///
/// let mut persons = Vec::new();
/// for person_result in rows {
/// persons.push(person_result?);
/// }
///
/// Ok(persons)
/// }
/// ```
///
/// # Failure
///
/// Will return `Err` if binding parameters fails.
#[inline]
/// Convenience method to execute a query that is expected to return a
/// single row.
///
/// ## Example
///
/// ```rust,no_run
/// # use rusqlite::{Result, Connection};
/// fn preferred_locale(conn: &Connection) -> Result<String> {
/// conn.query_row(
/// "SELECT value FROM preferences WHERE name='locale'",
/// [],
/// |row| row.get(0),
/// )
/// }
/// ```
///
/// If the query returns more than one row, all rows except the first are
/// ignored.
///
/// Returns `Err(QueryReturnedNoRows)` if no results are returned. If the
/// query truly is optional, you can call `.optional()` on the result of
/// this to get a `Result<Option<T>>`.
///
/// # Failure
///
/// Will return `Err` if `sql` cannot be converted to a C-compatible string
/// or if the underlying SQLite call fails.
#[inline]
/// Prepares a key for encryption.
///
/// # Failure
///
/// Returns an error if the key is not 128, 192, or 256 bits.
#[corresponds(AES_set_encrypt_key)]
/// Open a new connection to an in-memory SQLite database using the specific
/// flags and vfs name.
///
/// [Database Connection](http://www.sqlite.org/c3ref/open.html) for a description of valid
/// flag combinations.
///
/// # Failure
///
/// Will return `Err` if `vfs` cannot be converted to a C-compatible
/// string or if the underlying SQLite open call fails.
#[inline]
/// Execute the prepared statement.
///
/// On success, returns the number of rows that were changed or inserted or
/// deleted (via `sqlite3_changes`).
///
/// ## Example
///
/// ### Use with positional parameters
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result, params};
/// fn update_rows(conn: &Connection) -> Result<()> {
/// let mut stmt = conn.prepare("UPDATE foo SET bar = ?1 WHERE qux = ?2")?;
/// // For a single parameter, or a parameter where all the values have
/// // the same type, just passing an array is simplest.
/// stmt.execute([2i32])?;
/// // The `rusqlite::params!` macro is mostly useful when the parameters do not
/// // all have the same type, or if there are more than 32 parameters
/// // at once, but it can be used in other cases.
/// stmt.execute(params![1i32])?;
/// // However, it's not required, many cases are fine as:
/// stmt.execute(&[&2i32])?;
/// // Or even:
/// stmt.execute([2i32])?;
/// // If you really want to, this is an option as well.
/// stmt.execute((2i32,))?;
/// Ok(())
/// }
/// ```
///
/// #### Heterogeneous positional parameters
///
/// ```
/// use rusqlite::{Connection, Result};
/// fn store_file(conn: &Connection, path: &str, data: &[u8]) -> Result<()> {
/// # // no need to do it for real.
/// # fn sha256(_: &[u8]) -> [u8; 32] { [0; 32] }
/// let query = "INSERT OR REPLACE INTO files(path, hash, data) VALUES (?1, ?2, ?3)";
/// let mut stmt = conn.prepare_cached(query)?;
/// let hash: [u8; 32] = sha256(data);
/// // The easiest way to pass positional parameters of have several
/// // different types is by using a tuple.
/// stmt.execute((path, hash, data))?;
/// // Using the `params!` macro also works, and supports longer parameter lists:
/// stmt.execute(rusqlite::params![path, hash, data])?;
/// Ok(())
/// }
/// # let c = Connection::open_in_memory().unwrap();
/// # c.execute_batch("CREATE TABLE files(path TEXT PRIMARY KEY, hash BLOB, data BLOB)").unwrap();
/// # store_file(&c, "foo/bar.txt", b"bibble").unwrap();
/// # store_file(&c, "foo/baz.txt", b"bobble").unwrap();
/// ```
///
/// ### Use with named parameters
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result, named_params};
/// fn insert(conn: &Connection) -> Result<()> {
/// let mut stmt = conn.prepare("INSERT INTO test (key, value) VALUES (:key, :value)")?;
/// // The `rusqlite::named_params!` macro (like `params!`) is useful for heterogeneous
/// // sets of parameters (where all parameters are not the same type), or for queries
/// // with many (more than 32) statically known parameters.
/// stmt.execute(named_params! { ":key": "one", ":val": 2 })?;
/// // However, named parameters can also be passed like:
/// stmt.execute(&[(":key", "three"), (":val", "four")])?;
/// // Or even: (note that a &T is required for the value type, currently)
/// stmt.execute(&[(":key", &100), (":val", &200)])?;
/// Ok(())
/// }
/// ```
///
/// ### Use without parameters
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result, params};
/// fn delete_all(conn: &Connection) -> Result<()> {
/// let mut stmt = conn.prepare("DELETE FROM users")?;
/// stmt.execute([])?;
/// Ok(())
/// }
/// ```
///
/// # Failure
///
/// Will return `Err` if binding parameters fails, the executed statement
/// returns rows (in which case `query` should be used instead), or the
/// underlying SQLite call fails.
#[inline]
/// Prepare a SQL statement for execution.
///
/// # Failure
///
/// Will return `Err` if `sql` cannot be converted to a C-compatible string
/// or if the underlying SQLite call fails.
#[inline]
/// Open a new connection to a SQLite database.
///
/// [Database Connection](http://www.sqlite.org/c3ref/open.html) for a description of valid
/// flag combinations.
///
/// # Failure
///
/// Will return `Err` if `path` cannot be converted to a C-compatible
/// string or if the underlying SQLite open call fails.
#[inline]
/// Prepares a key for encryption.
///
/// # Failure
///
/// Returns an error if the key is not 128, 192, or 256 bits.
#[corresponds(AES_set_encrypt_key)]
/// Close a BLOB handle.
///
/// Calling `close` explicitly is not required (the BLOB will be closed
/// when the `Blob` is dropped), but it is available so you can get any
/// errors that occur.
///
/// # Failure
///
/// Will return `Err` if the underlying SQLite close call fails.
#[inline]
/// Begin a new transaction with the default behavior (DEFERRED).
///
/// Attempt to open a nested transaction will result in a SQLite error.
/// `Connection::transaction` prevents this at compile time by taking `&mut
/// self`, but `Connection::unchecked_transaction()` may be used to defer
/// the checking until runtime.
///
/// See [`Connection::transaction`] and [`Transaction::new_unchecked`]
/// (which can be used if the default transaction behavior is undesirable).
///
/// ## Example
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// # use std::rc::Rc;
/// # fn do_queries_part_1(_conn: &Connection) -> Result<()> { Ok(()) }
/// # fn do_queries_part_2(_conn: &Connection) -> Result<()> { Ok(()) }
/// fn perform_queries(conn: Rc<Connection>) -> Result<()> {
/// let tx = conn.unchecked_transaction()?;
///
/// do_queries_part_1(&tx)?; // tx causes rollback if this fails
/// do_queries_part_2(&tx)?; // tx causes rollback if this fails
///
/// tx.commit()
/// }
/// ```
///
/// # Failure
///
/// Will return `Err` if the underlying SQLite call fails. The specific
/// error returned if transactions are nested is currently unspecified.
pub fn unchecked_transaction(&self) -> Result<Transaction<'_>> {
/// Begin a new savepoint with a specified name.
///
/// See [`savepoint`](Connection::savepoint).
///
/// # Failure
///
/// Will return `Err` if the underlying SQLite call fails.
#[inline]
/// Returns the `idx`th argument as a `ValueRef`.
///
/// # Failure
///
/// Will panic if `idx` is greater than or equal to
/// [`self.len()`](Context::len).
#[inline]
/// Prepares a key for decryption.
///
/// # Failure
///
/// Returns an error if the key is not 128, 192, or 256 bits.
#[allow(deprecated)] // https://github.com/rust-lang/rust/issues/63566
/// Create a new version 7 UUID using a time value and random bytes.
///
/// When the `std` feature is enabled, you can also use [`Uuid::now_v7`].
///
/// Note that usage of this method requires the `v7` feature of this crate
/// to be enabled.
///
/// Also see [`Uuid::now_v7`] for a convenient way to generate version 7
/// UUIDs using the current system time.
///
/// # Examples
///
/// A v7 UUID can be created from a unix [`Timestamp`] plus a 128 bit
/// random number. When supplied as such, the data will be
///
/// ```rust
/// # use uuid::{Uuid, Timestamp, NoContext};
/// let ts = Timestamp::from_unix(NoContext, 1497624119, 1234);
///
/// let uuid = Uuid::new_v7(ts);
///
/// assert!(
/// uuid.hyphenated().to_string().starts_with("015cb15a-86d8-7")
/// );
/// ```
///
/// # References
///
/// * [Version 7 UUIDs in Draft RFC: New UUID Formats, Version 4](https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-04#section-5.2)
pub fn new_v7(ts: Timestamp) -> Self {
/// Asynchronously reads from a file descriptor into a buffer
///
/// # References
///
/// [aio_read](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_read.html)
pub fn read(self: &mut Pin<Box<Self>>) -> Result<()> {
/// Cancels an outstanding AIO request.
///
/// The operating system is not required to implement cancellation for all
/// file and device types. Even if it does, there is no guarantee that the
/// operation has not already completed. So the caller must check the
/// result and handle operations that were not canceled or that have already
/// completed.
///
/// # Examples
///
/// Cancel an outstanding aio operation. Note that we must still call
/// `aio_return` to free resources, even though we don't care about the
/// result.
///
/// ```
/// # use nix::errno::Errno;
/// # use nix::Error;
/// # use nix::sys::aio::*;
/// # use nix::sys::signal::SigevNotify;
/// # use std::{thread, time};
/// # use std::io::Write;
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// let wbuf = b"CDEF";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
/// 2, //offset
/// &wbuf[..],
/// 0, //priority
/// SigevNotify::SigevNone,
/// LioOpcode::LIO_NOP);
/// aiocb.write().unwrap();
/// let cs = aiocb.cancel().unwrap();
/// if cs == AioCancelStat::AioNotCanceled {
/// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// }
/// // Must call `aio_return`, but ignore the result
/// let _ = aiocb.aio_return();
/// # }
/// ```
///
/// # References
///
/// [aio_cancel](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_cancel.html)
pub fn cancel(self: &mut Pin<Box<Self>>) -> Result<AioCancelStat> {
/// Creates a random UUID.
///
/// This uses the [`getrandom`] crate to utilise the operating system's RNG
/// as the source of random numbers. If you'd like to use a custom
/// generator, don't use this method: generate random bytes using your
/// custom generator and pass them to the
/// [`uuid::Builder::from_random_bytes`][from_random_bytes] function
/// instead.
///
/// Note that usage of this method requires the `v4` feature of this crate
/// to be enabled.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use uuid::{Uuid, Version};
/// let uuid = Uuid::new_v4();
///
/// assert_eq!(Some(Version::Random), uuid.get_version());
/// ```
///
/// # References
///
/// * [Version 4 UUIDs in RFC4122](https://www.rfc-editor.org/rfc/rfc4122#section-4.4)
///
/// [`getrandom`]: https://crates.io/crates/getrandom
/// [from_random_bytes]: struct.Builder.html#method.from_random_bytes
pub fn new_v4() -> Uuid {
/// An asynchronous version of `fsync(2)`.
///
/// # References
///
/// [aio_fsync](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_fsync.html)
pub fn fsync(self: &mut Pin<Box<Self>>, mode: AioFsyncMode) -> Result<()> {
/// Creates a UUID using a name from a namespace, based on the SHA-1 hash.
///
/// A number of namespaces are available as constants in this crate:
///
/// * [`NAMESPACE_DNS`]
/// * [`NAMESPACE_OID`]
/// * [`NAMESPACE_URL`]
/// * [`NAMESPACE_X500`]
///
/// Note that usage of this method requires the `v5` feature of this crate
/// to be enabled.
///
/// # Examples
///
/// Generating a SHA1 DNS UUID for `rust-lang.org`:
///
/// ```
/// # use uuid::{Uuid, Version};
/// let uuid = Uuid::new_v5(&Uuid::NAMESPACE_DNS, b"rust-lang.org");
///
/// assert_eq!(Some(Version::Sha1), uuid.get_version());
/// ```
///
/// # References
///
/// * [Version 3 and 5 UUIDs in RFC4122](https://www.rfc-editor.org/rfc/rfc4122#section-4.3)
///
/// [`NAMESPACE_DNS`]: struct.Uuid.html#associatedconst.NAMESPACE_DNS
/// [`NAMESPACE_OID`]: struct.Uuid.html#associatedconst.NAMESPACE_OID
/// [`NAMESPACE_URL`]: struct.Uuid.html#associatedconst.NAMESPACE_URL
/// [`NAMESPACE_X500`]: struct.Uuid.html#associatedconst.NAMESPACE_X500
pub fn new_v5(namespace: &Uuid, name: &[u8]) -> Uuid {
/// Asynchronously reads from a file descriptor into a buffer
///
/// # References
///
/// [aio_read](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_read.html)
pub fn read(self: &mut Pin<Box<Self>>) -> Result<()> {
/// Apple system control socket
///
/// # References
///
/// https://developer.apple.com/documentation/kernel/sockaddr_ctl
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
/// Retrieve return status of an asynchronous operation.
///
/// Should only be called once for each `AioCb`, after `AioCb::error`
/// indicates that it has completed. The result is the same as for the
/// synchronous `read(2)`, `write(2)`, of `fsync(2)` functions.
///
/// # References
///
/// [aio_return](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_return.html)
// Note: this should be just `return`, but that's a reserved word
/// Address for the Linux kernel user interface device.
///
/// # References
///
/// [netlink(7)](https://man7.org/linux/man-pages/man7/netlink.7.html)
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
/// Retrieve error status of an asynchronous operation.
///
/// If the request has not yet completed, returns `EINPROGRESS`. Otherwise,
/// returns `Ok` or any other error.
///
/// # Examples
///
/// Issue an aio operation and use `error` to poll for completion. Polling
/// is an alternative to `aio_suspend`, used by most of the other examples.
///
/// ```
/// # use nix::errno::Errno;
/// # use nix::Error;
/// # use nix::sys::aio::*;
/// # use nix::sys::signal::SigevNotify;
/// # use std::{thread, time};
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = Box::pin(AioWrite::new(f.as_raw_fd(),
/// 2, //offset
/// WBUF,
/// 0, //priority
/// SigevNotify::SigevNone));
/// aiocb.as_mut().submit().unwrap();
/// while (aiocb.as_mut().error() == Err(Errno::EINPROGRESS)) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// assert_eq!(aiocb.as_mut().aio_return().unwrap(), WBUF.len());
/// ```
///
/// # References
///
/// [aio_error](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_error.html)
fn error(self: Pin<&mut Self>) -> Result<()>;
/// Resubmits any incomplete operations with [`lio_listio`].
///
/// Sometimes, due to system resource limitations, an `lio_listio` call will
/// return `EIO`, or `EAGAIN`. Or, if a signal is received, it may return
/// `EINTR`. In any of these cases, only a subset of its constituent
/// operations will actually have been initiated. `listio_resubmit` will
/// resubmit any operations that are still uninitiated.
///
/// After calling `listio_resubmit`, results should be collected by
/// [`LioCb::aio_return`].
///
/// # Examples
/// ```no_run
/// # use nix::Error;
/// # use nix::errno::Errno;
/// # use nix::sys::aio::*;
/// # use nix::sys::signal::SigevNotify;
/// # use std::os::unix::io::AsRawFd;
/// # use std::{thread, time};
/// # use tempfile::tempfile;
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut liocb = LioCbBuilder::with_capacity(1)
/// .emplace_slice(
/// f.as_raw_fd(),
/// 2, //offset
/// WBUF,
/// 0, //priority
/// SigevNotify::SigevNone,
/// LioOpcode::LIO_WRITE
/// ).finish();
/// let mut err = liocb.listio(LioMode::LIO_WAIT, SigevNotify::SigevNone);
/// while err == Err(Errno::EIO) ||
/// err == Err(Errno::EAGAIN) {
/// thread::sleep(time::Duration::from_millis(10));
/// err = liocb.listio_resubmit(LioMode::LIO_WAIT, SigevNotify::SigevNone);
/// }
/// assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len());
/// ```
///
/// # References
///
/// [`lio_listio`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html)
///
/// [`lio_listio`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html
/// [`LioCb::aio_return`]: struct.LioCb.html#method.aio_return
// Note: the addresses of any EINPROGRESS or EOK aiocbs _must_ not be
/// Apple system control socket
///
/// # References
///
/// <https://developer.apple.com/documentation/kernel/sockaddr_ctl>
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
/// Address for the Linux kernel user interface device.
///
/// # References
///
/// [netlink(7)](https://man7.org/linux/man-pages/man7/netlink.7.html)
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
/// Retrieve return status of an asynchronous operation.
///
/// Should only be called once for each `AioCb`, after `AioCb::error`
/// indicates that it has completed. The result is the same as for the
/// synchronous `read(2)`, `write(2)`, of `fsync(2)` functions.
///
/// # References
///
/// [aio_return](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_return.html)
// Note: this should be just `return`, but that's a reserved word
/// Retrieve error status of an asynchronous operation.
///
/// If the request has not yet completed, returns `EINPROGRESS`. Otherwise,
/// returns `Ok` or any other error.
///
/// # Examples
///
/// Issue an aio operation and use `error` to poll for completion. Polling
/// is an alternative to `aio_suspend`, used by most of the other examples.
///
/// ```
/// # use nix::errno::Errno;
/// # use nix::Error;
/// # use nix::sys::aio::*;
/// # use nix::sys::signal::SigevNotify;
/// # use std::{thread, time};
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = Box::pin(AioWrite::new(f.as_raw_fd(),
/// 2, //offset
/// WBUF,
/// 0, //priority
/// SigevNotify::SigevNone));
/// aiocb.as_mut().submit().unwrap();
/// while (aiocb.as_mut().error() == Err(Errno::EINPROGRESS)) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// assert_eq!(aiocb.as_mut().aio_return().unwrap(), WBUF.len());
/// ```
///
/// # References
///
/// [aio_error](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_error.html)
fn error(self: Pin<&mut Self>) -> Result<()>;
/// Retrieve error status of an asynchronous operation.
///
/// If the request has not yet completed, returns `EINPROGRESS`. Otherwise,
/// returns `Ok` or any other error.
///
/// # Examples
///
/// Issue an aio operation and use `error` to poll for completion. Polling
/// is an alternative to `aio_suspend`, used by most of the other examples.
///
/// ```
/// # use nix::errno::Errno;
/// # use nix::Error;
/// # use nix::sys::aio::*;
/// # use nix::sys::signal::SigevNotify;
/// # use std::{thread, time};
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// # fn main() {
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = AioCb::from_slice( f.as_raw_fd(),
/// 2, //offset
/// WBUF,
/// 0, //priority
/// SigevNotify::SigevNone,
/// LioOpcode::LIO_NOP);
/// aiocb.write().unwrap();
/// while (aiocb.error() == Err(Error::from(Errno::EINPROGRESS))) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// assert_eq!(aiocb.aio_return().unwrap() as usize, WBUF.len());
/// # }
/// ```
///
/// # References
///
/// [aio_error](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_error.html)
pub fn error(self: &mut Pin<Box<Self>>) -> Result<()> {
/// An asynchronous version of `fsync(2)`.
///
/// # References
///
/// [aio_fsync](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_fsync.html)
pub fn fsync(self: &mut Pin<Box<Self>>, mode: AioFsyncMode) -> Result<()> {
/// Socket address for VMWare VSockets protocol
///
/// # References
///
/// [vsock(7)](https://man7.org/linux/man-pages/man7/vsock.7.html)
#[derive(Copy, Clone)]
/// Asynchronously writes from a buffer to a file descriptor
///
/// # References
///
/// [aio_write](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_write.html)
pub fn write(self: &mut Pin<Box<Self>>) -> Result<()> {
/// Resubmits any incomplete operations with [`lio_listio`].
///
/// Sometimes, due to system resource limitations, an `lio_listio` call will
/// return `EIO`, or `EAGAIN`. Or, if a signal is received, it may return
/// `EINTR`. In any of these cases, only a subset of its constituent
/// operations will actually have been initiated. `listio_resubmit` will
/// resubmit any operations that are still uninitiated.
///
/// After calling `listio_resubmit`, results should be collected by
/// [`LioCb::aio_return`].
///
/// # Examples
/// ```no_run
/// # use nix::Error;
/// # use nix::errno::Errno;
/// # use nix::sys::aio::*;
/// # use nix::sys::signal::SigevNotify;
/// # use std::os::unix::io::AsRawFd;
/// # use std::{thread, time};
/// # use tempfile::tempfile;
/// # fn main() {
/// const WBUF: &[u8] = b"abcdef123456";
/// let mut f = tempfile().unwrap();
/// let mut liocb = LioCbBuilder::with_capacity(1)
/// .emplace_slice(
/// f.as_raw_fd(),
/// 2, //offset
/// WBUF,
/// 0, //priority
/// SigevNotify::SigevNone,
/// LioOpcode::LIO_WRITE
/// ).finish();
/// let mut err = liocb.listio(LioMode::LIO_WAIT, SigevNotify::SigevNone);
/// while err == Err(Error::from(Errno::EIO)) ||
/// err == Err(Error::from(Errno::EAGAIN)) {
/// thread::sleep(time::Duration::from_millis(10));
/// err = liocb.listio_resubmit(LioMode::LIO_WAIT, SigevNotify::SigevNone);
/// }
/// assert_eq!(liocb.aio_return(0).unwrap() as usize, WBUF.len());
/// # }
/// ```
///
/// # References
///
/// [`lio_listio`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html)
///
/// [`lio_listio`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html
/// [`LioCb::aio_return`]: struct.LioCb.html#method.aio_return
// Note: the addresses of any EINPROGRESS or EOK aiocbs _must_ not be
/// Address for the Linux kernel user interface device.
///
/// # References
///
/// [netlink(7)](https://man7.org/linux/man-pages/man7/netlink.7.html)
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
/// Returns the variant of the UUID structure.
///
/// This determines the interpretation of the structure of the UUID.
/// This method simply reads the value of the variant byte. It doesn't
/// validate the rest of the UUID as conforming to that variant.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use uuid::{Uuid, Variant};
/// # fn main() -> Result<(), uuid::Error> {
/// let my_uuid = Uuid::parse_str("02f09a3f-1624-3b1d-8409-44eff7708208")?;
///
/// assert_eq!(Variant::RFC4122, my_uuid.get_variant());
/// # Ok(())
/// # }
/// ```
///
/// # References
///
/// * [Variant in RFC4122](http://tools.ietf.org/html/rfc4122#section-4.1.1)
pub const fn get_variant(&self) -> Variant {
/// Create a new version 6 UUID using the given timestamp and a node ID.
///
/// This is similar to version 1 UUIDs, except that it is lexicographically sortable by timestamp.
///
/// Also see [`Uuid::now_v6`] for a convenient way to generate version 6
/// UUIDs using the current system time.
///
/// When generating [`Timestamp`]s using a [`ClockSequence`], this function
/// is only guaranteed to produce unique values if the following conditions
/// hold:
///
/// 1. The *node ID* is unique for this process,
/// 2. The *context* is shared across all threads which are generating version 6
/// UUIDs,
/// 3. The [`ClockSequence`] implementation reliably returns unique
/// clock sequences (this crate provides [`Context`] for this
/// purpose. However you can create your own [`ClockSequence`]
/// implementation, if [`Context`] does not meet your needs).
///
/// The NodeID must be exactly 6 bytes long.
///
/// Note that usage of this method requires the `v6` feature of this crate
/// to be enabled.
///
/// # Examples
///
/// A UUID can be created from a unix [`Timestamp`] with a
/// [`ClockSequence`]. RFC4122 requires the clock sequence
/// is seeded with a random value:
///
/// ```rust
/// # use uuid::{Uuid, Timestamp, Context};
/// # fn random_seed() -> u16 { 42 }
/// let context = Context::new(random_seed());
/// let ts = Timestamp::from_unix(context, 1497624119, 1234);
///
/// let uuid = Uuid::new_v6(ts, &[1, 2, 3, 4, 5, 6]);
///
/// assert_eq!(
/// uuid.hyphenated().to_string(),
/// "1e752a1f-3b49-658c-802a-010203040506"
/// );
/// ```
///
/// The timestamp can also be created manually as per RFC4122:
///
/// ```
/// # use uuid::{Uuid, Timestamp, Context, ClockSequence};
/// # fn random_seed() -> u16 { 42 }
/// let context = Context::new(random_seed());
/// let ts = Timestamp::from_rfc4122(14976241191231231313, context.generate_sequence(0, 0) );
///
/// let uuid = Uuid::new_v6(ts, &[1, 2, 3, 4, 5, 6]);
///
/// assert_eq!(
/// uuid.hyphenated().to_string(),
/// "fd64c041-1e91-6551-802a-010203040506"
/// );
/// ```
///
/// # References
///
/// * [Version 6 UUIDs in Draft RFC: New UUID Formats, Version 4](https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-04#section-5.1)
///
/// [`Timestamp`]: timestamp/struct.Timestamp.html
/// [`ClockSequence`]: timestamp/trait.ClockSequence.html
/// [`Context`]: timestamp/context/struct.Context.html
pub fn new_v6(ts: Timestamp, node_id: &[u8; 6]) -> Self {
/// Retrieve return status of an asynchronous operation.
///
/// Should only be called once for each operation, after [`Aio::error`]
/// indicates that it has completed. The result is the same as for the
/// synchronous `read(2)`, `write(2)`, of `fsync(2)` functions.
///
/// # References
///
/// [aio_return](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_return.html)
fn aio_return(self: Pin<&mut Self>) -> Result<Self::Output>;
/// Socket address for VMWare VSockets protocol
///
/// # References
///
/// [vsock(7)](https://man7.org/linux/man-pages/man7/vsock.7.html)
#[derive(Copy, Clone)]
/// Cancels an outstanding AIO request.
///
/// The operating system is not required to implement cancellation for all
/// file and device types. Even if it does, there is no guarantee that the
/// operation has not already completed. So the caller must check the
/// result and handle operations that were not canceled or that have already
/// completed.
///
/// # Examples
///
/// Cancel an outstanding aio operation. Note that we must still call
/// `aio_return` to free resources, even though we don't care about the
/// result.
///
/// ```
/// # use nix::errno::Errno;
/// # use nix::Error;
/// # use nix::sys::aio::*;
/// # use nix::sys::signal::SigevNotify;
/// # use std::{thread, time};
/// # use std::io::Write;
/// # use std::os::unix::io::AsRawFd;
/// # use tempfile::tempfile;
/// let wbuf = b"CDEF";
/// let mut f = tempfile().unwrap();
/// let mut aiocb = Box::pin(AioWrite::new(f.as_raw_fd(),
/// 2, //offset
/// &wbuf[..],
/// 0, //priority
/// SigevNotify::SigevNone));
/// aiocb.as_mut().submit().unwrap();
/// let cs = aiocb.as_mut().cancel().unwrap();
/// if cs == AioCancelStat::AioNotCanceled {
/// while (aiocb.as_mut().error() == Err(Errno::EINPROGRESS)) {
/// thread::sleep(time::Duration::from_millis(10));
/// }
/// }
/// // Must call `aio_return`, but ignore the result
/// let _ = aiocb.as_mut().aio_return();
/// ```
///
/// # References
///
/// [aio_cancel](https://pubs.opengroup.org/onlinepubs/9699919799/functions/aio_cancel.html)
fn cancel(self: Pin<&mut Self>) -> Result<AioCancelStat>;
/// Returns the version of the UUID.
///
/// This represents the algorithm used to generate the value.
/// If the version field doesn't contain a recognized version then `None`
/// is returned. If you're trying to read the version for a future extension
/// you can also use [`Uuid::get_version_num`] to unconditionally return a
/// number. Future extensions may start to return `Some` once they're
/// standardized and supported.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use uuid::{Uuid, Version};
/// # fn main() -> Result<(), uuid::Error> {
/// let my_uuid = Uuid::parse_str("02f09a3f-1624-3b1d-8409-44eff7708208")?;
///
/// assert_eq!(Some(Version::Md5), my_uuid.get_version());
/// # Ok(())
/// # }
/// ```
///
/// # References
///
/// * [Version in RFC4122](https://datatracker.ietf.org/doc/html/rfc4122#section-4.1.3)
pub const fn get_version(&self) -> Option<Version> {
/// Send a JSON body.
///
/// # Optional
///
/// This requires the optional `json` feature enabled.
///
/// # Errors
///
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, or if `T` contains a map with non-string keys.
#[cfg(feature = "json")]
/// Enable auto deflate decompression by checking the `Content-Encoding` response header.
///
/// If auto deflate decompresson is turned on:
///
/// - When sending a request and if the request's headers do not already contain
/// an `Accept-Encoding` **and** `Range` values, the `Accept-Encoding` header is set to `deflate`.
/// The request body is **not** automatically compressed.
/// - When receiving a response, if it's headers contain a `Content-Encoding` value that
/// equals to `deflate`, both values `Content-Encoding` and `Content-Length` are removed from the
/// headers' set. The response body is automatically decompressed.
///
/// If the `deflate` feature is turned on, the default option is enabled.
///
/// # Optional
///
/// This requires the optional `deflate` feature to be enabled
#[cfg(feature = "deflate")]
/// Set the maximum allowed TLS version for connections.
///
/// By default there's no maximum.
///
/// # Errors
///
/// A value of `tls::Version::TLS_1_3` will cause an error with the
/// `native-tls`/`default-tls` backend. This does not mean the version
/// isn't supported, just that it can't be set as a maximum due to
/// technical limitations.
///
/// # Optional
///
/// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
/// feature to be enabled.
#[cfg(feature = "__tls")]
/// Enable auto brotli decompression by checking the `Content-Encoding` response header.
///
/// If auto brotli decompression is turned on:
///
/// - When sending a request and if the request's headers do not already contain
/// an `Accept-Encoding` **and** `Range` values, the `Accept-Encoding` header is set to `br`.
/// The request body is **not** automatically compressed.
/// - When receiving a response, if its headers contain a `Content-Encoding` value of
/// `br`, both `Content-Encoding` and `Content-Length` are removed from the
/// headers' set. The response body is automatically decompressed.
///
/// If the `brotli` feature is turned on, the default option is enabled.
///
/// # Optional
///
/// This requires the optional `brotli` feature to be enabled
#[cfg(feature = "brotli")]
/// Enable a persistent cookie store for the client.
///
/// Cookies received in responses will be preserved and included in
/// additional requests.
///
/// By default, no cookie store is used. Enabling the cookie store
/// with `cookie_store(true)` will set the store to a default implementation.
/// It is **not** necessary to call [cookie_store(true)](crate::ClientBuilder::cookie_store) if [cookie_provider(my_cookie_store)](crate::ClientBuilder::cookie_provider)
/// is used; calling [cookie_store(true)](crate::ClientBuilder::cookie_store) _after_ [cookie_provider(my_cookie_store)](crate::ClientBuilder::cookie_provider) will result
/// in the provided `my_cookie_store` being **overridden** with a default implementation.
///
/// # Optional
///
/// This requires the optional `cookies` feature to be enabled.
#[cfg(feature = "cookies")]
/// Try to deserialize the response body as JSON.
///
/// # Optional
///
/// This requires the optional `json` feature enabled.
///
/// # Examples
///
/// ```
/// # extern crate reqwest;
/// # extern crate serde;
/// #
/// # use reqwest::Error;
/// # use serde::Deserialize;
/// #
/// // This `derive` requires the `serde` dependency.
/// #[derive(Deserialize)]
/// struct Ip {
/// origin: String,
/// }
///
/// # async fn run() -> Result<(), Error> {
/// let ip = reqwest::get("http://httpbin.org/ip")
/// .await?
/// .json::<Ip>()
/// .await?;
///
/// println!("ip: {}", ip.origin);
/// # Ok(())
/// # }
/// #
/// # fn main() { }
/// ```
///
/// # Errors
///
/// This method fails whenever the response body is not in JSON format
/// or it cannot be properly deserialized to target type `T`. For more
/// details please see [`serde_json::from_reader`].
///
/// [`serde_json::from_reader`]: https://docs.serde.rs/serde_json/fn.from_reader.html
#[cfg(feature = "json")]
/// Enable auto gzip decompression by checking the `Content-Encoding` response header.
///
/// If auto gzip decompression is turned on:
///
/// - When sending a request and if the request's headers do not already contain
/// an `Accept-Encoding` **and** `Range` values, the `Accept-Encoding` header is set to `gzip`.
/// The request body is **not** automatically compressed.
/// - When receiving a response, if its headers contain a `Content-Encoding` value of
/// `gzip`, both `Content-Encoding` and `Content-Length` are removed from the
/// headers' set. The response body is automatically decompressed.
///
/// If the `gzip` feature is turned on, the default option is enabled.
///
/// # Optional
///
/// This requires the optional `gzip` feature to be enabled
#[cfg(feature = "gzip")]
/// Force using the native TLS backend.
///
/// Since multiple TLS backends can be optionally enabled, this option will
/// force the `native-tls` backend to be used for this `Client`.
///
/// # Optional
///
/// This requires the optional `native-tls` feature to be enabled.
#[cfg(feature = "native-tls")]
/// Use a preconfigured TLS backend.
///
/// If the passed `Any` argument is not a TLS backend that reqwest
/// understands, the `ClientBuilder` will error when calling `build`.
///
/// # Advanced
///
/// This is an advanced option, and can be somewhat brittle. Usage requires
/// keeping the preconfigured TLS argument version in sync with reqwest,
/// since version mismatches will result in an "unknown" TLS backend.
///
/// If possible, it's preferable to use the methods on `ClientBuilder`
/// to configure reqwest's TLS.
///
/// # Optional
///
/// This requires one of the optional features `native-tls` or
/// `rustls-tls(-...)` to be enabled.
#[cfg(any(feature = "native-tls", feature = "__rustls",))]
/// Set the minimum required TLS version for connections.
///
/// By default the TLS backend's own default is used.
///
/// # Errors
///
/// A value of `tls::Version::TLS_1_3` will cause an error with the
/// `native-tls`/`default-tls` backend. This does not mean the version
/// isn't supported, just that it can't be set as a minimum due to
/// technical limitations.
///
/// # Optional
///
/// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
/// feature to be enabled.
#[cfg(feature = "__tls")]
/// Controls the use of built-in/preloaded certificates during certificate validation.
///
/// Defaults to `true` -- built-in system certs will be used.
///
/// # Optional
///
/// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
/// feature to be enabled.
#[cfg(feature = "__tls")]
/// Enables the [trust-dns](trust_dns_resolver) async resolver instead of a default threadpool using `getaddrinfo`.
///
/// If the `trust-dns` feature is turned on, the default option is enabled.
///
/// # Optional
///
/// This requires the optional `trust-dns` feature to be enabled
#[cfg(feature = "trust-dns")]
/// Controls the use of hostname verification.
///
/// Defaults to `false`.
///
/// # Warning
///
/// You should think very carefully before you use this method. If
/// hostname verification is not used, any valid certificate for any
/// site will be trusted for use from any other. This introduces a
/// significant vulnerability to man-in-the-middle attacks.
///
/// # Optional
///
/// This requires the optional `native-tls` feature to be enabled.
#[cfg(feature = "native-tls")]
/// Try and deserialize the response body as JSON using `serde`.
///
/// # Optional
///
/// This requires the optional `json` feature enabled.
///
/// # Examples
///
/// ```rust
/// # extern crate reqwest;
/// # extern crate serde;
/// #
/// # use reqwest::Error;
/// # use serde::Deserialize;
/// #
/// // This `derive` requires the `serde` dependency.
/// #[derive(Deserialize)]
/// struct Ip {
/// origin: String,
/// }
///
/// # fn run() -> Result<(), Error> {
/// let json: Ip = reqwest::blocking::get("http://httpbin.org/ip")?.json()?;
/// # Ok(())
/// # }
/// #
/// # fn main() { }
/// ```
///
/// # Errors
///
/// This method fails whenever the response body is not in JSON format
/// or it cannot be properly deserialized to target type `T`. For more
/// details please see [`serde_json::from_reader`].
///
/// [`serde_json::from_reader`]: https://docs.serde.rs/serde_json/fn.from_reader.html
#[cfg(feature = "json")]
/// Enable a persistent cookie store for the client.
///
/// Cookies received in responses will be preserved and included in
/// additional requests.
///
/// By default, no cookie store is used.
///
/// # Optional
///
/// This requires the optional `cookies` feature to be enabled.
#[cfg(feature = "cookies")]
/// Controls the use of TLS server name indication.
///
/// Defaults to `true`.
///
/// # Optional
///
/// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
/// feature to be enabled.
#[cfg(feature = "__tls")]
/// Send a JSON body.
///
/// Sets the body to the JSON serialization of the passed value, and
/// also sets the `Content-Type: application/json` header.
///
/// # Optional
///
/// This requires the optional `json` feature enabled.
///
/// # Examples
///
/// ```rust
/// # use reqwest::Error;
/// # use std::collections::HashMap;
/// #
/// # fn run() -> Result<(), Error> {
/// let mut map = HashMap::new();
/// map.insert("lang", "rust");
///
/// let client = reqwest::blocking::Client::new();
/// let res = client.post("http://httpbin.org")
/// .json(&map)
/// .send()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Serialization can fail if `T`'s implementation of `Serialize` decides to
/// fail, or if `T` contains a map with non-string keys.
#[cfg(feature = "json")]
/// Enables the [trust-dns](trust_dns_resolver) async resolver instead of a default threadpool using `getaddrinfo`.
///
/// If the `trust-dns` feature is turned on, the default option is enabled.
///
/// # Optional
///
/// This requires the optional `trust-dns` feature to be enabled
#[cfg(feature = "trust-dns")]
/// Parses a chain of PEM encoded X509 certificates, with the leaf certificate first.
/// `key` is a PEM encoded PKCS #8 formatted private key for the leaf certificate.
///
/// The certificate chain should contain any intermediate cerficates that should be sent to
/// clients to allow them to build a chain to a trusted root.
///
/// A certificate chain here means a series of PEM encoded certificates concatenated together.
///
/// # Examples
///
/// ```
/// # use std::fs;
/// # fn pkcs8() -> Result<(), Box<std::error::Error>> {
/// let cert = fs::read("client.pem")?;
/// let key = fs::read("key.pem")?;
/// let pkcs8 = reqwest::Identity::from_pkcs8_pem(&cert, &key)?;
/// # drop(pkcs8);
/// # Ok(())
/// # }
/// ```
///
/// # Optional
///
/// This requires the `native-tls` Cargo feature enabled.
#[cfg(feature = "native-tls")]
/// Retrieve the cookies contained in the response.
///
/// Note that invalid 'Set-Cookie' headers will be ignored.
///
/// # Optional
///
/// This requires the optional `cookies` feature to be enabled.
#[cfg(feature = "cookies")]
/// Add TLS information as `TlsInfo` extension to responses.
///
/// # Optional
///
/// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
/// feature to be enabled.
#[cfg(feature = "__tls")]
/// Parses a DER-formatted PKCS #12 archive, using the specified password to decrypt the key.
///
/// The archive should contain a leaf certificate and its private key, as well any intermediate
/// certificates that allow clients to build a chain to a trusted root.
/// The chain certificates should be in order from the leaf certificate towards the root.
///
/// PKCS #12 archives typically have the file extension `.p12` or `.pfx`, and can be created
/// with the OpenSSL `pkcs12` tool:
///
/// ```bash
/// openssl pkcs12 -export -out identity.pfx -inkey key.pem -in cert.pem -certfile chain_certs.pem
/// ```
///
/// # Examples
///
/// ```
/// # use std::fs::File;
/// # use std::io::Read;
/// # fn pkcs12() -> Result<(), Box<std::error::Error>> {
/// let mut buf = Vec::new();
/// File::open("my-ident.pfx")?
/// .read_to_end(&mut buf)?;
/// let pkcs12 = reqwest::Identity::from_pkcs12_der(&buf, "my-privkey-password")?;
/// # drop(pkcs12);
/// # Ok(())
/// # }
/// ```
///
/// # Optional
///
/// This requires the `native-tls` Cargo feature enabled.
#[cfg(feature = "native-tls")]
/// Force using the Rustls TLS backend.
///
/// Since multiple TLS backends can be optionally enabled, this option will
/// force the `rustls` backend to be used for this `Client`.
///
/// # Optional
///
/// This requires the optional `rustls-tls(-...)` feature to be enabled.
#[cfg(feature = "__rustls")]
/// Convert the response into a `Stream` of `Bytes` from the body.
///
/// # Example
///
/// ```
/// use futures_util::StreamExt;
///
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let mut stream = reqwest::get("http://httpbin.org/ip")
/// .await?
/// .bytes_stream();
///
/// while let Some(item) = stream.next().await {
/// println!("Chunk: {:?}", item?);
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Optional
///
/// This requires the optional `stream` feature to be enabled.
#[cfg(feature = "stream")]
/// Parses PEM encoded private key and certificate.
///
/// The input should contain a PEM encoded private key
/// and at least one PEM encoded certificate.
///
/// Note: The private key must be in RSA, SEC1 Elliptic Curve or PKCS#8 format.
///
/// # Examples
///
/// ```
/// # use std::fs::File;
/// # use std::io::Read;
/// # fn pem() -> Result<(), Box<std::error::Error>> {
/// let mut buf = Vec::new();
/// File::open("my-ident.pem")?
/// .read_to_end(&mut buf)?;
/// let id = reqwest::Identity::from_pem(&buf)?;
/// # drop(id);
/// # Ok(())
/// # }
/// ```
///
/// # Optional
///
/// This requires the `rustls-tls(-...)` Cargo feature enabled.
#[cfg(feature = "__rustls")]
/// Wrap a futures `Stream` in a box inside `Body`.
///
/// # Example
///
/// ```
/// # use hyper::Body;
/// let chunks: Vec<Result<_, std::io::Error>> = vec![
/// Ok("hello"),
/// Ok(" "),
/// Ok("world"),
/// ];
///
/// let stream = futures_util::stream::iter(chunks);
///
/// let body = Body::wrap_stream(stream);
/// ```
///
/// # Optional
///
/// This function requires enabling the `stream` feature in your
/// `Cargo.toml`.
#[cfg(feature = "stream")]
/// Sets the identity to be used for client certificate authentication.
///
/// # Optional
///
/// This requires the optional `native-tls` or `rustls-tls(-...)` feature to be
/// enabled.
#[cfg(any(feature = "native-tls", feature = "__rustls"))]
/// Controls the use of certificate validation.
///
/// Defaults to `false`.
///
/// # Warning
///
/// You should think very carefully before using this method. If
/// invalid certificates are trusted, *any* certificate for *any* site
/// will be trusted for use. This includes expired certificates. This
/// introduces significant vulnerabilities, and should only be used
/// as a last resort.
///
/// # Optional
///
/// This requires the optional `default-tls`, `native-tls`, or `rustls-tls(-...)`
/// feature to be enabled.
#[cfg(feature = "__tls")]
/// The [`textDocument/definition`] request asks the server for the definition location of a
/// symbol at a given text document position.
///
/// [`textDocument/definition`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_definition
///
/// # Compatibility
///
/// The [`GotoDefinitionResponse::Link`](lsp_types::GotoDefinitionResponse::Link) return value
/// was introduced in specification version 3.14.0 and requires client-side support in order to
/// be used. It can be returned if the client set the following field to `true` in the
/// [`initialize`](Self::initialize) method:
///
/// ```text
/// InitializeParams::capabilities::text_document::definition::link_support
/// ```
#[rpc(name = "textDocument/definition")]
/// The [`inlayHint/resolve`] request is sent from the client to the server to resolve
/// additional information for a given inlay hint.
///
/// [`inlayHint/resolve`]: https://microsoft.github.io/language-server-protocol/specification#inlayHint_resolve
///
/// This is usually used to compute the tooltip, location or command properties of an inlay
/// hint’s label part to avoid its unnecessary computation during the `textDocument/inlayHint`
/// request.
///
/// Consider a client announces the `label.location` property as a property that can be
/// resolved lazily using the client capability:
///
/// ```js
/// textDocument.inlayHint.resolveSupport = { properties: ['label.location'] };
/// ```
///
/// then an inlay hint with a label part, but without a location, must be resolved using the
/// `inlayHint/resolve` request before it can be used.
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0
#[rpc(name = "inlayHint/resolve")]
/// The [`textDocument/selectionRange`] request is sent from the client to the server to return
/// suggested selection ranges at an array of given positions. A selection range is a range
/// around the cursor position which the user might be interested in selecting.
///
/// [`textDocument/selectionRange`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_selectionRange
///
/// A selection range in the return array is for the position in the provided parameters at the
/// same index. Therefore `params.positions[i]` must be contained in `result[i].range`.
///
/// # Compatibility
///
/// This request was introduced in specification version 3.15.0.
#[rpc(name = "textDocument/selectionRange")]
/// The [`textDocument/inlineValue`] request is sent from the client to the server to compute
/// inline values for a given text document that may be rendered in the editor at the end of
/// lines.
///
/// [`textDocument/inlineValue`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_inlineValue
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0.
#[rpc(name = "textDocument/inlineValue")]
/// The [`workspace/willCreateFiles`] request is sent from the client to the server before
/// files are actually created as long as the creation is triggered from within the client.
///
/// [`workspace/willCreateFiles`]: https://microsoft.github.io/language-server-protocol/specification#workspace_willCreateFiles
///
/// The request can return a [`WorkspaceEdit`] which will be applied to workspace before the
/// files are created. Please note that clients might drop results if computing the edit took
/// too long or if a server constantly fails on this request. This is done to keep creates fast
/// and reliable.
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
#[rpc(name = "workspace/willCreateFiles")]
/// The [`textDocument/semanticTokens/full`] request is sent from the client to the server to
/// resolve the semantic tokens of a given file.
///
/// [`textDocument/semanticTokens/full`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_semanticTokens
///
/// Semantic tokens are used to add additional color information to a file that depends on
/// language specific symbol information. A semantic token request usually produces a large
/// result. The protocol therefore supports encoding tokens with numbers. In addition, optional
/// support for deltas is available, i.e. [`semantic_tokens_full_delta`].
///
/// [`semantic_tokens_full_delta`]: Self::semantic_tokens_full_delta
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
#[rpc(name = "textDocument/semanticTokens/full")]
/// The [`textDocument/prepareRename`] request is sent from the client to the server to setup
/// and test the validity of a rename operation at a given location.
///
/// [`textDocument/prepareRename`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_prepareRename
///
/// # Compatibility
///
/// This request was introduced in specification version 3.12.0.
#[rpc(name = "textDocument/prepareRename")]
/// The [`textDocument/typeDefinition`] request asks the server for the type definition location of
/// a symbol at a given text document position.
///
/// [`textDocument/typeDefinition`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_typeDefinition
///
/// # Compatibility
///
/// This request was introduced in specification version 3.6.0.
///
/// The [`GotoTypeDefinitionResponse::Link`](lsp_types::GotoDefinitionResponse::Link) return
/// value was introduced in specification version 3.14.0 and requires client-side support in
/// order to be used. It can be returned if the client set the following field to `true` in the
/// [`initialize`](Self::initialize) method:
///
/// ```text
/// InitializeParams::capabilities::text_document::type_definition::link_support
/// ```
#[rpc(name = "textDocument/typeDefinition")]
/// Asks the client to display a particular resource referenced by a URI in the user interface.
///
/// Returns `Ok(true)` if the document was successfully shown, or `Ok(false)` otherwise.
///
/// This corresponds to the [`window/showDocument`] request.
///
/// [`window/showDocument`]: https://microsoft.github.io/language-server-protocol/specification#window_showDocument
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
pub async fn show_document(&self, params: ShowDocumentParams) -> jsonrpc::Result<bool> {
/// The [`typeHierarchy/subtypes`] request is sent from the client to the server to resolve
/// the **subtypes** for a given type hierarchy item.
///
/// Returns `Ok(None)` if the server couldn’t infer a valid type from item in `params`.
///
/// The request doesn’t define its own client and server capabilities. It is only issued if a
/// server registers for the `textDocument/prepareTypeHierarchy` request.
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0.
#[rpc(name = "typeHierarchy/subtypes")]
/// The [`textDocument/completion`] request is sent from the client to the server to compute
/// completion items at a given cursor position.
///
/// If computing full completion items is expensive, servers can additionally provide a handler
/// for the completion item resolve request (`completionItem/resolve`). This request is sent
/// when a completion item is selected in the user interface.
///
/// [`textDocument/completion`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_completion
///
/// # Compatibility
///
/// Since 3.16.0, the client can signal that it can resolve more properties lazily. This is
/// done using the `completion_item.resolve_support` client capability which lists all
/// properties that can be filled in during a `completionItem/resolve` request.
///
/// All other properties (usually `sort_text`, `filter_text`, `insert_text`, and `text_edit`)
/// must be provided in the `textDocument/completion` response and must not be changed during
/// resolve.
#[rpc(name = "textDocument/completion")]
/// The [`textDocument/colorPresentation`] request is sent from the client to the server to
/// obtain a list of presentations for a color value at a given location.
///
/// [`textDocument/colorPresentation`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_colorPresentation
///
/// Clients can use the result to:
///
/// * Modify a color reference
/// * Show in a color picker and let users pick one of the presentations
///
/// # Compatibility
///
/// This request was introduced in specification version 3.6.0.
///
/// This request has no special capabilities and registration options since it is sent as a
/// resolve request for the [`textDocument/documentColor`](Self::document_color) request.
#[rpc(name = "textDocument/colorPresentation")]
/// The [`textDocument/semanticTokens/range`] request is sent from the client to the server to
/// resolve the semantic tokens **for the visible range** of a given file.
///
/// [`textDocument/semanticTokens/range`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_semanticTokens
///
/// When a user opens a file, it can be beneficial to only compute the semantic tokens for the
/// visible range (faster rendering of the tokens in the user interface). If a server can
/// compute these tokens faster than for the whole file, it can implement this method to handle
/// this special case.
///
/// See the [`semantic_tokens_full`](Self::semantic_tokens_full) documentation for more
/// details.
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
#[rpc(name = "textDocument/semanticTokens/range")]
/// The [`textDocument/codeAction`] request is sent from the client to the server to compute
/// commands for a given text document and range. These commands are typically code fixes to
/// either fix problems or to beautify/refactor code.
///
/// The result of a [`textDocument/codeAction`] request is an array of `Command` literals which
/// are typically presented in the user interface.
///
/// [`textDocument/codeAction`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_codeAction
///
/// To ensure that a server is useful in many clients, the commands specified in a code actions
/// should be handled by the server and not by the client (see [`workspace/executeCommand`] and
/// `ServerCapabilities::execute_command_provider`). If the client supports providing edits
/// with a code action, then the mode should be used.
///
/// When the command is selected the server should be contacted again (via the
/// [`workspace/executeCommand`] request) to execute the command.
///
/// [`workspace/executeCommand`]: https://microsoft.github.io/language-server-protocol/specification#workspace_executeCommand
///
/// # Compatibility
///
/// ## Since version 3.16.0
///
/// A client can offer a server to delay the computation of code action properties during a
/// `textDocument/codeAction` request. This is useful for cases where it is expensive to
/// compute the value of a property (for example, the `edit` property).
///
/// Clients signal this through the `code_action.resolve_support` client capability which lists
/// all properties a client can resolve lazily. The server capability
/// `code_action_provider.resolve_provider` signals that a server will offer a
/// `codeAction/resolve` route.
///
/// To help servers uniquely identify a code action in the resolve request, a code action
/// literal may optionally carry a `data` property. This is also guarded by an additional
/// client capability `code_action.data_support`. In general, a client should offer data
/// support if it offers resolve support.
///
/// It should also be noted that servers shouldn’t alter existing attributes of a code action
/// in a `codeAction/resolve` request.
///
/// ## Since version 3.8.0
///
/// Support for [`CodeAction`] literals to enable the following scenarios:
///
/// * The ability to directly return a workspace edit from the code action request.
/// This avoids having another server roundtrip to execute an actual code action.
/// However server providers should be aware that if the code action is expensive to compute
/// or the edits are huge it might still be beneficial if the result is simply a command and
/// the actual edit is only computed when needed.
///
/// * The ability to group code actions using a kind. Clients are allowed to ignore that
/// information. However it allows them to better group code action, for example, into
/// corresponding menus (e.g. all refactor code actions into a refactor menu).
#[rpc(name = "textDocument/codeAction")]
/// The [`textDocument/implementation`] request is sent from the client to the server to resolve
/// the implementation location of a symbol at a given text document position.
///
/// [`textDocument/implementation`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_implementation
///
/// # Compatibility
///
/// This request was introduced in specification version 3.6.0.
///
/// The [`GotoImplementationResponse::Link`](lsp_types::GotoDefinitionResponse::Link)
/// return value was introduced in specification version 3.14.0 and requires client-side
/// support in order to be used. It can be returned if the client set the following field to
/// `true` in the [`initialize`](Self::initialize) method:
///
/// ```text
/// InitializeParams::capabilities::text_document::implementation::link_support
/// ```
#[rpc(name = "textDocument/implementation")]
/// Asks the client to refresh the editors for which this server provides semantic tokens. As a
/// result, the client should ask the server to recompute the semantic tokens for these
/// editors.
///
/// This is useful if a server detects a project-wide configuration change which requires a
/// re-calculation of all semantic tokens. Note that the client still has the freedom to delay
/// the re-calculation of the semantic tokens if for example an editor is currently not visible.
///
/// This corresponds to the [`workspace/semanticTokens/refresh`] request.
///
/// [`workspace/semanticTokens/refresh`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_semanticTokens
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
pub async fn semantic_tokens_refresh(&self) -> jsonrpc::Result<()> {
/// Asks the client to refresh the inline values currently shown in editors. As a result, the
/// client should ask the server to recompute the inline values for these editors.
///
/// This is useful if a server detects a configuration change which requires a re-calculation
/// of all inline values. Note that the client still has the freedom to delay the
/// re-calculation of the inline values if for example an editor is currently not visible.
///
/// This corresponds to the [`workspace/inlineValue/refresh`] request.
///
/// [`workspace/inlineValue/refresh`]: https://microsoft.github.io/language-server-protocol/specification#workspace_inlineValue_refresh
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0.
pub async fn inline_value_refresh(&self) -> jsonrpc::Result<()> {
/// Asks the client to refresh the inlay hints currently shown in editors. As a result, the
/// client should ask the server to recompute the inlay hints for these editors.
///
/// This is useful if a server detects a configuration change which requires a re-calculation
/// of all inlay hints. Note that the client still has the freedom to delay the re-calculation
/// of the inlay hints if for example an editor is currently not visible.
///
/// This corresponds to the [`workspace/inlayHint/refresh`] request.
///
/// [`workspace/inlayHint/refresh`]: https://microsoft.github.io/language-server-protocol/specification#workspace_inlayHint_refresh
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0.
pub async fn inlay_hint_refresh(&self) -> jsonrpc::Result<()> {
/// The [`textDocument/declaration`] request asks the server for the declaration location of a
/// symbol at a given text document position.
///
/// [`textDocument/declaration`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_declaration
///
/// # Compatibility
///
/// This request was introduced in specification version 3.14.0.
///
/// The [`GotoDeclarationResponse::Link`](lsp_types::GotoDefinitionResponse::Link) return value
/// was introduced in specification version 3.14.0 and requires client-side support in order to
/// be used. It can be returned if the client set the following field to `true` in the
/// [`initialize`](Self::initialize) method:
///
/// ```text
/// InitializeParams::capabilities::text_document::declaration::link_support
/// ```
#[rpc(name = "textDocument/declaration")]
/// The [`textDocument/semanticTokens/full/delta`] request is sent from the client to the server to
/// resolve the semantic tokens of a given file, **returning only the delta**.
///
/// [`textDocument/semanticTokens/full/delta`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_semanticTokens
///
/// Similar to [`semantic_tokens_full`](Self::semantic_tokens_full), except it returns a
/// sequence of [`SemanticTokensEdit`] to transform a previous result into a new result.
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
#[rpc(name = "textDocument/semanticTokens/full/delta")]
/// The [`textDocument/documentColor`] request is sent from the client to the server to list
/// all color references found in a given text document. Along with the range, a color value in
/// RGB is returned.
///
/// [`textDocument/documentColor`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_documentColor
///
/// Clients can use the result to decorate color references in an editor. For example:
///
/// * Color boxes showing the actual color next to the reference
/// * Show a color picker when a color reference is edited
///
/// # Compatibility
///
/// This request was introduced in specification version 3.6.0.
#[rpc(name = "textDocument/documentColor")]
/// Asks the client to refresh the code lenses currently shown in editors. As a result, the
/// client should ask the server to recompute the code lenses for these editors.
///
/// This is useful if a server detects a configuration change which requires a re-calculation
/// of all code lenses.
///
/// Note that the client still has the freedom to delay the re-calculation of the code lenses
/// if for example an editor is currently not visible.
///
/// This corresponds to the [`workspace/codeLens/refresh`] request.
///
/// [`workspace/codeLens/refresh`]: https://microsoft.github.io/language-server-protocol/specification#codeLens_refresh
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
pub async fn code_lens_refresh(&self) -> jsonrpc::Result<()> {
/// The [`textDocument/documentLink`] request is sent from the client to the server to request
/// the location of links in a document.
///
/// A document link is a range in a text document that links to an internal or external
/// resource, like another text document or a web site.
///
/// [`textDocument/documentLink`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_documentLink
///
/// # Compatibility
///
/// The [`DocumentLink::tooltip`] field was introduced in specification version 3.15.0 and
/// requires client-side support in order to be used. It can be returned if the client set the
/// following field to `true` in the [`initialize`](Self::initialize) method:
///
/// ```text
/// InitializeParams::capabilities::text_document::document_link::tooltip_support
/// ```
#[rpc(name = "textDocument/documentLink")]
/// The [`textDocument/foldingRange`] request is sent from the client to the server to return
/// all folding ranges found in a given text document.
///
/// [`textDocument/foldingRange`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_foldingRange
///
/// # Compatibility
///
/// This request was introduced in specification version 3.10.0.
#[rpc(name = "textDocument/foldingRange")]
/// The [`textDocument/diagnostic`] request is sent from the client to the server to ask the
/// server to compute the diagnostics for a given document.
///
/// As with other pull requests, the server is asked to compute the diagnostics for the
/// currently synced version of the document.
///
/// The request doesn't define its own client and server capabilities. It is only issued if a
/// server registers for the [`textDocument/diagnostic`] request.
///
/// [`textDocument/diagnostic`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_diagnostic
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0.
#[rpc(name = "textDocument/diagnostic")]
/// The [`textDocument/inlayHint`] request is sent from the client to the server to compute
/// inlay hints for a given `(text document, range)` tuple that may be rendered in the editor
/// in place with other text.
///
/// [`textDocument/inlayHint`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_inlayHint
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0
#[rpc(name = "textDocument/inlayHint")]
/// The [`callHierarchy/outgoingCalls`] request is sent from the client to the server to
/// resolve **outgoing** calls for a given call hierarchy item.
///
/// The request doesn't define its own client and server capabilities. It is only issued if a
/// server registers for the [`textDocument/prepareCallHierarchy`] request.
///
/// [`callHierarchy/outgoingCalls`]: https://microsoft.github.io/language-server-protocol/specification#callHierarchy_outgoingCalls
/// [`textDocument/prepareCallHierarchy`]: Self::prepare_call_hierarchy
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
#[rpc(name = "callHierarchy/outgoingCalls")]
/// Creates a new "content modified" error (`-32801`).
///
/// # Compatibility
///
/// This error code is defined by the Language Server Protocol.
pub const fn content_modified() -> Self {
/// Returns the index of the last occurrence of this needle in the given
/// haystack.
///
/// The haystack may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::FinderReverse;
///
/// let haystack = "foo bar baz";
/// assert_eq!(Some(0), FinderReverse::new("foo").rfind(haystack));
/// assert_eq!(Some(4), FinderReverse::new("bar").rfind(haystack));
/// assert_eq!(None, FinderReverse::new("quux").rfind(haystack));
/// ```
#[inline]
/// Returns the index of the first occurrence of the given needle.
///
/// The needle may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// Note that if you're are searching for the same needle in many
/// different small haystacks, it may be faster to initialize a
/// [`Finder`](struct.Finder.html) once, and reuse it for each search.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo bar baz";
/// assert_eq!(Some(0), s.find("foo"));
/// assert_eq!(Some(4), s.find("bar"));
/// assert_eq!(None, s.find("quux"));
/// ```
#[inline]
/// Returns the index of the first occurrence of this needle in the given
/// haystack.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use memchr::memmem::Finder;
///
/// let haystack = b"foo bar baz";
/// assert_eq!(Some(0), Finder::new("foo").find(haystack));
/// assert_eq!(Some(4), Finder::new("bar").find(haystack));
/// assert_eq!(None, Finder::new("quux").find(haystack));
/// ```
#[inline]
/// Returns a reverse iterator over all occurrences of a substring in a
/// haystack.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use memchr::memmem::FinderRev;
///
/// let haystack = b"foo bar foo baz foo";
/// let finder = FinderRev::new(b"foo");
/// let mut it = finder.rfind_iter(haystack);
/// assert_eq!(Some(16), it.next());
/// assert_eq!(Some(8), it.next());
/// assert_eq!(Some(0), it.next());
/// assert_eq!(None, it.next());
/// ```
#[inline]
/// Returns an iterator of the non-overlapping occurrences of the given
/// needle. The iterator yields byte offset positions indicating the start
/// of each match.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo bar foo foo quux foo";
/// let matches: Vec<usize> = s.find_iter("foo").collect();
/// assert_eq!(matches, vec![0, 8, 12, 21]);
/// ```
///
/// An empty string matches at every position, including the position
/// immediately following the last byte:
///
/// ```
/// use bstr::ByteSlice;
///
/// let matches: Vec<usize> = b"foo".find_iter("").collect();
/// assert_eq!(matches, vec![0, 1, 2, 3]);
///
/// let matches: Vec<usize> = b"".find_iter("").collect();
/// assert_eq!(matches, vec![0]);
/// ```
#[inline]
/// Returns the index of the first occurrence of this needle in the given
/// haystack.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use memchr::memmem::Finder;
///
/// let haystack = b"foo bar baz";
/// assert_eq!(Some(0), Finder::new("foo").find(haystack));
/// assert_eq!(Some(4), Finder::new("bar").find(haystack));
/// assert_eq!(None, Finder::new("quux").find(haystack));
/// ```
pub fn find(&self, haystack: &[u8]) -> Option<usize> {
/// Returns a reverse iterator over all occurrences of a substring in a
/// haystack.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use memchr::memmem::FinderRev;
///
/// let haystack = b"foo bar foo baz foo";
/// let finder = FinderRev::new(b"foo");
/// let mut it = finder.rfind_iter(haystack);
/// assert_eq!(Some(16), it.next());
/// assert_eq!(Some(8), it.next());
/// assert_eq!(Some(0), it.next());
/// assert_eq!(None, it.next());
/// ```
#[inline]
/// Replaces all non-overlapping matches in the haystack with the
/// replacement provided. This is the same as calling `replacen` with
/// `limit` set to `0`.
///
/// The documentation for [`Regex::replace`] goes into more detail about
/// what kinds of replacement strings are supported.
///
/// # Time complexity
///
/// Since iterators over all matches requires running potentially many
/// searches on the haystack, and since each search has worst case
/// `O(m * n)` time complexity, the overall worst case time complexity for
/// this routine is `O(m * n^2)`.
///
/// # Fallibility
///
/// If you need to write a replacement routine where any individual
/// replacement might "fail," doing so with this API isn't really feasible
/// because there's no way to stop the search process if a replacement
/// fails. Instead, if you need this functionality, you should consider
/// implementing your own replacement routine:
///
/// ```
/// use regex::bytes::{Captures, Regex};
///
/// fn replace_all<E>(
/// re: &Regex,
/// haystack: &[u8],
/// replacement: impl Fn(&Captures) -> Result<Vec<u8>, E>,
/// ) -> Result<Vec<u8>, E> {
/// let mut new = Vec::with_capacity(haystack.len());
/// let mut last_match = 0;
/// for caps in re.captures_iter(haystack) {
/// let m = caps.get(0).unwrap();
/// new.extend_from_slice(&haystack[last_match..m.start()]);
/// new.extend_from_slice(&replacement(&caps)?);
/// last_match = m.end();
/// }
/// new.extend_from_slice(&haystack[last_match..]);
/// Ok(new)
/// }
///
/// // Let's replace each word with the number of bytes in that word.
/// // But if we see a word that is "too long," we'll give up.
/// let re = Regex::new(r"\w+").unwrap();
/// let replacement = |caps: &Captures| -> Result<Vec<u8>, &'static str> {
/// if caps[0].len() >= 5 {
/// return Err("word too long");
/// }
/// Ok(caps[0].len().to_string().into_bytes())
/// };
/// assert_eq!(
/// Ok(b"2 3 3 3?".to_vec()),
/// replace_all(&re, b"hi how are you?", &replacement),
/// );
/// assert!(replace_all(&re, b"hi there", &replacement).is_err());
/// ```
///
/// # Example
///
/// This example shows how to flip the order of whitespace (excluding line
/// terminators) delimited fields, and normalizes the whitespace that
/// delimits the fields:
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"(?m)^(\S+)[\s--\r\n]+(\S+)$").unwrap();
/// let hay = b"
/// Greetings 1973
/// Wild\t1973
/// BornToRun\t\t\t\t1975
/// Darkness 1978
/// TheRiver 1980
/// ";
/// let new = re.replace_all(hay, b"$2 $1");
/// assert_eq!(new, &b"
/// 1973 Greetings
/// 1973 Wild
/// 1975 BornToRun
/// 1978 Darkness
/// 1980 TheRiver
/// "[..]);
/// ```
#[inline]
/// Returns the index of the first occurrence of this needle in the given
/// haystack.
///
/// The haystack may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::Finder;
///
/// let haystack = "foo bar baz";
/// assert_eq!(Some(0), Finder::new("foo").find(haystack));
/// assert_eq!(Some(4), Finder::new("bar").find(haystack));
/// assert_eq!(None, Finder::new("quux").find(haystack));
/// ```
#[inline]
/// Replaces at most `limit` non-overlapping matches in the haystack with
/// the replacement provided. If `limit` is `0`, then all non-overlapping
/// matches are replaced. That is, `Regex::replace_all(hay, rep)` is
/// equivalent to `Regex::replacen(hay, 0, rep)`.
///
/// The documentation for [`Regex::replace`] goes into more detail about
/// what kinds of replacement strings are supported.
///
/// # Time complexity
///
/// Since iterators over all matches requires running potentially many
/// searches on the haystack, and since each search has worst case
/// `O(m * n)` time complexity, the overall worst case time complexity for
/// this routine is `O(m * n^2)`.
///
/// Although note that the worst case time here has an upper bound given
/// by the `limit` parameter.
///
/// # Fallibility
///
/// See the corresponding section in the docs for [`Regex::replace_all`]
/// for tips on how to deal with a replacement routine that can fail.
///
/// # Example
///
/// This example shows how to flip the order of whitespace (excluding line
/// terminators) delimited fields, and normalizes the whitespace that
/// delimits the fields. But we only do it for the first two matches.
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"(?m)^(\S+)[\s--\r\n]+(\S+)$").unwrap();
/// let hay = b"
/// Greetings 1973
/// Wild\t1973
/// BornToRun\t\t\t\t1975
/// Darkness 1978
/// TheRiver 1980
/// ";
/// let new = re.replacen(hay, 2, b"$2 $1");
/// assert_eq!(new, &b"
/// 1973 Greetings
/// 1973 Wild
/// BornToRun\t\t\t\t1975
/// Darkness 1978
/// TheRiver 1980
/// "[..]);
/// ```
#[inline]
/// Returns the index of the first occurrence of this needle in the given
/// haystack.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use memchr::memmem::Finder;
///
/// let haystack = b"foo bar baz";
/// assert_eq!(Some(0), Finder::new("foo").find(haystack));
/// assert_eq!(Some(4), Finder::new("bar").find(haystack));
/// assert_eq!(None, Finder::new("quux").find(haystack));
/// ```
pub fn find(&self, haystack: &[u8]) -> Option<usize> {
/// Returns an iterator over all occurrences of a substring in a haystack.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use memchr::memmem::Finder;
///
/// let haystack = b"foo bar foo baz foo";
/// let finder = Finder::new(b"foo");
/// let mut it = finder.find_iter(haystack);
/// assert_eq!(Some(0), it.next());
/// assert_eq!(Some(8), it.next());
/// assert_eq!(Some(16), it.next());
/// assert_eq!(None, it.next());
/// ```
#[inline]
/// Returns a mutable reference to the greatest item in the binary heap, or
/// `None` if it is empty.
///
/// Note: If the `PeekMut` value is leaked, some heap elements might get
/// leaked along with it, but the remaining elements will remain a valid
/// heap.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// assert!(heap.peek_mut().is_none());
///
/// heap.push(1);
/// heap.push(5);
/// heap.push(2);
/// {
/// let mut val = heap.peek_mut().unwrap();
/// *val = 0;
/// }
/// assert_eq!(heap.peek(), Some(&2));
/// ```
///
/// # Time complexity
///
/// If the item is modified then the worst case time complexity is *O*(log(*n*)),
/// otherwise it's *O*(1).
#[stable(feature = "binary_heap_peek_mut", since = "1.12.0")]
/// Rotates the double-ended queue `n` places to the left.
///
/// Equivalently,
/// - Rotates item `n` into the first position.
/// - Pops the first `n` items and pushes them to the end.
/// - Rotates `len() - n` places to the right.
///
/// # Panics
///
/// If `n` is greater than `len()`. Note that `n == len()`
/// does _not_ panic and is a no-op rotation.
///
/// # Complexity
///
/// Takes `*O*(min(n, len() - n))` time and no extra space.
///
/// # Examples
///
/// ```
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<_> = (0..10).collect();
///
/// buf.rotate_left(3);
/// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
///
/// for i in 1..10 {
/// assert_eq!(i * 3 % 10, buf[0]);
/// buf.rotate_left(3);
/// }
/// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
/// ```
#[stable(feature = "vecdeque_rotate", since = "1.36.0")]
/// Returns an iterator of at most `limit` substrings of the haystack
/// given, delimited by a match of the regex. (A `limit` of `0` will return
/// no substrings.) Namely, each element of the iterator corresponds to a
/// part of the haystack that *isn't* matched by the regular expression.
/// The remainder of the haystack that is not split will be the last
/// element in the iterator.
///
/// # Time complexity
///
/// Since iterators over all matches requires running potentially many
/// searches on the haystack, and since each search has worst case
/// `O(m * n)` time complexity, the overall worst case time complexity for
/// this routine is `O(m * n^2)`.
///
/// Although note that the worst case time here has an upper bound given
/// by the `limit` parameter.
///
/// # Example
///
/// Get the first two words in some haystack:
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r"\W+").unwrap();
/// let hay = "Hey! How are you?";
/// let fields: Vec<&str> = re.splitn(hay, 3).collect();
/// assert_eq!(fields, vec!["Hey", "How", "are you?"]);
/// ```
///
/// # Examples: more cases
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r" ").unwrap();
/// let hay = "Mary had a little lamb";
/// let got: Vec<&str> = re.splitn(hay, 3).collect();
/// assert_eq!(got, vec!["Mary", "had", "a little lamb"]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = "";
/// let got: Vec<&str> = re.splitn(hay, 3).collect();
/// assert_eq!(got, vec![""]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = "lionXXtigerXleopard";
/// let got: Vec<&str> = re.splitn(hay, 3).collect();
/// assert_eq!(got, vec!["lion", "", "tigerXleopard"]);
///
/// let re = Regex::new(r"::").unwrap();
/// let hay = "lion::tiger::leopard";
/// let got: Vec<&str> = re.splitn(hay, 2).collect();
/// assert_eq!(got, vec!["lion", "tiger::leopard"]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = "abcXdef";
/// let got: Vec<&str> = re.splitn(hay, 1).collect();
/// assert_eq!(got, vec!["abcXdef"]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = "abcdef";
/// let got: Vec<&str> = re.splitn(hay, 2).collect();
/// assert_eq!(got, vec!["abcdef"]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = "abcXdef";
/// let got: Vec<&str> = re.splitn(hay, 0).collect();
/// assert!(got.is_empty());
/// ```
#[inline]
/// Returns an iterator of at most `limit` substrings of the haystack
/// given, delimited by a match of the regex. (A `limit` of `0` will return
/// no substrings.) Namely, each element of the iterator corresponds to a
/// part of the haystack that *isn't* matched by the regular expression.
/// The remainder of the haystack that is not split will be the last
/// element in the iterator.
///
/// # Time complexity
///
/// Since iterators over all matches requires running potentially many
/// searches on the haystack, and since each search has worst case
/// `O(m * n)` time complexity, the overall worst case time complexity for
/// this routine is `O(m * n^2)`.
///
/// Although note that the worst case time here has an upper bound given
/// by the `limit` parameter.
///
/// # Example
///
/// Get the first two words in some haystack:
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"\W+").unwrap();
/// let hay = b"Hey! How are you?";
/// let fields: Vec<&[u8]> = re.splitn(hay, 3).collect();
/// assert_eq!(fields, vec![&b"Hey"[..], &b"How"[..], &b"are you?"[..]]);
/// ```
///
/// # Examples: more cases
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r" ").unwrap();
/// let hay = b"Mary had a little lamb";
/// let got: Vec<&[u8]> = re.splitn(hay, 3).collect();
/// assert_eq!(got, vec![&b"Mary"[..], &b"had"[..], &b"a little lamb"[..]]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = b"";
/// let got: Vec<&[u8]> = re.splitn(hay, 3).collect();
/// assert_eq!(got, vec![&b""[..]]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = b"lionXXtigerXleopard";
/// let got: Vec<&[u8]> = re.splitn(hay, 3).collect();
/// assert_eq!(got, vec![&b"lion"[..], &b""[..], &b"tigerXleopard"[..]]);
///
/// let re = Regex::new(r"::").unwrap();
/// let hay = b"lion::tiger::leopard";
/// let got: Vec<&[u8]> = re.splitn(hay, 2).collect();
/// assert_eq!(got, vec![&b"lion"[..], &b"tiger::leopard"[..]]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = b"abcXdef";
/// let got: Vec<&[u8]> = re.splitn(hay, 1).collect();
/// assert_eq!(got, vec![&b"abcXdef"[..]]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = b"abcdef";
/// let got: Vec<&[u8]> = re.splitn(hay, 2).collect();
/// assert_eq!(got, vec![&b"abcdef"[..]]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = b"abcXdef";
/// let got: Vec<&[u8]> = re.splitn(hay, 0).collect();
/// assert!(got.is_empty());
/// ```
#[inline]
/// Returns the index of the first occurrence of this needle in the given
/// haystack.
///
/// The haystack may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::Finder;
///
/// let haystack = "foo bar baz";
/// assert_eq!(Some(0), Finder::new("foo").find(haystack));
/// assert_eq!(Some(4), Finder::new("bar").find(haystack));
/// assert_eq!(None, Finder::new("quux").find(haystack));
/// ```
#[inline]
/// Returns the index of the last occurrence of the given needle.
///
/// The needle may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// Note that if you're are searching for the same needle in many
/// different small haystacks, it may be faster to initialize a
/// [`FinderReverse`](struct.FinderReverse.html) once, and reuse it for
/// each search.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo bar baz";
/// assert_eq!(Some(0), s.rfind("foo"));
/// assert_eq!(Some(4), s.rfind("bar"));
/// assert_eq!(Some(8), s.rfind("ba"));
/// assert_eq!(None, s.rfind("quux"));
/// ```
#[inline]
/// Returns an iterator that yields successive non-overlapping matches in
/// the given haystack. The iterator yields values of type [`Captures`].
///
/// This is the same as [`Regex::find_iter`], but instead of only providing
/// access to the overall match, each value yield includes access to the
/// matches of all capture groups in the regex. Reporting this extra match
/// data is potentially costly, so callers should only use `captures_iter`
/// over `find_iter` when they actually need access to the capture group
/// matches.
///
/// # Time complexity
///
/// Note that since `captures_iter` runs potentially many searches on the
/// haystack and since each search has worst case `O(m * n)` time
/// complexity, the overall worst case time complexity for iteration is
/// `O(m * n^2)`.
///
/// # Example
///
/// We can use this to find all movie titles and their release years in
/// some haystack, where the movie is formatted like "'Title' (xxxx)":
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"'([^']+)'\s+\(([0-9]{4})\)").unwrap();
/// let hay = b"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
/// let mut movies = vec![];
/// for (_, [title, year]) in re.captures_iter(hay).map(|c| c.extract()) {
/// // OK because [0-9]{4} can only match valid UTF-8.
/// let year = std::str::from_utf8(year).unwrap();
/// movies.push((title, year.parse::<i64>()?));
/// }
/// assert_eq!(movies, vec![
/// (&b"Citizen Kane"[..], 1941),
/// (&b"The Wizard of Oz"[..], 1939),
/// (&b"M"[..], 1931),
/// ]);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// Or with named groups:
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"'(?<title>[^']+)'\s+\((?<year>[0-9]{4})\)").unwrap();
/// let hay = b"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
/// let mut it = re.captures_iter(hay);
///
/// let caps = it.next().unwrap();
/// assert_eq!(&caps["title"], b"Citizen Kane");
/// assert_eq!(&caps["year"], b"1941");
///
/// let caps = it.next().unwrap();
/// assert_eq!(&caps["title"], b"The Wizard of Oz");
/// assert_eq!(&caps["year"], b"1939");
///
/// let caps = it.next().unwrap();
/// assert_eq!(&caps["title"], b"M");
/// assert_eq!(&caps["year"], b"1931");
/// ```
#[inline]
/// Rotates the slice in-place such that the first `mid` elements of the
/// slice move to the end while the last `self.len() - mid` elements move to
/// the front. After calling `rotate_left`, the element previously at index
/// `mid` will become the first element in the slice.
///
/// # Panics
///
/// This function will panic if `mid` is greater than the length of the
/// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
/// rotation.
///
/// # Complexity
///
/// Takes linear (in `self.len()`) time.
///
/// # Examples
///
/// ```
/// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
/// a.rotate_left(2);
/// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
/// ```
///
/// Rotating a subslice:
///
/// ```
/// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
/// a[1..5].rotate_left(1);
/// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
/// ```
#[stable(feature = "slice_rotate", since = "1.26.0")]
/// Returns the index of the last occurrence of any of the bytes in the
/// provided set.
///
/// The `byteset` may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`, but
/// note that passing a `&str` which contains multibyte characters may not
/// behave as you expect: each byte in the `&str` is treated as an
/// individual member of the byte set.
///
/// Note that order is irrelevant for the `byteset` parameter, and duplicate
/// bytes present in its body are ignored.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the set of bytes and the haystack. That is, this
/// runs in `O(byteset.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(b"foo bar baz".rfind_byteset(b"agb"), Some(9));
/// assert_eq!(b"foo baz bar".rfind_byteset(b"rabz "), Some(10));
/// assert_eq!(b"foo baz bar".rfind_byteset(b"\n123"), None);
/// ```
#[inline]
/// Returns the index of the last occurrence of any of the bytes in the
/// provided set.
///
/// The `byteset` may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`, but
/// note that passing a `&str` which contains multibyte characters may not
/// behave as you expect: each byte in the `&str` is treated as an
/// individual member of the byte set.
///
/// Note that order is irrelevant for the `byteset` parameter, and duplicate
/// bytes present in its body are ignored.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the set of bytes and the haystack. That is, this
/// runs in `O(byteset.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// assert_eq!(b"foo bar baz".rfind_byteset(b"agb"), Some(9));
/// assert_eq!(b"foo baz bar".rfind_byteset(b"rabz "), Some(10));
/// assert_eq!(b"foo baz bar".rfind_byteset(b"\n123"), None);
/// ```
#[inline]
/// Returns an iterator of the non-overlapping occurrences of the given
/// needle in reverse. The iterator yields byte offset positions indicating
/// the start of each match.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo bar foo foo quux foo";
/// let matches: Vec<usize> = s.rfind_iter("foo").collect();
/// assert_eq!(matches, vec![21, 12, 8, 0]);
/// ```
///
/// An empty string matches at every position, including the position
/// immediately following the last byte:
///
/// ```
/// use bstr::ByteSlice;
///
/// let matches: Vec<usize> = b"foo".rfind_iter("").collect();
/// assert_eq!(matches, vec![3, 2, 1, 0]);
///
/// let matches: Vec<usize> = b"".rfind_iter("").collect();
/// assert_eq!(matches, vec![0]);
/// ```
#[inline]
/// Returns an iterator of substrings of the haystack given, delimited by a
/// match of the regex. Namely, each element of the iterator corresponds to
/// a part of the haystack that *isn't* matched by the regular expression.
///
/// # Time complexity
///
/// Since iterators over all matches requires running potentially many
/// searches on the haystack, and since each search has worst case
/// `O(m * n)` time complexity, the overall worst case time complexity for
/// this routine is `O(m * n^2)`.
///
/// # Example
///
/// To split a string delimited by arbitrary amounts of spaces or tabs:
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r"[ \t]+").unwrap();
/// let hay = "a b \t c\td e";
/// let fields: Vec<&str> = re.split(hay).collect();
/// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]);
/// ```
///
/// # Example: more cases
///
/// Basic usage:
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r" ").unwrap();
/// let hay = "Mary had a little lamb";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec!["Mary", "had", "a", "little", "lamb"]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = "";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec![""]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = "lionXXtigerXleopard";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec!["lion", "", "tiger", "leopard"]);
///
/// let re = Regex::new(r"::").unwrap();
/// let hay = "lion::tiger::leopard";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec!["lion", "tiger", "leopard"]);
/// ```
///
/// If a haystack contains multiple contiguous matches, you will end up
/// with empty spans yielded by the iterator:
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = "XXXXaXXbXc";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec!["", "", "", "", "a", "", "b", "c"]);
///
/// let re = Regex::new(r"/").unwrap();
/// let hay = "(///)";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec!["(", "", "", ")"]);
/// ```
///
/// Separators at the start or end of a haystack are neighbored by empty
/// substring.
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r"0").unwrap();
/// let hay = "010";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec!["", "1", ""]);
/// ```
///
/// When the empty string is used as a regex, it splits at every valid
/// UTF-8 boundary by default (which includes the beginning and end of the
/// haystack):
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r"").unwrap();
/// let hay = "rust";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec!["", "r", "u", "s", "t", ""]);
///
/// // Splitting by an empty string is UTF-8 aware by default!
/// let re = Regex::new(r"").unwrap();
/// let hay = "☃";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec!["", "☃", ""]);
/// ```
///
/// Contiguous separators (commonly shows up with whitespace), can lead to
/// possibly surprising behavior. For example, this code is correct:
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r" ").unwrap();
/// let hay = " a b c";
/// let got: Vec<&str> = re.split(hay).collect();
/// assert_eq!(got, vec!["", "", "", "", "a", "", "b", "c"]);
/// ```
///
/// It does *not* give you `["a", "b", "c"]`. For that behavior, you'd want
/// to match contiguous space characters:
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r" +").unwrap();
/// let hay = " a b c";
/// let got: Vec<&str> = re.split(hay).collect();
/// // N.B. This does still include a leading empty span because ' +'
/// // matches at the beginning of the haystack.
/// assert_eq!(got, vec!["", "a", "b", "c"]);
/// ```
#[inline]
/// Returns an iterator of the non-overlapping occurrences of the given
/// needle in reverse. The iterator yields byte offset positions indicating
/// the start of each match.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use bstr::ByteSlice;
///
/// let s = b"foo bar foo foo quux foo";
/// let matches: Vec<usize> = s.rfind_iter("foo").collect();
/// assert_eq!(matches, vec![21, 12, 8, 0]);
/// ```
///
/// An empty string matches at every position, including the position
/// immediately following the last byte:
///
/// ```
/// use bstr::ByteSlice;
///
/// let matches: Vec<usize> = b"foo".rfind_iter("").collect();
/// assert_eq!(matches, vec![3, 2, 1, 0]);
///
/// let matches: Vec<usize> = b"".rfind_iter("").collect();
/// assert_eq!(matches, vec![0]);
/// ```
#[inline]
/// Returns the index of the last occurrence of this needle in the given
/// haystack.
///
/// The haystack may be any type that can be cheaply converted into a
/// `&[u8]`. This includes, but is not limited to, `&str` and `&[u8]`.
///
/// # Complexity
///
/// This routine is guaranteed to have worst case linear time complexity
/// with respect to both the needle and the haystack. That is, this runs
/// in `O(needle.len() + haystack.len())` time.
///
/// This routine is also guaranteed to have worst case constant space
/// complexity.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use memchr::memmem::FinderRev;
///
/// let haystack = b"foo bar baz";
/// assert_eq!(Some(0), FinderRev::new("foo").rfind(haystack));
/// assert_eq!(Some(4), FinderRev::new("bar").rfind(haystack));
/// assert_eq!(None, FinderRev::new("quux").rfind(haystack));
/// ```
pub fn rfind<B: AsRef<[u8]>>(&self, haystack: B) -> Option<usize> {
/// Replaces all non-overlapping matches in the haystack with the
/// replacement provided. This is the same as calling `replacen` with
/// `limit` set to `0`.
///
/// The documentation for [`Regex::replace`] goes into more detail about
/// what kinds of replacement strings are supported.
///
/// # Time complexity
///
/// Since iterators over all matches requires running potentially many
/// searches on the haystack, and since each search has worst case
/// `O(m * n)` time complexity, the overall worst case time complexity for
/// this routine is `O(m * n^2)`.
///
/// # Fallibility
///
/// If you need to write a replacement routine where any individual
/// replacement might "fail," doing so with this API isn't really feasible
/// because there's no way to stop the search process if a replacement
/// fails. Instead, if you need this functionality, you should consider
/// implementing your own replacement routine:
///
/// ```
/// use regex::{Captures, Regex};
///
/// fn replace_all<E>(
/// re: &Regex,
/// haystack: &str,
/// replacement: impl Fn(&Captures) -> Result<String, E>,
/// ) -> Result<String, E> {
/// let mut new = String::with_capacity(haystack.len());
/// let mut last_match = 0;
/// for caps in re.captures_iter(haystack) {
/// let m = caps.get(0).unwrap();
/// new.push_str(&haystack[last_match..m.start()]);
/// new.push_str(&replacement(&caps)?);
/// last_match = m.end();
/// }
/// new.push_str(&haystack[last_match..]);
/// Ok(new)
/// }
///
/// // Let's replace each word with the number of bytes in that word.
/// // But if we see a word that is "too long," we'll give up.
/// let re = Regex::new(r"\w+").unwrap();
/// let replacement = |caps: &Captures| -> Result<String, &'static str> {
/// if caps[0].len() >= 5 {
/// return Err("word too long");
/// }
/// Ok(caps[0].len().to_string())
/// };
/// assert_eq!(
/// Ok("2 3 3 3?".to_string()),
/// replace_all(&re, "hi how are you?", &replacement),
/// );
/// assert!(replace_all(&re, "hi there", &replacement).is_err());
/// ```
///
/// # Example
///
/// This example shows how to flip the order of whitespace (excluding line
/// terminators) delimited fields, and normalizes the whitespace that
/// delimits the fields:
///
/// ```
/// use regex::Regex;
///
/// let re = Regex::new(r"(?m)^(\S+)[\s--\r\n]+(\S+)$").unwrap();
/// let hay = "
/// Greetings 1973
/// Wild\t1973
/// BornToRun\t\t\t\t1975
/// Darkness 1978
/// TheRiver 1980
/// ";
/// let new = re.replace_all(hay, "$2 $1");
/// assert_eq!(new, "
/// 1973 Greetings
/// 1973 Wild
/// 1975 BornToRun
/// 1978 Darkness
/// 1980 TheRiver
/// ");
/// ```
#[inline]
/// Returns an iterator of substrings of the haystack given, delimited by a
/// match of the regex. Namely, each element of the iterator corresponds to
/// a part of the haystack that *isn't* matched by the regular expression.
///
/// # Time complexity
///
/// Since iterators over all matches requires running potentially many
/// searches on the haystack, and since each search has worst case
/// `O(m * n)` time complexity, the overall worst case time complexity for
/// this routine is `O(m * n^2)`.
///
/// # Example
///
/// To split a string delimited by arbitrary amounts of spaces or tabs:
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"[ \t]+").unwrap();
/// let hay = b"a b \t c\td e";
/// let fields: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(fields, vec![
/// &b"a"[..], &b"b"[..], &b"c"[..], &b"d"[..], &b"e"[..],
/// ]);
/// ```
///
/// # Example: more cases
///
/// Basic usage:
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r" ").unwrap();
/// let hay = b"Mary had a little lamb";
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(got, vec![
/// &b"Mary"[..], &b"had"[..], &b"a"[..], &b"little"[..], &b"lamb"[..],
/// ]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = b"";
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(got, vec![&b""[..]]);
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = b"lionXXtigerXleopard";
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(got, vec![
/// &b"lion"[..], &b""[..], &b"tiger"[..], &b"leopard"[..],
/// ]);
///
/// let re = Regex::new(r"::").unwrap();
/// let hay = b"lion::tiger::leopard";
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(got, vec![&b"lion"[..], &b"tiger"[..], &b"leopard"[..]]);
/// ```
///
/// If a haystack contains multiple contiguous matches, you will end up
/// with empty spans yielded by the iterator:
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"X").unwrap();
/// let hay = b"XXXXaXXbXc";
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(got, vec![
/// &b""[..], &b""[..], &b""[..], &b""[..],
/// &b"a"[..], &b""[..], &b"b"[..], &b"c"[..],
/// ]);
///
/// let re = Regex::new(r"/").unwrap();
/// let hay = b"(///)";
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(got, vec![&b"("[..], &b""[..], &b""[..], &b")"[..]]);
/// ```
///
/// Separators at the start or end of a haystack are neighbored by empty
/// substring.
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"0").unwrap();
/// let hay = b"010";
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(got, vec![&b""[..], &b"1"[..], &b""[..]]);
/// ```
///
/// When the regex can match the empty string, it splits at every byte
/// position in the haystack. This includes between all UTF-8 code units.
/// (The top-level [`Regex::split`](crate::Regex::split) will only split
/// at valid UTF-8 boundaries.)
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r"").unwrap();
/// let hay = "☃".as_bytes();
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(got, vec![
/// &[][..], &[b'\xE2'][..], &[b'\x98'][..], &[b'\x83'][..], &[][..],
/// ]);
/// ```
///
/// Contiguous separators (commonly shows up with whitespace), can lead to
/// possibly surprising behavior. For example, this code is correct:
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r" ").unwrap();
/// let hay = b" a b c";
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// assert_eq!(got, vec![
/// &b""[..], &b""[..], &b""[..], &b""[..],
/// &b"a"[..], &b""[..], &b"b"[..], &b"c"[..],
/// ]);
/// ```
///
/// It does *not* give you `["a", "b", "c"]`. For that behavior, you'd want
/// to match contiguous space characters:
///
/// ```
/// use regex::bytes::Regex;
///
/// let re = Regex::new(r" +").unwrap();
/// let hay = b" a b c";
/// let got: Vec<&[u8]> = re.split(hay).collect();
/// // N.B. This does still include a leading empty span because ' +'
/// // matches at the beginning of the haystack.
/// assert_eq!(got, vec![&b""[..], &b"a"[..], &b"b"[..], &b"c"[..]]);
/// ```
#[inline]
/// Returns an iterator of non-overlapping matches in the given
/// stream. Matches correspond to the same matches as reported by
/// [`find_iter`](struct.AhoCorasick.html#method.find_iter).
///
/// The matches yielded by this iterator use absolute position offsets in
/// the stream given, where the first byte has index `0`. Matches are
/// yieled until the stream is exhausted.
///
/// Each item yielded by the iterator is an `io::Result<Match>`, where an
/// error is yielded if there was a problem reading from the reader given.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible.
///
/// Searching a stream requires that the automaton was built with
/// `MatchKind::Standard` semantics. If this automaton was constructed
/// with leftmost semantics, then this method will panic. To determine
/// whether this will panic at runtime, use the
/// [`AhoCorasick::supports_stream`](struct.AhoCorasick.html#method.supports_stream)
/// method.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Panics
///
/// This panics when `AhoCorasick::supports_stream` returns `false`.
/// That is, this panics when this automaton's match semantics are not
/// `MatchKind::Standard`. This restriction may be lifted in the future.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// # fn example() -> Result<(), ::std::io::Error> {
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns);
/// let mut matches = vec![];
/// for result in ac.stream_find_iter(haystack.as_bytes()) {
/// let mat = result?;
/// matches.push(mat.pattern());
/// }
/// assert_eq!(vec![2, 2, 2], matches);
/// # Ok(()) }; example().unwrap()
/// ```
pub fn stream_find_iter<'a, R: io::Read>(
/// Search for and replace all matches of this automaton in
/// the given reader, and write the replacements to the given
/// writer. Matches correspond to the same matches as reported by
/// [`AhoCorasick::try_find_iter`].
///
/// Replacements are determined by the index of the matching pattern. For
/// example, if the pattern with index `2` is found, then it is replaced by
/// `replace_with[2]`.
///
/// After all matches are replaced, the writer is _not_ flushed.
///
/// If there was a problem reading from the given reader or writing to the
/// given writer, then the corresponding `io::Error` is returned and all
/// replacement is stopped.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible. However,
/// callers may want to provide a buffered writer.
///
/// Note that there is currently no infallible version of this routine.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Panics
///
/// This panics when `replace_with.len()` does not equal
/// [`AhoCorasick::patterns_len`].
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this stream searching routine always does an unanchored search.
///
/// This also returns an error if the searcher does not support stream
/// searches. Only searchers built with [`MatchKind::Standard`] semantics
/// support stream searches.
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// let patterns = &["fox", "brown", "quick"];
/// let haystack = "The quick brown fox.";
/// let replace_with = &["sloth", "grey", "slow"];
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut result = vec![];
/// ac.try_stream_replace_all(
/// haystack.as_bytes(),
/// &mut result,
/// replace_with,
/// )?;
/// assert_eq!(b"The slow grey sloth.".to_vec(), result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "std")]
/// Returns an iterator of non-overlapping matches in the given
/// stream. Matches correspond to the same matches as reported by
/// [`AhoCorasick::try_find_iter`].
///
/// The matches yielded by this iterator use absolute position offsets in
/// the stream given, where the first byte has index `0`. Matches are
/// yieled until the stream is exhausted.
///
/// Each item yielded by the iterator is an `Result<Match,
/// std::io::Error>`, where an error is yielded if there was a problem
/// reading from the reader given.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible.
///
/// This is the fallible version of [`AhoCorasick::stream_find_iter`].
/// Note that both methods return iterators that produce `Result` values.
/// The difference is that this routine returns an error if _construction_
/// of the iterator failed. The `Result` values yield by the iterator
/// come from whether the given reader returns an error or not during the
/// search.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this stream searching routine always does an unanchored search.
///
/// This also returns an error if the searcher does not support stream
/// searches. Only searchers built with [`MatchKind::Standard`] semantics
/// support stream searches.
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut matches = vec![];
/// for result in ac.try_stream_find_iter(haystack.as_bytes())? {
/// let mat = result?;
/// matches.push(mat.pattern());
/// }
/// assert_eq!(vec![
/// PatternID::must(2),
/// PatternID::must(2),
/// PatternID::must(2),
/// ], matches);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "std")]
/// Search the given reader and replace all matches of this automaton
/// using the given closure. The result is written to the given
/// writer. Matches correspond to the same matches as reported by
/// [`AhoCorasick::try_find_iter`].
///
/// The closure accepts three parameters: the match found, the text of
/// the match and the writer with which to write the replaced text (if any).
///
/// After all matches are replaced, the writer is _not_ flushed.
///
/// If there was a problem reading from the given reader or writing to the
/// given writer, then the corresponding `io::Error` is returned and all
/// replacement is stopped.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible. However,
/// callers may want to provide a buffered writer.
///
/// Note that there is currently no infallible version of this routine.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Errors
///
/// This returns an error when this Aho-Corasick searcher does not support
/// the default `Input` configuration. More specifically, this occurs only
/// when the Aho-Corasick searcher does not support unanchored searches
/// since this stream searching routine always does an unanchored search.
///
/// This also returns an error if the searcher does not support stream
/// searches. Only searchers built with [`MatchKind::Standard`] semantics
/// support stream searches.
///
/// # Example: basic usage
///
/// ```
/// use std::io::Write;
/// use aho_corasick::AhoCorasick;
///
/// let patterns = &["fox", "brown", "quick"];
/// let haystack = "The quick brown fox.";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut result = vec![];
/// ac.try_stream_replace_all_with(
/// haystack.as_bytes(),
/// &mut result,
/// |mat, _, wtr| {
/// wtr.write_all(mat.pattern().as_usize().to_string().as_bytes())
/// },
/// )?;
/// assert_eq!(b"The 2 1 0.".to_vec(), result);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "std")]
/// Search for and replace all matches of this automaton in
/// the given reader, and write the replacements to the given
/// writer. Matches correspond to the same matches as reported by
/// [`find_iter`](struct.AhoCorasick.html#method.find_iter).
///
/// Replacements are determined by the index of the matching pattern.
/// For example, if the pattern with index `2` is found, then it is
/// replaced by `replace_with[2]`.
///
/// After all matches are replaced, the writer is _not_ flushed.
///
/// If there was a problem reading from the given reader or writing to the
/// given writer, then the corresponding `io::Error` is returned and all
/// replacement is stopped.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible. However,
/// callers may want to provide a buffered writer.
///
/// Searching a stream requires that the automaton was built with
/// `MatchKind::Standard` semantics. If this automaton was constructed
/// with leftmost semantics, then this method will panic. To determine
/// whether this will panic at runtime, use the
/// [`AhoCorasick::supports_stream`](struct.AhoCorasick.html#method.supports_stream)
/// method.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Panics
///
/// This panics when `AhoCorasick::supports_stream` returns `false`.
/// That is, this panics when this automaton's match semantics are not
/// `MatchKind::Standard`. This restriction may be lifted in the future.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use aho_corasick::AhoCorasick;
///
/// # fn example() -> Result<(), ::std::io::Error> {
/// let patterns = &["fox", "brown", "quick"];
/// let haystack = "The quick brown fox.";
/// let replace_with = &["sloth", "grey", "slow"];
///
/// let ac = AhoCorasick::new(patterns);
/// let mut result = vec![];
/// ac.stream_replace_all(haystack.as_bytes(), &mut result, replace_with)?;
/// assert_eq!(b"The slow grey sloth.".to_vec(), result);
/// # Ok(()) }; example().unwrap()
/// ```
pub fn stream_replace_all<R, W, B>(
/// Returns an iterator of non-overlapping matches in the given
/// stream. Matches correspond to the same matches as reported by
/// [`AhoCorasick::find_iter`].
///
/// The matches yielded by this iterator use absolute position offsets in
/// the stream given, where the first byte has index `0`. Matches are
/// yieled until the stream is exhausted.
///
/// Each item yielded by the iterator is an `Result<Match,
/// std::io::Error>`, where an error is yielded if there was a problem
/// reading from the reader given.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible.
///
/// This is the infallible version of
/// [`AhoCorasick::try_stream_find_iter`]. Note that both methods return
/// iterators that produce `Result` values. The difference is that this
/// routine panics if _construction_ of the iterator failed. The `Result`
/// values yield by the iterator come from whether the given reader returns
/// an error or not during the search.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Panics
///
/// This panics when [`AhoCorasick::try_stream_find_iter`] would return
/// an error. For example, when the Aho-Corasick searcher doesn't support
/// stream searches. (Only searchers built with [`MatchKind::Standard`]
/// semantics support stream searches.)
///
/// # Example: basic usage
///
/// ```
/// use aho_corasick::{AhoCorasick, PatternID};
///
/// let patterns = &["append", "appendage", "app"];
/// let haystack = "append the app to the appendage";
///
/// let ac = AhoCorasick::new(patterns).unwrap();
/// let mut matches = vec![];
/// for result in ac.stream_find_iter(haystack.as_bytes()) {
/// let mat = result?;
/// matches.push(mat.pattern());
/// }
/// assert_eq!(vec![
/// PatternID::must(2),
/// PatternID::must(2),
/// PatternID::must(2),
/// ], matches);
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[cfg(feature = "std")]
/// Search the given reader and replace all matches of this automaton
/// using the given closure. The result is written to the given
/// writer. Matches correspond to the same matches as reported by
/// [`find_iter`](struct.AhoCorasick.html#method.find_iter).
///
/// The closure accepts three parameters: the match found, the text of
/// the match and the writer with which to write the replaced text (if any).
///
/// After all matches are replaced, the writer is _not_ flushed.
///
/// If there was a problem reading from the given reader or writing to the
/// given writer, then the corresponding `io::Error` is returned and all
/// replacement is stopped.
///
/// When searching a stream, an internal buffer is used. Therefore, callers
/// should avoiding providing a buffered reader, if possible. However,
/// callers may want to provide a buffered writer.
///
/// Searching a stream requires that the automaton was built with
/// `MatchKind::Standard` semantics. If this automaton was constructed
/// with leftmost semantics, then this method will panic. To determine
/// whether this will panic at runtime, use the
/// [`AhoCorasick::supports_stream`](struct.AhoCorasick.html#method.supports_stream)
/// method.
///
/// # Memory usage
///
/// In general, searching streams will use a constant amount of memory for
/// its internal buffer. The one requirement is that the internal buffer
/// must be at least the size of the longest possible match. In most use
/// cases, the default buffer size will be much larger than any individual
/// match.
///
/// # Panics
///
/// This panics when `AhoCorasick::supports_stream` returns `false`.
/// That is, this panics when this automaton's match semantics are not
/// `MatchKind::Standard`. This restriction may be lifted in the future.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::io::Write;
/// use aho_corasick::AhoCorasick;
///
/// # fn example() -> Result<(), ::std::io::Error> {
/// let patterns = &["fox", "brown", "quick"];
/// let haystack = "The quick brown fox.";
///
/// let ac = AhoCorasick::new(patterns);
/// let mut result = vec![];
/// ac.stream_replace_all_with(
/// haystack.as_bytes(),
/// &mut result,
/// |mat, _, wtr| {
/// wtr.write_all(mat.pattern().to_string().as_bytes())
/// },
/// )?;
/// assert_eq!(b"The 2 1 0.".to_vec(), result);
/// # Ok(()) }; example().unwrap()
/// ```
pub fn stream_replace_all_with<R, W, F>(
/// Sets the working directory for the child process.
///
/// # Platform-specific behavior
///
/// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
/// whether it should be interpreted relative to the parent's working
/// directory or relative to `current_dir`. The behavior in this case is
/// platform specific and unstable, and it's recommended to use
/// [`canonicalize`] to get an absolute program path instead.
///
/// [`canonicalize`]: crate::fs::canonicalize()
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// # async fn test() { // allow using await
/// use tokio::process::Command;
///
/// let output = Command::new("ls")
/// .current_dir("/bin")
/// .output().await.unwrap();
/// # }
/// ```
pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
/// Sets the working directory for the child process.
///
/// # Platform-specific behavior
///
/// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
/// whether it should be interpreted relative to the parent's working
/// directory or relative to `current_dir`. The behavior in this case is
/// platform specific and unstable, and it's recommended to use
/// [`canonicalize`] to get an absolute program path instead.
///
/// [`canonicalize`]: crate::fs::canonicalize()
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// # async fn test() { // allow using await
/// use tokio::process::Command;
///
/// let output = Command::new("ls")
/// .current_dir("/bin")
/// .output().await.unwrap();
/// # }
/// ```
pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
/// Returns the file type for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a
/// symlink.
///
/// # Platform-specific behavior
///
/// On Windows and most Unix platforms this function is free (no extra
/// system calls needed), but some Unix platforms may require the equivalent
/// call to `symlink_metadata` to learn about the target file type.
///
/// # Examples
///
/// ```
/// use tokio::fs;
///
/// # async fn dox() -> std::io::Result<()> {
/// let mut entries = fs::read_dir(".").await?;
///
/// while let Some(entry) = entries.next_entry().await? {
/// if let Ok(file_type) = entry.file_type().await {
/// // Now let's show our entry's file type!
/// println!("{:?}: {:?}", entry.path(), file_type);
/// } else {
/// println!("Couldn't get file type for {:?}", entry.path());
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn file_type(&self) -> io::Result<FileType> {
/// Shuts down the read, write, or both halves of this connection.
///
/// This function will cause all pending and future I/O on the specified
/// portions to return immediately with an appropriate value (see the
/// documentation of [`Shutdown`]).
///
/// # Platform-specific behavior
///
/// Calling this function multiple times may result in different behavior,
/// depending on the operating system. On Linux, the second call will
/// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
/// This may change in the future.
///
/// # Examples
///
/// ```no_run
/// use std::net::{Shutdown, TcpStream};
///
/// let stream = TcpStream::connect("127.0.0.1:8080")
/// .expect("Couldn't connect to the server...");
/// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// Sets the write timeout to the timeout specified.
///
/// If the value specified is [`None`], then [`write`] calls will block
/// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
/// passed to this method.
///
/// # Platform-specific behavior
///
/// Platforms may return a different error code whenever a write times out
/// as a result of setting this option. For example Unix typically returns
/// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
///
/// [`write`]: io::Write::write
/// [`WouldBlock`]: io::ErrorKind::WouldBlock
/// [`TimedOut`]: io::ErrorKind::TimedOut
///
/// # Examples
///
/// ```no_run
/// use std::net::UdpSocket;
///
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
/// socket.set_write_timeout(None).expect("set_write_timeout call failed");
/// ```
///
/// An [`Err`] is returned if the zero [`Duration`] is passed to this
/// method:
///
/// ```no_run
/// use std::io;
/// use std::net::UdpSocket;
/// use std::time::Duration;
///
/// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
/// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
/// let err = result.unwrap_err();
/// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
/// ```
#[stable(feature = "socket_timeout", since = "1.4.0")]
/// Returns the read timeout of this socket.
///
/// If the timeout is [`None`], then [`read`] calls will block indefinitely.
///
/// # Platform-specific behavior
///
/// Some platforms do not provide access to the current timeout.
///
/// [`read`]: Read::read
///
/// # Examples
///
/// ```no_run
/// use std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080")
/// .expect("Couldn't connect to the server...");
/// stream.set_read_timeout(None).expect("set_read_timeout call failed");
/// assert_eq!(stream.read_timeout().unwrap(), None);
/// ```
#[stable(feature = "socket_timeout", since = "1.4.0")]
/// Returns the file type for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a
/// symlink.
///
/// # Platform-specific behavior
///
/// On Windows and most Unix platforms this function is free (no extra
/// system calls needed), but some Unix platforms may require the equivalent
/// call to `symlink_metadata` to learn about the target file type.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
/// for entry in entries {
/// if let Ok(entry) = entry {
/// // Here, `entry` is a `DirEntry`.
/// if let Ok(file_type) = entry.file_type() {
/// // Now let's show our entry's file type!
/// println!("{}: {:?}", entry.path(), file_type);
/// } else {
/// println!("Couldn't get file type for {}", entry.path());
/// }
/// }
/// }
/// }
/// ```
#[inline]
/// Converts this `Client` into a helper thread to deal with a blocking
/// `acquire` function a little more easily.
///
/// The fact that the `acquire` function on `Client` blocks isn't always
/// the easiest to work with. Typically you're using a jobserver to
/// manage running other events in parallel! This means that you need to
/// either (a) wait for an existing job to finish or (b) wait for a
/// new token to become available.
///
/// Unfortunately the blocking in `acquire` happens at the implementation
/// layer of jobservers. On Unix this requires a blocking call to `read`
/// and on Windows this requires one of the `WaitFor*` functions. Both
/// of these situations aren't the easiest to deal with:
///
/// * On Unix there's basically only one way to wake up a `read` early, and
/// that's through a signal. This is what the `make` implementation
/// itself uses, relying on `SIGCHLD` to wake up a blocking acquisition
/// of a new job token. Unfortunately nonblocking I/O is not an option
/// here, so it means that "waiting for one of two events" means that
/// the latter event must generate a signal! This is not always the case
/// on unix for all jobservers.
///
/// * On Windows you'd have to basically use the `WaitForMultipleObjects`
/// which means that you've got to canonicalize all your event sources
/// into a `HANDLE` which also isn't the easiest thing to do
/// unfortunately.
///
/// This function essentially attempts to ease these limitations by
/// converting this `Client` into a helper thread spawned into this
/// process. The application can then request that the helper thread
/// acquires tokens and the provided closure will be invoked for each token
/// acquired.
///
/// The intention is that this function can be used to translate the event
/// of a token acquisition into an arbitrary user-defined event.
///
/// # Arguments
///
/// This function will consume the `Client` provided to be transferred to
/// the helper thread that is spawned. Additionally a closure `f` is
/// provided to be invoked whenever a token is acquired.
///
/// This closure is only invoked after calls to
/// `HelperThread::request_token` have been made and a token itself has
/// been acquired. If an error happens while acquiring the token then
/// an error will be yielded to the closure as well.
///
/// # Return Value
///
/// This function will return an instance of the `HelperThread` structure
/// which is used to manage the helper thread associated with this client.
/// Through the `HelperThread` you'll request that tokens are acquired.
/// When acquired, the closure provided here is invoked.
///
/// When the `HelperThread` structure is returned it will be gracefully
/// torn down, and the calling thread will be blocked until the thread is
/// torn down (which should be prompt).
///
/// # Errors
///
/// This function may fail due to creation of the helper thread or
/// auxiliary I/O objects to manage the helper thread. In any of these
/// situations the error is propagated upwards.
///
/// # Platform-specific behavior
///
/// On Windows this function behaves pretty normally as expected, but on
/// Unix the implementation is... a little heinous. As mentioned above
/// we're forced into blocking I/O for token acquisition, namely a blocking
/// call to `read`. We must be able to unblock this, however, to tear down
/// the helper thread gracefully!
///
/// Essentially what happens is that we'll send a signal to the helper
/// thread spawned and rely on `EINTR` being returned to wake up the helper
/// thread. This involves installing a global `SIGUSR1` handler that does
/// nothing along with sending signals to that thread. This may cause
/// odd behavior in some applications, so it's recommended to review and
/// test thoroughly before using this.
pub fn into_helper_thread<F>(self, f: F) -> io::Result<HelperThread>
/// Changes the permissions on the underlying file.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `fchmod` function on Unix and
/// the `SetFileInformationByHandle` function on Windows. Note that, this
/// [may change in the future][changes].
///
/// [changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior
///
/// # Errors
///
/// This function will return an error if the user lacks permission change
/// attributes on the underlying file. It may also return an error in other
/// os-specific unspecified cases.
///
/// # Examples
///
/// ```no_run
/// use tokio::fs::File;
///
/// # async fn dox() -> std::io::Result<()> {
/// let file = File::open("foo.txt").await?;
/// let mut perms = file.metadata().await?.permissions();
/// perms.set_readonly(true);
/// file.set_permissions(perms).await?;
/// # Ok(())
/// # }
/// ```
pub async fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
/// Constructs a new `Command` for launching the program at
/// path `program`, with the following default configuration:
///
/// * No arguments to the program
/// * Inherit the current process's environment
/// * Inherit the current process's working directory
/// * Inherit stdin/stdout/stderr for [`spawn`] or [`status`], but create pipes for [`output`]
///
/// [`spawn`]: Self::spawn
/// [`status`]: Self::status
/// [`output`]: Self::output
///
/// Builder methods are provided to change these defaults and
/// otherwise configure the process.
///
/// If `program` is not an absolute path, the `PATH` will be searched in
/// an OS-defined way.
///
/// The search path to be used may be controlled by setting the
/// `PATH` environment variable on the Command,
/// but this has some implementation limitations on Windows
/// (see issue #37519).
///
/// # Platform-specific behavior
///
/// Note on Windows: For executable files with the .exe extension,
/// it can be omitted when specifying the program for this Command.
/// However, if the file has a different extension,
/// a filename including the extension needs to be provided,
/// otherwise the file won't be found.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use std::process::Command;
///
/// Command::new("sh")
/// .spawn()
/// .expect("sh command failed to start");
/// ```
#[stable(feature = "process", since = "1.0.0")]
/// Returns `true` if the descriptor/handle refers to a terminal/tty.
///
/// On platforms where Rust does not know how to detect a terminal yet, this will return
/// `false`. This will also return `false` if an unexpected error occurred, such as from
/// passing an invalid file descriptor.
///
/// # Platform-specific behavior
///
/// On Windows, in addition to detecting consoles, this currently uses some heuristics to
/// detect older msys/cygwin/mingw pseudo-terminals based on device name: devices with names
/// starting with `msys-` or `cygwin-` and ending in `-pty` will be considered terminals.
/// Note that this [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
#[stable(feature = "is_terminal", since = "1.70.0")]
/// Returns the file type for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a
/// symlink.
///
/// # Platform-specific behavior
///
/// On Windows and most Unix platforms this function is free (no extra
/// system calls needed), but some Unix platforms may require the equivalent
/// call to `symlink_metadata` to learn about the target file type.
///
/// # Examples
///
/// ```
/// use std::fs;
///
/// if let Ok(entries) = fs::read_dir(".") {
/// for entry in entries {
/// if let Ok(entry) = entry {
/// // Here, `entry` is a `DirEntry`.
/// if let Ok(file_type) = entry.file_type() {
/// // Now let's show our entry's file type!
/// println!("{:?}: {:?}", entry.path(), file_type);
/// } else {
/// println!("Couldn't get file type for {:?}", entry.path());
/// }
/// }
/// }
/// }
/// ```
#[stable(feature = "dir_entry_ext", since = "1.1.0")]
/// Changes the permissions on the underlying file.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `fchmod` function on Unix and
/// the `SetFileInformationByHandle` function on Windows. Note that, this
/// [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
///
/// # Errors
///
/// This function will return an error if the user lacks permission change
/// attributes on the underlying file. It may also return an error in other
/// os-specific unspecified cases.
///
/// # Examples
///
/// ```no_run
/// fn main() -> std::io::Result<()> {
/// use std::fs::File;
///
/// let file = File::open("foo.txt")?;
/// let mut perms = file.metadata()?.permissions();
/// perms.set_readonly(true);
/// file.set_permissions(perms)?;
/// Ok(())
/// }
/// ```
///
/// Note that this method alters the permissions of the underlying file,
/// even though it takes `&self` rather than `&mut self`.
#[doc(alias = "fchmod", alias = "SetFileInformationByHandle")]
/// Changes the permissions on the underlying file.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `fchmod` function on Unix and
/// the `SetFileInformationByHandle` function on Windows. Note that, this
/// [may change in the future][changes].
///
/// [changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior
///
/// # Errors
///
/// This function will return an error if the user lacks permission change
/// attributes on the underlying file. It may also return an error in other
/// os-specific unspecified cases.
///
/// # Examples
///
/// ```no_run
/// use tokio::fs::File;
///
/// # async fn dox() -> std::io::Result<()> {
/// let file = File::open("foo.txt").await?;
/// let mut perms = file.metadata().await?.permissions();
/// perms.set_readonly(true);
/// file.set_permissions(perms).await?;
/// # Ok(())
/// # }
/// ```
pub async fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
/// Returns the metadata for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a symlink. To traverse
/// symlinks use [`Utf8Path::metadata`] or [`fs::File::metadata`].
///
/// # Platform-specific behavior
///
/// On Windows this function is cheap to call (no extra system calls
/// needed), but on Unix platforms this function is the equivalent of
/// calling `symlink_metadata` on the path.
///
/// # Examples
///
/// ```
/// use camino::Utf8Path;
///
/// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
/// for entry in entries {
/// if let Ok(entry) = entry {
/// // Here, `entry` is a `Utf8DirEntry`.
/// if let Ok(metadata) = entry.metadata() {
/// // Now let's show our entry's permissions!
/// println!("{}: {:?}", entry.path(), metadata.permissions());
/// } else {
/// println!("Couldn't get metadata for {}", entry.path());
/// }
/// }
/// }
/// }
/// ```
#[inline]
/// Sets the working directory for the child process.
///
/// # Platform-specific behavior
///
/// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
/// whether it should be interpreted relative to the parent's working
/// directory or relative to `current_dir`. The behavior in this case is
/// platform specific and unstable, and it's recommended to use
/// [`canonicalize`] to get an absolute program path instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use std::process::Command;
///
/// Command::new("ls")
/// .current_dir("/bin")
/// .spawn()
/// .expect("ls command failed to start");
/// ```
///
/// [`canonicalize`]: crate::fs::canonicalize
#[stable(feature = "process", since = "1.0.0")]
/// Returns the metadata for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a
/// symlink.
///
/// # Platform-specific behavior
///
/// On Windows this function is cheap to call (no extra system calls
/// needed), but on Unix platforms this function is the equivalent of
/// calling `symlink_metadata` on the path.
///
/// # Examples
///
/// ```
/// use tokio::fs;
///
/// # async fn dox() -> std::io::Result<()> {
/// let mut entries = fs::read_dir(".").await?;
///
/// while let Some(entry) = entries.next_entry().await? {
/// if let Ok(metadata) = entry.metadata().await {
/// // Now let's show our entry's permissions!
/// println!("{:?}: {:?}", entry.path(), metadata.permissions());
/// } else {
/// println!("Couldn't get file type for {:?}", entry.path());
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn metadata(&self) -> io::Result<Metadata> {
/// Sets the read timeout to the timeout specified.
///
/// If the value specified is [`None`], then [`read`] calls will block
/// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
/// passed to this method.
///
/// # Platform-specific behavior
///
/// Platforms may return a different error code whenever a read times out as
/// a result of setting this option. For example Unix typically returns an
/// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
///
/// [`read`]: Read::read
/// [`WouldBlock`]: io::ErrorKind::WouldBlock
/// [`TimedOut`]: io::ErrorKind::TimedOut
///
/// # Examples
///
/// ```no_run
/// use std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080")
/// .expect("Couldn't connect to the server...");
/// stream.set_read_timeout(None).expect("set_read_timeout call failed");
/// ```
///
/// An [`Err`] is returned if the zero [`Duration`] is passed to this
/// method:
///
/// ```no_run
/// use std::io;
/// use std::net::TcpStream;
/// use std::time::Duration;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
/// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
/// let err = result.unwrap_err();
/// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
/// ```
#[stable(feature = "socket_timeout", since = "1.4.0")]
/// Sets the working directory for the child process.
///
/// # Platform-specific behavior
///
/// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
/// whether it should be interpreted relative to the parent's working
/// directory or relative to `current_dir`. The behavior in this case is
/// platform specific and unstable, and it's recommended to use
/// [`canonicalize`] to get an absolute program path instead.
///
/// [`canonicalize`]: crate::fs::canonicalize()
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use tokio::process::Command;
///
/// let command = Command::new("ls")
/// .current_dir("/bin");
/// ```
pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
/// Returns the metadata for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a
/// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
///
/// [`fs::metadata`]: metadata
/// [`fs::File::metadata`]: File::metadata
///
/// # Platform-specific behavior
///
/// On Windows this function is cheap to call (no extra system calls
/// needed), but on Unix platforms this function is the equivalent of
/// calling `symlink_metadata` on the path.
///
/// # Examples
///
/// ```
/// use std::fs;
///
/// if let Ok(entries) = fs::read_dir(".") {
/// for entry in entries {
/// if let Ok(entry) = entry {
/// // Here, `entry` is a `DirEntry`.
/// if let Ok(metadata) = entry.metadata() {
/// // Now let's show our entry's permissions!
/// println!("{:?}: {:?}", entry.path(), metadata.permissions());
/// } else {
/// println!("Couldn't get metadata for {:?}", entry.path());
/// }
/// }
/// }
/// }
/// ```
#[stable(feature = "dir_entry_ext", since = "1.1.0")]
/// Returns the metadata for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a
/// symlink.
///
/// # Platform-specific behavior
///
/// On Windows this function is cheap to call (no extra system calls
/// needed), but on Unix platforms this function is the equivalent of
/// calling `symlink_metadata` on the path.
///
/// # Examples
///
/// ```
/// use tokio::fs;
///
/// # async fn dox() -> std::io::Result<()> {
/// let mut entries = fs::read_dir(".").await?;
///
/// while let Some(entry) = entries.next_entry().await? {
/// if let Ok(metadata) = entry.metadata().await {
/// // Now let's show our entry's permissions!
/// println!("{:?}: {:?}", entry.path(), metadata.permissions());
/// } else {
/// println!("Couldn't get file type for {:?}", entry.path());
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn metadata(&self) -> io::Result<Metadata> {
/// Sets the working directory for the child process.
///
/// # Platform-specific behavior
///
/// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
/// whether it should be interpreted relative to the parent's working
/// directory or relative to `current_dir`. The behavior in this case is
/// platform specific and unstable, and it's recommended to use
/// [`canonicalize`] to get an absolute program path instead.
///
/// [`canonicalize`]: crate::fs::canonicalize()
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use tokio::process::Command;
///
/// let command = Command::new("ls")
/// .current_dir("/bin");
/// ```
pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
/// Sets the read timeout to the timeout specified.
///
/// If the value specified is [`None`], then [`read`] calls will block
/// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
/// passed to this method.
///
/// # Platform-specific behavior
///
/// Platforms may return a different error code whenever a read times out as
/// a result of setting this option. For example Unix typically returns an
/// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
///
/// [`read`]: io::Read::read
/// [`WouldBlock`]: io::ErrorKind::WouldBlock
/// [`TimedOut`]: io::ErrorKind::TimedOut
///
/// # Examples
///
/// ```no_run
/// use std::net::UdpSocket;
///
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
/// socket.set_read_timeout(None).expect("set_read_timeout call failed");
/// ```
///
/// An [`Err`] is returned if the zero [`Duration`] is passed to this
/// method:
///
/// ```no_run
/// use std::io;
/// use std::net::UdpSocket;
/// use std::time::Duration;
///
/// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
/// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
/// let err = result.unwrap_err();
/// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
/// ```
#[stable(feature = "socket_timeout", since = "1.4.0")]
/// Changes the timestamps of the underlying file.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `futimens` function on Unix (falling back to
/// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
/// [may change in the future][changes].
///
/// [changes]: io#platform-specific-behavior
///
/// # Errors
///
/// This function will return an error if the user lacks permission to change timestamps on the
/// underlying file. It may also return an error in other os-specific unspecified cases.
///
/// This function may return an error if the operating system lacks support to change one or
/// more of the timestamps set in the `FileTimes` structure.
///
/// # Examples
///
/// ```no_run
/// fn main() -> std::io::Result<()> {
/// use std::fs::{self, File, FileTimes};
///
/// let src = fs::metadata("src")?;
/// let dest = File::options().write(true).open("dest")?;
/// let times = FileTimes::new()
/// .set_accessed(src.accessed()?)
/// .set_modified(src.modified()?);
/// dest.set_times(times)?;
/// Ok(())
/// }
/// ```
#[stable(feature = "file_set_times", since = "1.75.0")]
/// Returns the metadata for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a
/// symlink.
///
/// # Platform-specific behavior
///
/// On Windows this function is cheap to call (no extra system calls
/// needed), but on Unix platforms this function is the equivalent of
/// calling `symlink_metadata` on the path.
///
/// # Examples
///
/// ```
/// use tokio::fs;
///
/// # async fn dox() -> std::io::Result<()> {
/// let mut entries = fs::read_dir(".").await?;
///
/// while let Some(entry) = entries.next_entry().await? {
/// if let Ok(metadata) = entry.metadata().await {
/// // Now let's show our entry's permissions!
/// println!("{:?}: {:?}", entry.path(), metadata.permissions());
/// } else {
/// println!("Couldn't get file type for {:?}", entry.path());
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn metadata(&self) -> io::Result<Metadata> {
/// Changes the permissions on the underlying file.
///
/// # Platform-specific behavior
///
/// This function currently corresponds to the `fchmod` function on Unix and
/// the `SetFileInformationByHandle` function on Windows. Note that, this
/// [may change in the future][changes].
///
/// [changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior
///
/// # Errors
///
/// This function will return an error if the user lacks permission change
/// attributes on the underlying file. It may also return an error in other
/// os-specific unspecified cases.
///
/// # Examples
///
/// ```no_run
/// use tokio::fs::File;
///
/// # async fn dox() -> std::io::Result<()> {
/// let file = File::open("foo.txt").await?;
/// let mut perms = file.metadata().await?.permissions();
/// perms.set_readonly(true);
/// file.set_permissions(perms).await?;
/// # Ok(())
/// # }
/// ```
pub async fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
/// Converts this `Client` into a helper thread to deal with a blocking
/// `acquire` function a little more easily.
///
/// The fact that the `acquire` function on `Client` blocks isn't always
/// the easiest to work with. Typically you're using a jobserver to
/// manage running other events in parallel! This means that you need to
/// either (a) wait for an existing job to finish or (b) wait for a
/// new token to become available.
///
/// Unfortunately the blocking in `acquire` happens at the implementation
/// layer of jobservers. On Unix this requires a blocking call to `read`
/// and on Windows this requires one of the `WaitFor*` functions. Both
/// of these situations aren't the easiest to deal with:
///
/// * On Unix there's basically only one way to wake up a `read` early, and
/// that's through a signal. This is what the `make` implementation
/// itself uses, relying on `SIGCHLD` to wake up a blocking acquisition
/// of a new job token. Unfortunately nonblocking I/O is not an option
/// here, so it means that "waiting for one of two events" means that
/// the latter event must generate a signal! This is not always the case
/// on unix for all jobservers.
///
/// * On Windows you'd have to basically use the `WaitForMultipleObjects`
/// which means that you've got to canonicalize all your event sources
/// into a `HANDLE` which also isn't the easiest thing to do
/// unfortunately.
///
/// This function essentially attempts to ease these limitations by
/// converting this `Client` into a helper thread spawned into this
/// process. The application can then request that the helper thread
/// acquires tokens and the provided closure will be invoked for each token
/// acquired.
///
/// The intention is that this function can be used to translate the event
/// of a token acquisition into an arbitrary user-defined event.
///
/// # Arguments
///
/// This function will consume the `Client` provided to be transferred to
/// the helper thread that is spawned. Additionally a closure `f` is
/// provided to be invoked whenever a token is acquired.
///
/// This closure is only invoked after calls to
/// `HelperThread::request_token` have been made and a token itself has
/// been acquired. If an error happens while acquiring the token then
/// an error will be yielded to the closure as well.
///
/// # Return Value
///
/// This function will return an instance of the `HelperThread` structure
/// which is used to manage the helper thread associated with this client.
/// Through the `HelperThread` you'll request that tokens are acquired.
/// When acquired, the closure provided here is invoked.
///
/// When the `HelperThread` structure is returned it will be gracefully
/// torn down, and the calling thread will be blocked until the thread is
/// torn down (which should be prompt).
///
/// # Errors
///
/// This function may fail due to creation of the helper thread or
/// auxiliary I/O objects to manage the helper thread. In any of these
/// situations the error is propagated upwards.
///
/// # Platform-specific behavior
///
/// On Windows this function behaves pretty normally as expected, but on
/// Unix the implementation is... a little heinous. As mentioned above
/// we're forced into blocking I/O for token acquisition, namely a blocking
/// call to `read`. We must be able to unblock this, however, to tear down
/// the helper thread gracefully!
///
/// Essentially what happens is that we'll send a signal to the helper
/// thread spawned and rely on `EINTR` being returned to wake up the helper
/// thread. This involves installing a global `SIGUSR1` handler that does
/// nothing along with sending signals to that thread. This may cause
/// odd behavior in some applications, so it's recommended to review and
/// test thoroughly before using this.
pub fn into_helper_thread<F>(self, f: F) -> io::Result<HelperThread>
/// Returns the file type for the file that this entry points at.
///
/// This function will not traverse symlinks if this entry points at a
/// symlink.
///
/// # Platform-specific behavior
///
/// On Windows and most Unix platforms this function is free (no extra
/// system calls needed), but some Unix platforms may require the equivalent
/// call to `symlink_metadata` to learn about the target file type.
///
/// # Examples
///
/// ```
/// use tokio::fs;
///
/// # async fn dox() -> std::io::Result<()> {
/// let mut entries = fs::read_dir(".").await?;
///
/// while let Some(entry) = entries.next_entry().await? {
/// if let Ok(file_type) = entry.file_type().await {
/// // Now let's show our entry's file type!
/// println!("{:?}: {:?}", entry.path(), file_type);
/// } else {
/// println!("Couldn't get file type for {:?}", entry.path());
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn file_type(&self) -> io::Result<FileType> {
/// Forks a parse stream so that parsing tokens out of either the original
/// or the fork does not advance the position of the other.
///
/// # Performance
///
/// Forking a parse stream is a cheap fixed amount of work and does not
/// involve copying token buffers. Where you might hit performance problems
/// is if your macro ends up parsing a large amount of content more than
/// once.
///
/// ```
/// # use syn::{Expr, Result};
/// # use syn::parse::ParseStream;
/// #
/// # fn bad(input: ParseStream) -> Result<Expr> {
/// // Do not do this.
/// if input.fork().parse::<Expr>().is_ok() {
/// return input.parse::<Expr>();
/// }
/// # unimplemented!()
/// # }
/// ```
///
/// As a rule, avoid parsing an unbounded amount of tokens out of a forked
/// parse stream. Only use a fork when the amount of work performed against
/// the fork is small and bounded.
///
/// When complex speculative parsing against the forked stream is
/// unavoidable, use [`parse::discouraged::Speculative`] to advance the
/// original stream once the fork's parse is determined to have been
/// successful.
///
/// For a lower level way to perform speculative parsing at the token level,
/// consider using [`ParseStream::step`] instead.
///
/// [`parse::discouraged::Speculative`]: discouraged::Speculative
/// [`ParseStream::step`]: ParseBuffer::step
///
/// # Example
///
/// The parse implementation shown here parses possibly restricted `pub`
/// visibilities.
///
/// - `pub`
/// - `pub(crate)`
/// - `pub(self)`
/// - `pub(super)`
/// - `pub(in some::path)`
///
/// To handle the case of visibilities inside of tuple structs, the parser
/// needs to distinguish parentheses that specify visibility restrictions
/// from parentheses that form part of a tuple type.
///
/// ```
/// # struct A;
/// # struct B;
/// # struct C;
/// #
/// struct S(pub(crate) A, pub (B, C));
/// ```
///
/// In this example input the first tuple struct element of `S` has
/// `pub(crate)` visibility while the second tuple struct element has `pub`
/// visibility; the parentheses around `(B, C)` are part of the type rather
/// than part of a visibility restriction.
///
/// The parser uses a forked parse stream to check the first token inside of
/// parentheses after the `pub` keyword. This is a small bounded amount of
/// work performed against the forked parse stream.
///
/// ```
/// use syn::{parenthesized, token, Ident, Path, Result, Token};
/// use syn::ext::IdentExt;
/// use syn::parse::{Parse, ParseStream};
///
/// struct PubVisibility {
/// pub_token: Token![pub],
/// restricted: Option<Restricted>,
/// }
///
/// struct Restricted {
/// paren_token: token::Paren,
/// in_token: Option<Token![in]>,
/// path: Path,
/// }
///
/// impl Parse for PubVisibility {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let pub_token: Token![pub] = input.parse()?;
///
/// if input.peek(token::Paren) {
/// let ahead = input.fork();
/// let mut content;
/// parenthesized!(content in ahead);
///
/// if content.peek(Token![crate])
/// || content.peek(Token![self])
/// || content.peek(Token![super])
/// {
/// return Ok(PubVisibility {
/// pub_token,
/// restricted: Some(Restricted {
/// paren_token: parenthesized!(content in input),
/// in_token: None,
/// path: Path::from(content.call(Ident::parse_any)?),
/// }),
/// });
/// } else if content.peek(Token![in]) {
/// return Ok(PubVisibility {
/// pub_token,
/// restricted: Some(Restricted {
/// paren_token: parenthesized!(content in input),
/// in_token: Some(content.parse()?),
/// path: content.call(Path::parse_mod_style)?,
/// }),
/// });
/// }
/// }
///
/// Ok(PubVisibility {
/// pub_token,
/// restricted: None,
/// })
/// }
/// }
/// ```
pub fn fork(&self) -> Self {
/// Creates a consuming iterator visiting all the values in arbitrary order.
/// The map cannot be used after calling this.
/// The iterator element type is `V`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// let map = HashMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// let mut vec: Vec<i32> = map.into_values().collect();
/// // The `IntoValues` iterator produces values in arbitrary order, so
/// // the values must be sorted to test them against a sorted array.
/// vec.sort_unstable();
/// assert_eq!(vec, [1, 2, 3]);
/// ```
///
/// # Performance
///
/// In the current implementation, iterating over values takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[inline]
/// Follow a sequence of `path` components starting from this instance, and look them up one by one until the last component
/// is looked up and its tree entry is returned, while changing this instance to point to the last seen tree.
/// Note that if the lookup fails, it may be impossible to continue making lookups through this tree.
/// It's useful to have this function to be able to reuse the internal buffer of the tree.
///
/// # Performance Notes
///
/// Searching tree entries is currently done in sequence, which allows to the search to be allocation free. It would be possible
/// to reuse a vector and use a binary search instead, which might be able to improve performance over all.
/// However, a benchmark should be created first to have some data and see which trade-off to choose here.
///
pub fn peel_to_entry<I, P>(&mut self, path: I) -> Result<Option<Entry<'repo>>, find::existing::Error>
/// Return `true` if `id` exists in the object database.
///
/// # Performance
///
/// This method can be slow if the underlying [object database](crate::Repository::objects) has
/// an unsuitable [RefreshMode](gix_odb::store::RefreshMode) and `id` is not likely to exist.
/// Use [`repo.objects.refresh_never()`](gix_odb::store::Handle::refresh_never) to avoid expensive
/// IO-bound refreshes if an object wasn't found.
#[doc(alias = "exists", alias = "git2")]
/// Return a platform to see the changes needed to create other trees, for instance.
///
/// # Performance
///
/// It's highly recommended to set an object cache to avoid extracting the same object multiple times.
/// By default, similar to `git diff`, rename tracking will be enabled if it is not configured.
///
/// Note that if a clone with `--filter=blob=none` was created, rename tracking may fail as it might
/// try to access blobs to compute a similarity metric. Thus, it's more compatible to turn rewrite tracking off
/// using [`Platform::track_rewrites()`].
#[allow(clippy::result_large_err)]
/// An iterator visiting all key-value pairs in arbitrary order.
/// The iterator element type is `(&'a K, &'a V)`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// let map = HashMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// for (key, val) in map.iter() {
/// println!("key: {key} val: {val}");
/// }
/// ```
///
/// # Performance
///
/// In the current implementation, iterating over map takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[rustc_lint_query_instability]
/// Forks a parse stream so that parsing tokens out of either the original
/// or the fork does not advance the position of the other.
///
/// # Performance
///
/// Forking a parse stream is a cheap fixed amount of work and does not
/// involve copying token buffers. Where you might hit performance problems
/// is if your macro ends up parsing a large amount of content more than
/// once.
///
/// ```
/// # use syn::{Expr, Result};
/// # use syn::parse::ParseStream;
/// #
/// # fn bad(input: ParseStream) -> Result<Expr> {
/// // Do not do this.
/// if input.fork().parse::<Expr>().is_ok() {
/// return input.parse::<Expr>();
/// }
/// # unimplemented!()
/// # }
/// ```
///
/// As a rule, avoid parsing an unbounded amount of tokens out of a forked
/// parse stream. Only use a fork when the amount of work performed against
/// the fork is small and bounded.
///
/// When complex speculative parsing against the forked stream is
/// unavoidable, use [`parse::discouraged::Speculative`] to advance the
/// original stream once the fork's parse is determined to have been
/// successful.
///
/// For a lower level way to perform speculative parsing at the token level,
/// consider using [`ParseStream::step`] instead.
///
/// [`parse::discouraged::Speculative`]: discouraged::Speculative
/// [`ParseStream::step`]: ParseBuffer::step
///
/// # Example
///
/// The parse implementation shown here parses possibly restricted `pub`
/// visibilities.
///
/// - `pub`
/// - `pub(crate)`
/// - `pub(self)`
/// - `pub(super)`
/// - `pub(in some::path)`
///
/// To handle the case of visibilities inside of tuple structs, the parser
/// needs to distinguish parentheses that specify visibility restrictions
/// from parentheses that form part of a tuple type.
///
/// ```
/// # struct A;
/// # struct B;
/// # struct C;
/// #
/// struct S(pub(crate) A, pub (B, C));
/// ```
///
/// In this example input the first tuple struct element of `S` has
/// `pub(crate)` visibility while the second tuple struct element has `pub`
/// visibility; the parentheses around `(B, C)` are part of the type rather
/// than part of a visibility restriction.
///
/// The parser uses a forked parse stream to check the first token inside of
/// parentheses after the `pub` keyword. This is a small bounded amount of
/// work performed against the forked parse stream.
///
/// ```
/// use syn::{parenthesized, token, Ident, Path, Result, Token};
/// use syn::ext::IdentExt;
/// use syn::parse::{Parse, ParseStream};
///
/// struct PubVisibility {
/// pub_token: Token![pub],
/// restricted: Option<Restricted>,
/// }
///
/// struct Restricted {
/// paren_token: token::Paren,
/// in_token: Option<Token![in]>,
/// path: Path,
/// }
///
/// impl Parse for PubVisibility {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let pub_token: Token![pub] = input.parse()?;
///
/// if input.peek(token::Paren) {
/// let ahead = input.fork();
/// let mut content;
/// parenthesized!(content in ahead);
///
/// if content.peek(Token![crate])
/// || content.peek(Token![self])
/// || content.peek(Token![super])
/// {
/// return Ok(PubVisibility {
/// pub_token,
/// restricted: Some(Restricted {
/// paren_token: parenthesized!(content in input),
/// in_token: None,
/// path: Path::from(content.call(Ident::parse_any)?),
/// }),
/// });
/// } else if content.peek(Token![in]) {
/// return Ok(PubVisibility {
/// pub_token,
/// restricted: Some(Restricted {
/// paren_token: parenthesized!(content in input),
/// in_token: Some(content.parse()?),
/// path: content.call(Path::parse_mod_style)?,
/// }),
/// });
/// }
/// }
///
/// Ok(PubVisibility {
/// pub_token,
/// restricted: None,
/// })
/// }
/// }
/// ```
pub fn fork(&self) -> Self {
/// An iterator visiting all values mutably in arbitrary order.
/// The iterator element type is `&'a mut V`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// let mut map = HashMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// for val in map.values_mut() {
/// *val = *val + 10;
/// }
///
/// for val in map.values() {
/// println!("{val}");
/// }
/// ```
///
/// # Performance
///
/// In the current implementation, iterating over values takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[rustc_lint_query_instability]
/// Return an iterator to traverse all commits reachable as configured by the [Platform].
///
/// # Performance
///
/// It's highly recommended to set an [`object cache`][Repository::object_cache_size()] on the parent repo
/// to greatly speed up performance if the returned id is supposed to be looked up right after.
pub fn all(self) -> Result<revision::Walk<'repo>, Error> {
/// Provides an access to an up to date projection of the carried data.
///
/// # Motivation
///
/// Sometimes, an application consists of components. Each component has its own configuration
/// structure. The whole configuration contains all the smaller config parts.
///
/// For the sake of separation and abstraction, it is not desirable to pass the whole
/// configuration to each of the components. This allows the component to take only access to
/// its own part.
///
/// # Lifetimes & flexibility
///
/// This method is not the most flexible way, as the returned type borrows into the `ArcSwap`.
/// To provide access into eg. `Arc<ArcSwap<T>>`, you can create the [`Map`] type directly. See
/// the [`access`] module.
///
/// # Performance
///
/// As the provided function is called on each load from the shared storage, it should
/// generally be cheap. It is expected this will usually be just referencing of a field inside
/// the structure.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
///
/// use arc_swap::ArcSwap;
/// use arc_swap::access::Access;
///
/// struct Cfg {
/// value: usize,
/// }
///
/// fn print_many_times<V: Access<usize>>(value: V) {
/// for _ in 0..25 {
/// let value = value.load();
/// println!("{}", *value);
/// }
/// }
///
/// let shared = ArcSwap::from_pointee(Cfg { value: 0 });
/// let mapped = shared.map(|c: &Cfg| &c.value);
/// crossbeam_utils::thread::scope(|s| {
/// // Will print some zeroes and some twos
/// s.spawn(|_| print_many_times(mapped));
/// s.spawn(|_| shared.store(Arc::new(Cfg { value: 2 })));
/// }).expect("Something panicked in a thread");
/// ```
pub fn map<I, R, F>(&self, f: F) -> Map<&Self, I, F>
/// Advance this parse stream to the position of a forked parse stream.
///
/// This is the opposite operation to [`ParseStream::fork`]. You can fork a
/// parse stream, perform some speculative parsing, then join the original
/// stream to the fork to "commit" the parsing from the fork to the main
/// stream.
///
/// If you can avoid doing this, you should, as it limits the ability to
/// generate useful errors. That said, it is often the only way to parse
/// syntax of the form `A* B*` for arbitrary syntax `A` and `B`. The problem
/// is that when the fork fails to parse an `A`, it's impossible to tell
/// whether that was because of a syntax error and the user meant to provide
/// an `A`, or that the `A`s are finished and it's time to start parsing
/// `B`s. Use with care.
///
/// Also note that if `A` is a subset of `B`, `A* B*` can be parsed by
/// parsing `B*` and removing the leading members of `A` from the
/// repetition, bypassing the need to involve the downsides associated with
/// speculative parsing.
///
/// [`ParseStream::fork`]: ParseBuffer::fork
///
/// # Example
///
/// There has been chatter about the possibility of making the colons in the
/// turbofish syntax like `path::to::<T>` no longer required by accepting
/// `path::to<T>` in expression position. Specifically, according to [RFC
/// 2544], [`PathSegment`] parsing should always try to consume a following
/// `<` token as the start of generic arguments, and reset to the `<` if
/// that fails (e.g. the token is acting as a less-than operator).
///
/// This is the exact kind of parsing behavior which requires the "fork,
/// try, commit" behavior that [`ParseStream::fork`] discourages. With
/// `advance_to`, we can avoid having to parse the speculatively parsed
/// content a second time.
///
/// This change in behavior can be implemented in syn by replacing just the
/// `Parse` implementation for `PathSegment`:
///
/// ```
/// # use syn::ext::IdentExt;
/// use syn::parse::discouraged::Speculative;
/// # use syn::parse::{Parse, ParseStream};
/// # use syn::{Ident, PathArguments, Result, Token};
///
/// pub struct PathSegment {
/// pub ident: Ident,
/// pub arguments: PathArguments,
/// }
/// #
/// # impl<T> From<T> for PathSegment
/// # where
/// # T: Into<Ident>,
/// # {
/// # fn from(ident: T) -> Self {
/// # PathSegment {
/// # ident: ident.into(),
/// # arguments: PathArguments::None,
/// # }
/// # }
/// # }
///
/// impl Parse for PathSegment {
/// fn parse(input: ParseStream) -> Result<Self> {
/// if input.peek(Token![super])
/// || input.peek(Token![self])
/// || input.peek(Token![Self])
/// || input.peek(Token![crate])
/// {
/// let ident = input.call(Ident::parse_any)?;
/// return Ok(PathSegment::from(ident));
/// }
///
/// let ident = input.parse()?;
/// if input.peek(Token![::]) && input.peek3(Token![<]) {
/// return Ok(PathSegment {
/// ident,
/// arguments: PathArguments::AngleBracketed(input.parse()?),
/// });
/// }
/// if input.peek(Token![<]) && !input.peek(Token![<=]) {
/// let fork = input.fork();
/// if let Ok(arguments) = fork.parse() {
/// input.advance_to(&fork);
/// return Ok(PathSegment {
/// ident,
/// arguments: PathArguments::AngleBracketed(arguments),
/// });
/// }
/// }
/// Ok(PathSegment::from(ident))
/// }
/// }
///
/// # syn::parse_str::<PathSegment>("a<b,c>").unwrap();
/// ```
///
/// # Drawbacks
///
/// The main drawback of this style of speculative parsing is in error
/// presentation. Even if the lookahead is the "correct" parse, the error
/// that is shown is that of the "fallback" parse. To use the same example
/// as the turbofish above, take the following unfinished "turbofish":
///
/// ```text
/// let _ = f<&'a fn(), for<'a> serde::>();
/// ```
///
/// If this is parsed as generic arguments, we can provide the error message
///
/// ```text
/// error: expected identifier
/// --> src.rs:L:C
/// |
/// L | let _ = f<&'a fn(), for<'a> serde::>();
/// | ^
/// ```
///
/// but if parsed using the above speculative parsing, it falls back to
/// assuming that the `<` is a less-than when it fails to parse the generic
/// arguments, and tries to interpret the `&'a` as the start of a labelled
/// loop, resulting in the much less helpful error
///
/// ```text
/// error: expected `:`
/// --> src.rs:L:C
/// |
/// L | let _ = f<&'a fn(), for<'a> serde::>();
/// | ^^
/// ```
///
/// This can be mitigated with various heuristics (two examples: show both
/// forks' parse errors, or show the one that consumed more tokens), but
/// when you can control the grammar, sticking to something that can be
/// parsed LL(3) and without the LL(*) speculative parsing this makes
/// possible, displaying reasonable errors becomes much more simple.
///
/// [RFC 2544]: https://github.com/rust-lang/rfcs/pull/2544
/// [`PathSegment`]: crate::PathSegment
///
/// # Performance
///
/// This method performs a cheap fixed amount of work that does not depend
/// on how far apart the two streams are positioned.
///
/// # Panics
///
/// The forked stream in the argument of `advance_to` must have been
/// obtained by forking `self`. Attempting to advance to any other stream
/// will cause a panic.
fn advance_to(&self, fork: &Self);
/// An iterator visiting all values in arbitrary order.
/// The iterator element type is `&'a V`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// let map = HashMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// for val in map.values() {
/// println!("{val}");
/// }
/// ```
///
/// # Performance
///
/// In the current implementation, iterating over values takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[rustc_lint_query_instability]
/// Commits are sorted by their commit time in descending order, that is newest first.
///
/// The sorting applies to all currently queued commit ids and thus is full.
///
/// In the *sample history* the order would be `8, 7, 6, 5, 4, 3, 2, 1`
///
/// # Performance
///
/// This mode benefits greatly from having an object_cache in `find()`
/// to avoid having to lookup each commit twice.
ByCommitTimeNewestFirst,
/// This sorting is similar to `ByCommitTimeNewestFirst`, but adds a cutoff to not return commits older than
/// a given time, stopping the iteration once no younger commits is queued to be traversed.
///
/// As the query is usually repeated with different cutoff dates, this search mode benefits greatly from an object cache.
///
/// In the *sample history* and a cut-off date of 4, the returned list of commits would be `8, 7, 6, 4`
ByCommitTimeNewestFirstCutoffOlderThan {
/// The amount of seconds since unix epoch, the same value obtained by any `gix_date::Time` structure and the way git counts time.
seconds: gix_date::SecondsSinceUnixEpoch,
/// Follow a sequence of `path` components starting from this instance, and look them up one by one until the last component
/// is looked up and its tree entry is returned.
/// Use `buf` as temporary location for sub-trees to avoid allocating a temporary buffer for each lookup.
///
/// # Performance Notes
///
/// Searching tree entries is currently done in sequence, which allows to the search to be allocation free. It would be possible
/// to reuse a vector and use a binary search instead, which might be able to improve performance over all.
/// However, a benchmark should be created first to have some data and see which trade-off to choose here.
///
pub fn lookup_entry<I, P>(&self, path: I, buf: &mut Vec<u8>) -> Result<Option<Entry<'repo>>, find::existing::Error>
/// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`.
///
/// # Performance characteristics
///
/// ## The general case
///
/// In the general case, collecting into `Rc<[T]>` is done by first
/// collecting into a `Vec<T>`. That is, when writing the following:
///
/// ```rust
/// # use std::rc::Rc;
/// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
/// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
/// ```
///
/// this behaves as if we wrote:
///
/// ```rust
/// # use std::rc::Rc;
/// let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
/// .collect::<Vec<_>>() // The first set of allocations happens here.
/// .into(); // A second allocation for `Rc<[T]>` happens here.
/// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
/// ```
///
/// This will allocate as many times as needed for constructing the `Vec<T>`
/// and then it will allocate once for turning the `Vec<T>` into the `Rc<[T]>`.
///
/// ## Iterators of known length
///
/// When your `Iterator` implements `TrustedLen` and is of an exact size,
/// a single allocation will be made for the `Rc<[T]>`. For example:
///
/// ```rust
/// # use std::rc::Rc;
/// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
/// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
/// ```
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` for which `f(&e)` returns `false`.
/// The elements are visited in unsorted (and unspecified) order.
///
/// # Examples
///
/// ```
/// use std::collections::HashSet;
///
/// let mut set = HashSet::from([1, 2, 3, 4, 5, 6]);
/// set.retain(|&k| k % 2 == 0);
/// assert_eq!(set, HashSet::from([2, 4, 6]));
/// ```
///
/// # Performance
///
/// In the current implementation, this operation takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[rustc_lint_query_instability]
/// Advance this parse stream to the position of a forked parse stream.
///
/// This is the opposite operation to [`ParseStream::fork`]. You can fork a
/// parse stream, perform some speculative parsing, then join the original
/// stream to the fork to "commit" the parsing from the fork to the main
/// stream.
///
/// If you can avoid doing this, you should, as it limits the ability to
/// generate useful errors. That said, it is often the only way to parse
/// syntax of the form `A* B*` for arbitrary syntax `A` and `B`. The problem
/// is that when the fork fails to parse an `A`, it's impossible to tell
/// whether that was because of a syntax error and the user meant to provide
/// an `A`, or that the `A`s are finished and it's time to start parsing
/// `B`s. Use with care.
///
/// Also note that if `A` is a subset of `B`, `A* B*` can be parsed by
/// parsing `B*` and removing the leading members of `A` from the
/// repetition, bypassing the need to involve the downsides associated with
/// speculative parsing.
///
/// [`ParseStream::fork`]: ParseBuffer::fork
///
/// # Example
///
/// There has been chatter about the possibility of making the colons in the
/// turbofish syntax like `path::to::<T>` no longer required by accepting
/// `path::to<T>` in expression position. Specifically, according to [RFC
/// 2544], [`PathSegment`] parsing should always try to consume a following
/// `<` token as the start of generic arguments, and reset to the `<` if
/// that fails (e.g. the token is acting as a less-than operator).
///
/// This is the exact kind of parsing behavior which requires the "fork,
/// try, commit" behavior that [`ParseStream::fork`] discourages. With
/// `advance_to`, we can avoid having to parse the speculatively parsed
/// content a second time.
///
/// This change in behavior can be implemented in syn by replacing just the
/// `Parse` implementation for `PathSegment`:
///
/// ```
/// # use syn::ext::IdentExt;
/// use syn::parse::discouraged::Speculative;
/// # use syn::parse::{Parse, ParseStream};
/// # use syn::{Ident, PathArguments, Result, Token};
///
/// pub struct PathSegment {
/// pub ident: Ident,
/// pub arguments: PathArguments,
/// }
/// #
/// # impl<T> From<T> for PathSegment
/// # where
/// # T: Into<Ident>,
/// # {
/// # fn from(ident: T) -> Self {
/// # PathSegment {
/// # ident: ident.into(),
/// # arguments: PathArguments::None,
/// # }
/// # }
/// # }
///
/// impl Parse for PathSegment {
/// fn parse(input: ParseStream) -> Result<Self> {
/// if input.peek(Token![super])
/// || input.peek(Token![self])
/// || input.peek(Token![Self])
/// || input.peek(Token![crate])
/// {
/// let ident = input.call(Ident::parse_any)?;
/// return Ok(PathSegment::from(ident));
/// }
///
/// let ident = input.parse()?;
/// if input.peek(Token![::]) && input.peek3(Token![<]) {
/// return Ok(PathSegment {
/// ident,
/// arguments: PathArguments::AngleBracketed(input.parse()?),
/// });
/// }
/// if input.peek(Token![<]) && !input.peek(Token![<=]) {
/// let fork = input.fork();
/// if let Ok(arguments) = fork.parse() {
/// input.advance_to(&fork);
/// return Ok(PathSegment {
/// ident,
/// arguments: PathArguments::AngleBracketed(arguments),
/// });
/// }
/// }
/// Ok(PathSegment::from(ident))
/// }
/// }
///
/// # syn::parse_str::<PathSegment>("a<b,c>").unwrap();
/// ```
///
/// # Drawbacks
///
/// The main drawback of this style of speculative parsing is in error
/// presentation. Even if the lookahead is the "correct" parse, the error
/// that is shown is that of the "fallback" parse. To use the same example
/// as the turbofish above, take the following unfinished "turbofish":
///
/// ```text
/// let _ = f<&'a fn(), for<'a> serde::>();
/// ```
///
/// If this is parsed as generic arguments, we can provide the error message
///
/// ```text
/// error: expected identifier
/// --> src.rs:L:C
/// |
/// L | let _ = f<&'a fn(), for<'a> serde::>();
/// | ^
/// ```
///
/// but if parsed using the above speculative parsing, it falls back to
/// assuming that the `<` is a less-than when it fails to parse the generic
/// arguments, and tries to interpret the `&'a` as the start of a labelled
/// loop, resulting in the much less helpful error
///
/// ```text
/// error: expected `:`
/// --> src.rs:L:C
/// |
/// L | let _ = f<&'a fn(), for<'a> serde::>();
/// | ^^
/// ```
///
/// This can be mitigated with various heuristics (two examples: show both
/// forks' parse errors, or show the one that consumed more tokens), but
/// when you can control the grammar, sticking to something that can be
/// parsed LL(3) and without the LL(*) speculative parsing this makes
/// possible, displaying reasonable errors becomes much more simple.
///
/// [RFC 2544]: https://github.com/rust-lang/rfcs/pull/2544
/// [`PathSegment`]: crate::PathSegment
///
/// # Performance
///
/// This method performs a cheap fixed amount of work that does not depend
/// on how far apart the two streams are positioned.
///
/// # Panics
///
/// The forked stream in the argument of `advance_to` must have been
/// obtained by forking `self`. Attempting to advance to any other stream
/// will cause a panic.
fn advance_to(&self, fork: &Self);
/// An iterator visiting all keys in arbitrary order.
/// The iterator element type is `&'a K`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// let map = HashMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// for key in map.keys() {
/// println!("{key}");
/// }
/// ```
///
/// # Performance
///
/// In the current implementation, iterating over keys takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[rustc_lint_query_instability]
/// Creates a consuming iterator visiting all the values in arbitrary order.
/// The map cannot be used after calling this.
/// The iterator element type is `V`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// let map = HashMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// let mut vec: Vec<i32> = map.into_values().collect();
/// // The `IntoValues` iterator produces values in arbitrary order, so
/// // the values must be sorted to test them against a sorted array.
/// vec.sort_unstable();
/// assert_eq!(vec, [1, 2, 3]);
/// ```
///
/// # Performance
///
/// In the current implementation, iterating over values takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[inline]
/// Modifies interest in a file descriptor or socket to the poller, but with the specified
/// mode.
///
/// This is identical to the `modify()` function, but allows specifying the polling mode
/// to use for this socket.
///
/// # Performance Notes
///
/// This function can be used to change a source from one polling mode to another. However,
/// on some platforms, this switch can cause delays in the delivery of events.
///
/// # Errors
///
/// If the operating system does not support the specified mode, this function will return
/// an error.
pub fn modify_with_mode(
/// Retains only the elements specified by the predicate.
///
/// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
/// The elements are visited in unsorted (and unspecified) order.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
/// map.retain(|&k, _| k % 2 == 0);
/// assert_eq!(map.len(), 4);
/// ```
///
/// # Performance
///
/// In the current implementation, this operation takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[inline]
/// An iterator visiting all elements in arbitrary order.
/// The iterator element type is `&'a T`.
///
/// # Examples
///
/// ```
/// use std::collections::HashSet;
/// let mut set = HashSet::new();
/// set.insert("a");
/// set.insert("b");
///
/// // Will print in an arbitrary order.
/// for x in set.iter() {
/// println!("{x}");
/// }
/// ```
///
/// # Performance
///
/// In the current implementation, iterating over set takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[inline]
/// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`.
///
/// # Performance characteristics
///
/// ## The general case
///
/// In the general case, collecting into `Arc<[T]>` is done by first
/// collecting into a `Vec<T>`. That is, when writing the following:
///
/// ```rust
/// # use std::sync::Arc;
/// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
/// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
/// ```
///
/// this behaves as if we wrote:
///
/// ```rust
/// # use std::sync::Arc;
/// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0)
/// .collect::<Vec<_>>() // The first set of allocations happens here.
/// .into(); // A second allocation for `Arc<[T]>` happens here.
/// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]);
/// ```
///
/// This will allocate as many times as needed for constructing the `Vec<T>`
/// and then it will allocate once for turning the `Vec<T>` into the `Arc<[T]>`.
///
/// ## Iterators of known length
///
/// When your `Iterator` implements `TrustedLen` and is of an exact size,
/// a single allocation will be made for the `Arc<[T]>`. For example:
///
/// ```rust
/// # use std::sync::Arc;
/// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
/// # assert_eq!(&*evens, &*(0..10).collect::<Vec<_>>());
/// ```
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
/// Validates the argument via the given regular expression.
///
/// As regular expressions are not very user friendly, the additional `err_message` should
/// describe the expected format in clear words. All notes for [`Arg::validator()`] regarding the
/// error message and performance also hold for `validator_regex`.
///
/// The regular expression can either be borrowed or moved into `validator_regex`. This happens
/// automatically via [`RegexRef`]'s `Into` implementation.
///
/// # Performance
/// Regular expressions are expensive to compile. You should prefer sharing your regular expression.
/// We use a [`Cow`]-like internal structure to enable both sharing as well as taking ownership of a
/// provided regular expression.
///
/// # Examples
///
/// You can use the classical `"\d+"` regular expression to match digits only:
///
/// ```rust
/// # use clap::{Command, Arg};
/// use regex::Regex;
///
/// let digits = Regex::new(r"\d+").unwrap();
///
/// let res = Command::new("prog")
/// .arg(Arg::new("digits")
/// .validator_regex(&digits, "only digits are allowed"))
/// .try_get_matches_from(vec![
/// "prog", "12345"
/// ]);
/// assert!(res.is_ok());
/// assert_eq!(res.unwrap().value_of("digits"), Some("12345"));
/// ```
///
/// However, any valid `Regex` can be used:
///
/// ```rust
/// # use clap::{Command, Arg, ErrorKind};
/// use regex::Regex;
///
/// let priority = Regex::new(r"[A-C]").unwrap();
///
/// let res = Command::new("prog")
/// .arg(Arg::new("priority")
/// .validator_regex(priority, "only priorities A, B or C are allowed"))
/// .try_get_matches_from(vec![
/// "prog", "12345"
/// ]);
/// assert!(res.is_err());
/// assert_eq!(res.err().unwrap().kind(), ErrorKind::ValueValidation)
/// ```
#[cfg(feature = "regex")]
/// Advance this parse stream to the position of a forked parse stream.
///
/// This is the opposite operation to [`ParseStream::fork`]. You can fork a
/// parse stream, perform some speculative parsing, then join the original
/// stream to the fork to "commit" the parsing from the fork to the main
/// stream.
///
/// If you can avoid doing this, you should, as it limits the ability to
/// generate useful errors. That said, it is often the only way to parse
/// syntax of the form `A* B*` for arbitrary syntax `A` and `B`. The problem
/// is that when the fork fails to parse an `A`, it's impossible to tell
/// whether that was because of a syntax error and the user meant to provide
/// an `A`, or that the `A`s are finished and it's time to start parsing
/// `B`s. Use with care.
///
/// Also note that if `A` is a subset of `B`, `A* B*` can be parsed by
/// parsing `B*` and removing the leading members of `A` from the
/// repetition, bypassing the need to involve the downsides associated with
/// speculative parsing.
///
/// [`ParseStream::fork`]: ParseBuffer::fork
///
/// # Example
///
/// There has been chatter about the possibility of making the colons in the
/// turbofish syntax like `path::to::<T>` no longer required by accepting
/// `path::to<T>` in expression position. Specifically, according to [RFC
/// 2544], [`PathSegment`] parsing should always try to consume a following
/// `<` token as the start of generic arguments, and reset to the `<` if
/// that fails (e.g. the token is acting as a less-than operator).
///
/// This is the exact kind of parsing behavior which requires the "fork,
/// try, commit" behavior that [`ParseStream::fork`] discourages. With
/// `advance_to`, we can avoid having to parse the speculatively parsed
/// content a second time.
///
/// This change in behavior can be implemented in syn by replacing just the
/// `Parse` implementation for `PathSegment`:
///
/// ```
/// # use syn::ext::IdentExt;
/// use syn::parse::discouraged::Speculative;
/// # use syn::parse::{Parse, ParseStream};
/// # use syn::{Ident, PathArguments, Result, Token};
///
/// pub struct PathSegment {
/// pub ident: Ident,
/// pub arguments: PathArguments,
/// }
/// #
/// # impl<T> From<T> for PathSegment
/// # where
/// # T: Into<Ident>,
/// # {
/// # fn from(ident: T) -> Self {
/// # PathSegment {
/// # ident: ident.into(),
/// # arguments: PathArguments::None,
/// # }
/// # }
/// # }
///
/// impl Parse for PathSegment {
/// fn parse(input: ParseStream) -> Result<Self> {
/// if input.peek(Token![super])
/// || input.peek(Token![self])
/// || input.peek(Token![Self])
/// || input.peek(Token![crate])
/// {
/// let ident = input.call(Ident::parse_any)?;
/// return Ok(PathSegment::from(ident));
/// }
///
/// let ident = input.parse()?;
/// if input.peek(Token![::]) && input.peek3(Token![<]) {
/// return Ok(PathSegment {
/// ident,
/// arguments: PathArguments::AngleBracketed(input.parse()?),
/// });
/// }
/// if input.peek(Token![<]) && !input.peek(Token![<=]) {
/// let fork = input.fork();
/// if let Ok(arguments) = fork.parse() {
/// input.advance_to(&fork);
/// return Ok(PathSegment {
/// ident,
/// arguments: PathArguments::AngleBracketed(arguments),
/// });
/// }
/// }
/// Ok(PathSegment::from(ident))
/// }
/// }
///
/// # syn::parse_str::<PathSegment>("a<b,c>").unwrap();
/// ```
///
/// # Drawbacks
///
/// The main drawback of this style of speculative parsing is in error
/// presentation. Even if the lookahead is the "correct" parse, the error
/// that is shown is that of the "fallback" parse. To use the same example
/// as the turbofish above, take the following unfinished "turbofish":
///
/// ```text
/// let _ = f<&'a fn(), for<'a> serde::>();
/// ```
///
/// If this is parsed as generic arguments, we can provide the error message
///
/// ```text
/// error: expected identifier
/// --> src.rs:L:C
/// |
/// L | let _ = f<&'a fn(), for<'a> serde::>();
/// | ^
/// ```
///
/// but if parsed using the above speculative parsing, it falls back to
/// assuming that the `<` is a less-than when it fails to parse the generic
/// arguments, and tries to interpret the `&'a` as the start of a labelled
/// loop, resulting in the much less helpful error
///
/// ```text
/// error: expected `:`
/// --> src.rs:L:C
/// |
/// L | let _ = f<&'a fn(), for<'a> serde::>();
/// | ^^
/// ```
///
/// This can be mitigated with various heuristics (two examples: show both
/// forks' parse errors, or show the one that consumed more tokens), but
/// when you can control the grammar, sticking to something that can be
/// parsed LL(3) and without the LL(*) speculative parsing this makes
/// possible, displaying reasonable errors becomes much more simple.
///
/// [RFC 2544]: https://github.com/rust-lang/rfcs/pull/2544
/// [`PathSegment`]: crate::PathSegment
///
/// # Performance
///
/// This method performs a cheap fixed amount of work that does not depend
/// on how far apart the two streams are positioned.
///
/// # Panics
///
/// The forked stream in the argument of `advance_to` must have been
/// obtained by forking `self`. Attempting to advance to any other stream
/// will cause a panic.
fn advance_to(&self, fork: &Self);
/// Advance this parse stream to the position of a forked parse stream.
///
/// This is the opposite operation to [`ParseStream::fork`]. You can fork a
/// parse stream, perform some speculative parsing, then join the original
/// stream to the fork to "commit" the parsing from the fork to the main
/// stream.
///
/// If you can avoid doing this, you should, as it limits the ability to
/// generate useful errors. That said, it is often the only way to parse
/// syntax of the form `A* B*` for arbitrary syntax `A` and `B`. The problem
/// is that when the fork fails to parse an `A`, it's impossible to tell
/// whether that was because of a syntax error and the user meant to provide
/// an `A`, or that the `A`s are finished and it's time to start parsing
/// `B`s. Use with care.
///
/// Also note that if `A` is a subset of `B`, `A* B*` can be parsed by
/// parsing `B*` and removing the leading members of `A` from the
/// repetition, bypassing the need to involve the downsides associated with
/// speculative parsing.
///
/// [`ParseStream::fork`]: ParseBuffer::fork
///
/// # Example
///
/// There has been chatter about the possibility of making the colons in the
/// turbofish syntax like `path::to::<T>` no longer required by accepting
/// `path::to<T>` in expression position. Specifically, according to [RFC
/// 2544], [`PathSegment`] parsing should always try to consume a following
/// `<` token as the start of generic arguments, and reset to the `<` if
/// that fails (e.g. the token is acting as a less-than operator).
///
/// This is the exact kind of parsing behavior which requires the "fork,
/// try, commit" behavior that [`ParseStream::fork`] discourages. With
/// `advance_to`, we can avoid having to parse the speculatively parsed
/// content a second time.
///
/// This change in behavior can be implemented in syn by replacing just the
/// `Parse` implementation for `PathSegment`:
///
/// ```
/// # use syn::ext::IdentExt;
/// use syn::parse::discouraged::Speculative;
/// # use syn::parse::{Parse, ParseStream};
/// # use syn::{Ident, PathArguments, Result, Token};
///
/// pub struct PathSegment {
/// pub ident: Ident,
/// pub arguments: PathArguments,
/// }
/// #
/// # impl<T> From<T> for PathSegment
/// # where
/// # T: Into<Ident>,
/// # {
/// # fn from(ident: T) -> Self {
/// # PathSegment {
/// # ident: ident.into(),
/// # arguments: PathArguments::None,
/// # }
/// # }
/// # }
///
/// impl Parse for PathSegment {
/// fn parse(input: ParseStream) -> Result<Self> {
/// if input.peek(Token![super])
/// || input.peek(Token![self])
/// || input.peek(Token![Self])
/// || input.peek(Token![crate])
/// {
/// let ident = input.call(Ident::parse_any)?;
/// return Ok(PathSegment::from(ident));
/// }
///
/// let ident = input.parse()?;
/// if input.peek(Token![::]) && input.peek3(Token![<]) {
/// return Ok(PathSegment {
/// ident,
/// arguments: PathArguments::AngleBracketed(input.parse()?),
/// });
/// }
/// if input.peek(Token![<]) && !input.peek(Token![<=]) {
/// let fork = input.fork();
/// if let Ok(arguments) = fork.parse() {
/// input.advance_to(&fork);
/// return Ok(PathSegment {
/// ident,
/// arguments: PathArguments::AngleBracketed(arguments),
/// });
/// }
/// }
/// Ok(PathSegment::from(ident))
/// }
/// }
///
/// # syn::parse_str::<PathSegment>("a<b,c>").unwrap();
/// ```
///
/// # Drawbacks
///
/// The main drawback of this style of speculative parsing is in error
/// presentation. Even if the lookahead is the "correct" parse, the error
/// that is shown is that of the "fallback" parse. To use the same example
/// as the turbofish above, take the following unfinished "turbofish":
///
/// ```text
/// let _ = f<&'a fn(), for<'a> serde::>();
/// ```
///
/// If this is parsed as generic arguments, we can provide the error message
///
/// ```text
/// error: expected identifier
/// --> src.rs:L:C
/// |
/// L | let _ = f<&'a fn(), for<'a> serde::>();
/// | ^
/// ```
///
/// but if parsed using the above speculative parsing, it falls back to
/// assuming that the `<` is a less-than when it fails to parse the generic
/// arguments, and tries to interpret the `&'a` as the start of a labelled
/// loop, resulting in the much less helpful error
///
/// ```text
/// error: expected `:`
/// --> src.rs:L:C
/// |
/// L | let _ = f<&'a fn(), for<'a> serde::>();
/// | ^^
/// ```
///
/// This can be mitigated with various heuristics (two examples: show both
/// forks' parse errors, or show the one that consumed more tokens), but
/// when you can control the grammar, sticking to something that can be
/// parsed LL(3) and without the LL(*) speculative parsing this makes
/// possible, displaying reasonable errors becomes much more simple.
///
/// [RFC 2544]: https://github.com/rust-lang/rfcs/pull/2544
/// [`PathSegment`]: crate::PathSegment
///
/// # Performance
///
/// This method performs a cheap fixed amount of work that does not depend
/// on how far apart the two streams are positioned.
///
/// # Panics
///
/// The forked stream in the argument of `advance_to` must have been
/// obtained by forking `self`. Attempting to advance to any other stream
/// will cause a panic.
fn advance_to(&self, fork: &Self);
/// Creates a consuming iterator visiting all the keys in arbitrary order.
/// The map cannot be used after calling this.
/// The iterator element type is `K`.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// let map = HashMap::from([
/// ("a", 1),
/// ("b", 2),
/// ("c", 3),
/// ]);
///
/// let mut vec: Vec<&str> = map.into_keys().collect();
/// // The `IntoKeys` iterator produces keys in arbitrary order, so the
/// // keys must be sorted to test them against a sorted array.
/// vec.sort_unstable();
/// assert_eq!(vec, ["a", "b", "c"]);
/// ```
///
/// # Performance
///
/// In the current implementation, iterating over keys takes O(capacity) time
/// instead of O(len) because it internally visits empty buckets too.
#[inline]
/// Forks a parse stream so that parsing tokens out of either the original
/// or the fork does not advance the position of the other.
///
/// # Performance
///
/// Forking a parse stream is a cheap fixed amount of work and does not
/// involve copying token buffers. Where you might hit performance problems
/// is if your macro ends up parsing a large amount of content more than
/// once.
///
/// ```
/// # use syn::{Expr, Result};
/// # use syn::parse::ParseStream;
/// #
/// # fn bad(input: ParseStream) -> Result<Expr> {
/// // Do not do this.
/// if input.fork().parse::<Expr>().is_ok() {
/// return input.parse::<Expr>();
/// }
/// # unimplemented!()
/// # }
/// ```
///
/// As a rule, avoid parsing an unbounded amount of tokens out of a forked
/// parse stream. Only use a fork when the amount of work performed against
/// the fork is small and bounded.
///
/// When complex speculative parsing against the forked stream is
/// unavoidable, use [`parse::discouraged::Speculative`] to advance the
/// original stream once the fork's parse is determined to have been
/// successful.
///
/// For a lower level way to perform speculative parsing at the token level,
/// consider using [`ParseStream::step`] instead.
///
/// [`parse::discouraged::Speculative`]: discouraged::Speculative
/// [`ParseStream::step`]: ParseBuffer::step
///
/// # Example
///
/// The parse implementation shown here parses possibly restricted `pub`
/// visibilities.
///
/// - `pub`
/// - `pub(crate)`
/// - `pub(self)`
/// - `pub(super)`
/// - `pub(in some::path)`
///
/// To handle the case of visibilities inside of tuple structs, the parser
/// needs to distinguish parentheses that specify visibility restrictions
/// from parentheses that form part of a tuple type.
///
/// ```
/// # struct A;
/// # struct B;
/// # struct C;
/// #
/// struct S(pub(crate) A, pub (B, C));
/// ```
///
/// In this example input the first tuple struct element of `S` has
/// `pub(crate)` visibility while the second tuple struct element has `pub`
/// visibility; the parentheses around `(B, C)` are part of the type rather
/// than part of a visibility restriction.
///
/// The parser uses a forked parse stream to check the first token inside of
/// parentheses after the `pub` keyword. This is a small bounded amount of
/// work performed against the forked parse stream.
///
/// ```
/// use syn::{parenthesized, token, Ident, Path, Result, Token};
/// use syn::ext::IdentExt;
/// use syn::parse::{Parse, ParseStream};
///
/// struct PubVisibility {
/// pub_token: Token![pub],
/// restricted: Option<Restricted>,
/// }
///
/// struct Restricted {
/// paren_token: token::Paren,
/// in_token: Option<Token![in]>,
/// path: Path,
/// }
///
/// impl Parse for PubVisibility {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let pub_token: Token![pub] = input.parse()?;
///
/// if input.peek(token::Paren) {
/// let ahead = input.fork();
/// let mut content;
/// parenthesized!(content in ahead);
///
/// if content.peek(Token![crate])
/// || content.peek(Token![self])
/// || content.peek(Token![super])
/// {
/// return Ok(PubVisibility {
/// pub_token,
/// restricted: Some(Restricted {
/// paren_token: parenthesized!(content in input),
/// in_token: None,
/// path: Path::from(content.call(Ident::parse_any)?),
/// }),
/// });
/// } else if content.peek(Token![in]) {
/// return Ok(PubVisibility {
/// pub_token,
/// restricted: Some(Restricted {
/// paren_token: parenthesized!(content in input),
/// in_token: Some(content.parse()?),
/// path: content.call(Path::parse_mod_style)?,
/// }),
/// });
/// }
/// }
///
/// Ok(PubVisibility {
/// pub_token,
/// restricted: None,
/// })
/// }
/// }
/// ```
pub fn fork(&self) -> Self {
/// `If-Match` header, defined in
/// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.1)
///
/// The `If-Match` header field makes the request method conditional on
/// the recipient origin server either having at least one current
/// representation of the target resource, when the field-value is "*",
/// or having a current representation of the target resource that has an
/// entity-tag matching a member of the list of entity-tags provided in
/// the field-value.
///
/// An origin server MUST use the strong comparison function when
/// comparing entity-tags for `If-Match`, since the client
/// intends this precondition to prevent the method from being applied if
/// there have been any changes to the representation data.
///
/// # ABNF
/// ```plain
/// If-Match = "*" / 1#entity-tag
/// ```
///
/// # Example values
/// * `"xyzzy"`
/// * "xyzzy", "r2d2xxxx", "c3piozzzz"
///
/// # Examples
/// ```
/// use hyper::header::{Headers, IfMatch};
///
/// let mut headers = Headers::new();
/// headers.set(IfMatch::Any);
/// ```
/// ```
/// use hyper::header::{Headers, IfMatch, EntityTag};
///
/// let mut headers = Headers::new();
/// headers.set(
/// IfMatch::Items(vec![
/// EntityTag::new(false, "xyzzy".to_owned()),
/// EntityTag::new(false, "foobar".to_owned()),
/// EntityTag::new(false, "bazquux".to_owned()),
/// ])
/// );
/// ```
(IfMatch, "If-Match") => {Any / (EntityTag)+}
/// `Connection` header, defined in
/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-6.1)
///
/// The `Connection` header field allows the sender to indicate desired
/// control options for the current connection. In order to avoid
/// confusing downstream recipients, a proxy or gateway MUST remove or
/// replace any received connection options before forwarding the
/// message.
///
/// # ABNF
/// ```plain
/// Connection = 1#connection-option
/// connection-option = token
///
/// # Example values
/// * `close`
/// * `keep-alive`
/// * `upgrade`
/// ```
///
/// # Examples
/// ```
/// use hyper::header::{Headers, Connection};
///
/// let mut headers = Headers::new();
/// headers.set(Connection::keep_alive());
/// ```
/// ```
/// # extern crate hyper;
/// # extern crate unicase;
/// # fn main() {
/// // extern crate unicase;
///
/// use hyper::header::{Headers, Connection, ConnectionOption};
/// use unicase::UniCase;
///
/// let mut headers = Headers::new();
/// headers.set(
/// Connection(vec![
/// ConnectionOption::ConnectionHeader(UniCase("upgrade".to_owned())),
/// ])
/// );
/// # }
/// ```
(Connection, "Connection") => (ConnectionOption)+
/// `Accept-Encoding` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.4)
///
/// The `Accept-Encoding` header field can be used by user agents to
/// indicate what response content-codings are
/// acceptable in the response. An `identity` token is used as a synonym
/// for "no encoding" in order to communicate when no encoding is
/// preferred.
///
/// # ABNF
/// ```plain
/// Accept-Encoding = #( codings [ weight ] )
/// codings = content-coding / "identity" / "*"
/// ```
///
/// # Example values
/// * `compress, gzip`
/// * ``
/// * `*`
/// * `compress;q=0.5, gzip;q=1`
/// * `gzip;q=1.0, identity; q=0.5, *;q=0`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AcceptEncoding, Encoding, qitem};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptEncoding(vec![qitem(Encoding::Chunked)])
/// );
/// ```
/// ```
/// use hyper::header::{Headers, AcceptEncoding, Encoding, qitem};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptEncoding(vec![
/// qitem(Encoding::Chunked),
/// qitem(Encoding::Gzip),
/// qitem(Encoding::Deflate),
/// ])
/// );
/// ```
/// ```
/// use hyper::header::{Headers, AcceptEncoding, Encoding, QualityItem, Quality, qitem};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptEncoding(vec![
/// qitem(Encoding::Chunked),
/// QualityItem::new(Encoding::Gzip, Quality(600)),
/// QualityItem::new(Encoding::EncodingExt("*".to_owned()), Quality(0)),
/// ])
/// );
/// ```
(AcceptEncoding, "Accept-Encoding") => (QualityItem<Encoding>)*
/// `Access-Control-Allow-Methods` header, part of
/// [CORS](http://www.w3.org/TR/cors/#access-control-allow-methods-response-header)
///
/// The `Access-Control-Allow-Methods` header indicates, as part of the
/// response to a preflight request, which methods can be used during the
/// actual request.
///
/// # ABNF
/// ```plain
/// Access-Control-Allow-Methods: "Access-Control-Allow-Methods" ":" #Method
/// ```
///
/// # Example values
/// * `PUT, DELETE, XMODIFY`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AccessControlAllowMethods};
/// use hyper::method::Method;
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlAllowMethods(vec![Method::Get])
/// );
/// ```
/// ```
/// use hyper::header::{Headers, AccessControlAllowMethods};
/// use hyper::method::Method;
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlAllowMethods(vec![
/// Method::Get,
/// Method::Post,
/// Method::Patch,
/// Method::Extension("COPY".to_owned()),
/// ])
/// );
/// ```
(AccessControlAllowMethods, "Access-Control-Allow-Methods") => (Method)*
/// `Access-Control-Max-Age` header, part of
/// [CORS](http://www.w3.org/TR/cors/#access-control-max-age-response-header)
///
/// The `Access-Control-Max-Age` header indicates how long the results of a
/// preflight request can be cached in a preflight result cache.
///
/// # ABNF
/// ```plain
/// Access-Control-Max-Age = \"Access-Control-Max-Age\" \":\" delta-seconds
/// ```
///
/// # Example values
/// * `531`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AccessControlMaxAge};
///
/// let mut headers = Headers::new();
/// headers.set(AccessControlMaxAge(1728000u32));
/// ```
(AccessControlMaxAge, "Access-Control-Max-Age") => [u32]
/// `User-Agent` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.5.3)
///
/// The `User-Agent` header field contains information about the user
/// agent originating the request, which is often used by servers to help
/// identify the scope of reported interoperability problems, to work
/// around or tailor responses to avoid particular user agent
/// limitations, and for analytics regarding browser or operating system
/// use. A user agent SHOULD send a User-Agent field in each request
/// unless specifically configured not to do so.
///
/// # ABNF
/// ```plain
/// User-Agent = product *( RWS ( product / comment ) )
/// product = token ["/" product-version]
/// product-version = token
/// ```
///
/// # Example values
/// * `CERN-LineMode/2.15 libwww/2.17b3`
/// * `Bunnies`
///
/// # Notes
/// * The parser does not split the value
///
/// # Example
/// ```
/// use hyper::header::{Headers, UserAgent};
///
/// let mut headers = Headers::new();
/// headers.set(UserAgent("hyper/0.5.2".to_owned()));
/// ```
(UserAgent, "User-Agent") => [String]
/// `Last-Modified` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.2)
///
/// The `Last-Modified` header field in a response provides a timestamp
/// indicating the date and time at which the origin server believes the
/// selected representation was last modified, as determined at the
/// conclusion of handling the request.
///
/// # ABNF
/// ```plain
/// Expires = HTTP-date
/// ```
///
/// # Example values
/// * `Sat, 29 Oct 1994 19:43:31 GMT`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate time;
/// # fn main() {
/// // extern crate time;
///
/// use hyper::header::{Headers, LastModified, HttpDate};
/// use time::{self, Duration};
///
/// let mut headers = Headers::new();
/// headers.set(LastModified(HttpDate(time::now() - Duration::days(1))));
/// # }
/// ```
(LastModified, "Last-Modified") => [HttpDate]
/// `If-Modified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.3)
///
/// The `If-Modified-Since` header field makes a GET or HEAD request
/// method conditional on the selected representation's modification date
/// being more recent than the date provided in the field-value.
/// Transfer of the selected representation's data is avoided if that
/// data has not changed.
///
/// # ABNF
/// ```plain
/// If-Unmodified-Since = HTTP-date
/// ```
///
/// # Example values
/// * `Sat, 29 Oct 1994 19:43:31 GMT`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate time;
/// # fn main() {
/// // extern crate time;
///
/// use hyper::header::{Headers, IfModifiedSince, HttpDate};
/// use time::{self, Duration};
///
/// let mut headers = Headers::new();
/// headers.set(IfModifiedSince(HttpDate(time::now() - Duration::days(1))));
/// # }
/// ```
(IfModifiedSince, "If-Modified-Since") => [HttpDate]
/// `Expires` header, defined in [RFC7234](http://tools.ietf.org/html/rfc7234#section-5.3)
///
/// The `Expires` header field gives the date/time after which the
/// response is considered stale.
///
/// The presence of an Expires field does not imply that the original
/// resource will change or cease to exist at, before, or after that
/// time.
///
/// # ABNF
/// ```plain
/// Expires = HTTP-date
/// ```
///
/// # Example values
/// * `Thu, 01 Dec 1994 16:00:00 GMT`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate time;
/// # fn main() {
/// // extern crate time;
///
/// use hyper::header::{Headers, Expires, HttpDate};
/// use time::{self, Duration};
///
/// let mut headers = Headers::new();
/// headers.set(Expires(HttpDate(time::now() + Duration::days(1))));
/// # }
/// ```
(Expires, "Expires") => [HttpDate]
/// `If-None-Match` header, defined in
/// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.2)
///
/// The `If-None-Match` header field makes the request method conditional
/// on a recipient cache or origin server either not having any current
/// representation of the target resource, when the field-value is "*",
/// or having a selected representation with an entity-tag that does not
/// match any of those listed in the field-value.
///
/// A recipient MUST use the weak comparison function when comparing
/// entity-tags for If-None-Match (Section 2.3.2), since weak entity-tags
/// can be used for cache validation even if there have been changes to
/// the representation data.
///
/// # ABNF
/// ```plain
/// If-None-Match = "*" / 1#entity-tag
/// ```
///
/// # Example values
/// * `"xyzzy"`
/// * `W/"xyzzy"`
/// * `"xyzzy", "r2d2xxxx", "c3piozzzz"`
/// * `W/"xyzzy", W/"r2d2xxxx", W/"c3piozzzz"`
/// * `*`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, IfNoneMatch};
///
/// let mut headers = Headers::new();
/// headers.set(IfNoneMatch::Any);
/// ```
/// ```
/// use hyper::header::{Headers, IfNoneMatch, EntityTag};
///
/// let mut headers = Headers::new();
/// headers.set(
/// IfNoneMatch::Items(vec![
/// EntityTag::new(false, "xyzzy".to_owned()),
/// EntityTag::new(false, "foobar".to_owned()),
/// EntityTag::new(false, "bazquux".to_owned()),
/// ])
/// );
/// ```
(IfNoneMatch, "If-None-Match") => {Any / (EntityTag)+}
/// `Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1)
///
/// The `Allow` header field lists the set of methods advertised as
/// supported by the target resource. The purpose of this field is
/// strictly to inform the recipient of valid request methods associated
/// with the resource.
///
/// # ABNF
/// ```plain
/// Allow = #method
/// ```
///
/// # Example values
/// * `GET, HEAD, PUT`
/// * `OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT, PATCH, fOObAr`
/// * ``
///
/// # Examples
/// ```
/// use hyper::header::{Headers, Allow};
/// use hyper::method::Method;
///
/// let mut headers = Headers::new();
/// headers.set(
/// Allow(vec![Method::Get])
/// );
/// ```
/// ```
/// use hyper::header::{Headers, Allow};
/// use hyper::method::Method;
///
/// let mut headers = Headers::new();
/// headers.set(
/// Allow(vec![
/// Method::Get,
/// Method::Post,
/// Method::Patch,
/// Method::Extension("COPY".to_owned()),
/// ])
/// );
/// ```
(Allow, "Allow") => (Method)*
/// `Access-Control-Request-Headers` header, part of
/// [CORS](http://www.w3.org/TR/cors/#access-control-request-headers-request-header)
///
/// The `Access-Control-Request-Headers` header indicates which headers will
/// be used in the actual request as part of the preflight request.
/// during the actual request.
///
/// # ABNF
/// ```plain
/// Access-Control-Allow-Headers: "Access-Control-Allow-Headers" ":" #field-name
/// ```
///
/// # Example values
/// * `accept-language, date`
///
/// # Examples
/// ```
/// # extern crate hyper;
/// # extern crate unicase;
/// # fn main() {
/// // extern crate unicase;
///
/// use hyper::header::{Headers, AccessControlRequestHeaders};
/// use unicase::UniCase;
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlRequestHeaders(vec![UniCase("date".to_owned())])
/// );
/// # }
/// ```
/// ```
/// # extern crate hyper;
/// # extern crate unicase;
/// # fn main() {
/// // extern crate unicase;
///
/// use hyper::header::{Headers, AccessControlRequestHeaders};
/// use unicase::UniCase;
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlRequestHeaders(vec![
/// UniCase("accept-language".to_owned()),
/// UniCase("date".to_owned()),
/// ])
/// );
/// # }
/// ```
(AccessControlRequestHeaders, "Access-Control-Request-Headers") => (UniCase<String>)*
/// `Accept-Charset` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.3)
///
/// The `Accept-Charset` header field can be sent by a user agent to
/// indicate what charsets are acceptable in textual response content.
/// This field allows user agents capable of understanding more
/// comprehensive or special-purpose charsets to signal that capability
/// to an origin server that is capable of representing information in
/// those charsets.
///
/// # ABNF
/// ```plain
/// Accept-Charset = 1#( ( charset / "*" ) [ weight ] )
/// ```
///
/// # Example values
/// * `iso-8859-5, unicode-1-1;q=0.8`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AcceptCharset, Charset, qitem};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptCharset(vec![qitem(Charset::Us_Ascii)])
/// );
/// ```
/// ```
/// use hyper::header::{Headers, AcceptCharset, Charset, Quality, QualityItem};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptCharset(vec![
/// QualityItem::new(Charset::Us_Ascii, Quality(900)),
/// QualityItem::new(Charset::Iso_8859_10, Quality(200)),
/// ])
/// );
/// ```
/// ```
/// use hyper::header::{Headers, AcceptCharset, Charset, qitem};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptCharset(vec![qitem(Charset::Ext("utf-8".to_owned()))])
/// );
/// ```
(AcceptCharset, "Accept-Charset") => (QualityItem<Charset>)+
/// `ETag` header, defined in [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.3)
///
/// The `ETag` header field in a response provides the current entity-tag
/// for the selected representation, as determined at the conclusion of
/// handling the request. An entity-tag is an opaque validator for
/// differentiating between multiple representations of the same
/// resource, regardless of whether those multiple representations are
/// due to resource state changes over time, content negotiation
/// resulting in multiple representations being valid at the same time,
/// or both. An entity-tag consists of an opaque quoted string, possibly
/// prefixed by a weakness indicator.
///
/// # ABNF
/// ```plain
/// ETag = entity-tag
/// ```
///
/// # Example values
/// * `"xyzzy"`
/// * `W/"xyzzy"`
/// * `""`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, ETag, EntityTag};
///
/// let mut headers = Headers::new();
/// headers.set(ETag(EntityTag::new(false, "xyzzy".to_owned())));
/// ```
/// ```
/// use hyper::header::{Headers, ETag, EntityTag};
///
/// let mut headers = Headers::new();
/// headers.set(ETag(EntityTag::new(true, "xyzzy".to_owned())));
/// ```
(ETag, "ETag") => [EntityTag]
/// `Access-Control-Expose-Headers` header, part of
/// [CORS](http://www.w3.org/TR/cors/#access-control-expose-headers-response-header)
///
/// The Access-Control-Expose-Headers header indicates which headers are safe to expose to the
/// API of a CORS API specification.
///
/// # ABNF
/// ```plain
/// Access-Control-Expose-Headers = "Access-Control-Expose-Headers" ":" #field-name
/// ```
///
/// # Example values
/// * `ETag, Content-Length`
///
/// # Examples
/// ```
/// # extern crate hyper;
/// # extern crate unicase;
/// # fn main() {
/// // extern crate unicase;
///
/// use hyper::header::{Headers, AccessControlExposeHeaders};
/// use unicase::UniCase;
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlExposeHeaders(vec![
/// UniCase("etag".to_owned()),
/// UniCase("content-length".to_owned())
/// ])
/// );
/// # }
/// ```
/// ```
/// # extern crate hyper;
/// # extern crate unicase;
/// # fn main() {
/// // extern crate unicase;
///
/// use hyper::header::{Headers, AccessControlExposeHeaders};
/// use unicase::UniCase;
///
/// let mut headers = Headers::new();
/// headers.set(
/// AccessControlExposeHeaders(vec![
/// UniCase("etag".to_owned()),
/// UniCase("content-length".to_owned())
/// ])
/// );
/// # }
/// ```
(AccessControlExposeHeaders, "Access-Control-Expose-Headers") => (UniCase<String>)*
/// `Server` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.2)
///
/// The `Server` header field contains information about the software
/// used by the origin server to handle the request, which is often used
/// by clients to help identify the scope of reported interoperability
/// problems, to work around or tailor requests to avoid particular
/// server limitations, and for analytics regarding server or operating
/// system use. An origin server MAY generate a Server field in its
/// responses.
///
/// # ABNF
/// ```plain
/// Server = product *( RWS ( product / comment ) )
/// ```
///
/// # Example values
/// * `CERN/3.0 libwww/2.17`
///
/// # Example
/// ```
/// use hyper::header::{Headers, Server};
///
/// let mut headers = Headers::new();
/// headers.set(Server("hyper/0.5.2".to_owned()));
/// ```
// TODO: Maybe parse as defined in the spec?
/// `Referer` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.5.2)
///
/// The `Referer` [sic] header field allows the user agent to specify a
/// URI reference for the resource from which the target URI was obtained
/// (i.e., the "referrer", though the field name is misspelled). A user
/// agent MUST NOT include the fragment and userinfo components of the
/// URI reference, if any, when generating the Referer field value.
///
/// # ABNF
/// ```plain
/// Referer = absolute-URI / partial-URI
/// ```
///
/// # Example values
/// * `http://www.example.org/hypertext/Overview.html`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, Referer};
///
/// let mut headers = Headers::new();
/// headers.set(Referer("/People.html#tim".to_owned()));
/// ```
/// ```
/// use hyper::header::{Headers, Referer};
///
/// let mut headers = Headers::new();
/// headers.set(Referer("http://www.example.com/index.html".to_owned()));
/// ```
// TODO Use URL
/// `Transfer-Encoding` header, defined in
/// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.1)
///
/// The `Transfer-Encoding` header field lists the transfer coding names
/// corresponding to the sequence of transfer codings that have been (or
/// will be) applied to the payload body in order to form the message
/// body.
///
/// # ABNF
/// ```plain
/// Transfer-Encoding = 1#transfer-coding
/// ```
///
/// # Example values
/// * `gzip, chunked`
///
/// # Example
/// ```
/// use hyper::header::{Headers, TransferEncoding, Encoding};
///
/// let mut headers = Headers::new();
/// headers.set(
/// TransferEncoding(vec![
/// Encoding::Gzip,
/// Encoding::Chunked,
/// ])
/// );
/// ```
(TransferEncoding, "Transfer-Encoding") => (Encoding)+
/// `Accept-Language` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)
///
/// The `Accept-Language` header field can be used by user agents to
/// indicate the set of natural languages that are preferred in the
/// response.
///
/// # ABNF
/// ```plain
/// Accept-Language = 1#( language-range [ weight ] )
/// language-range = <language-range, see [RFC4647], Section 2.1>
/// ```
///
/// # Example values
/// * `da, en-gb;q=0.8, en;q=0.7`
/// * `en-us;q=1.0, en;q=0.5, fr`
///
/// # Examples
/// ```
/// use hyper::LanguageTag;
/// use hyper::header::{Headers, AcceptLanguage, qitem};
///
/// let mut headers = Headers::new();
/// let mut langtag: LanguageTag = Default::default();
/// langtag.language = Some("en".to_owned());
/// langtag.region = Some("US".to_owned());
/// headers.set(
/// AcceptLanguage(vec![
/// qitem(langtag),
/// ])
/// );
/// ```
/// ```
/// # extern crate hyper;
/// # #[macro_use] extern crate language_tags;
/// # use hyper::header::{Headers, AcceptLanguage, QualityItem, Quality, qitem};
/// #
/// # fn main() {
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptLanguage(vec![
/// qitem(langtag!(da)),
/// QualityItem::new(langtag!(en;;;GB), Quality(800)),
/// QualityItem::new(langtag!(en), Quality(700)),
/// ])
/// );
/// # }
/// ```
(AcceptLanguage, "Accept-Language") => (QualityItem<LanguageTag>)+
/// `Content-Type` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5)
///
/// The `Content-Type` header field indicates the media type of the
/// associated representation: either the representation enclosed in the
/// message payload or the selected representation, as determined by the
/// message semantics. The indicated media type defines both the data
/// format and how that data is intended to be processed by a recipient,
/// within the scope of the received message semantics, after any content
/// codings indicated by Content-Encoding are decoded.
///
/// # ABNF
/// ```plain
/// Content-Type = media-type
/// ```
///
/// # Example values
/// * `text/html; charset=ISO-8859-4`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, ContentType};
/// use hyper::mime::{Mime, TopLevel, SubLevel};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType(Mime(TopLevel::Text, SubLevel::Html, vec![]))
/// );
/// ```
/// ```
/// use hyper::header::{Headers, ContentType};
/// use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType(Mime(TopLevel::Application, SubLevel::Json,
/// vec![(Attr::Charset, Value::Utf8)]))
/// );
/// ```
(ContentType, "Content-Type") => [Mime]
/// `Accept-Ranges` header, defined in
/// [RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)
///
/// The `Accept-Ranges` header field allows a server to indicate that it
/// supports range requests for the target resource.
///
/// # ABNF
/// ```plain
/// Accept-Ranges = acceptable-ranges
/// acceptable-ranges = 1#range-unit / \"none\"
///
/// # Example values
/// * `bytes`
/// * `none`
/// * `unknown-unit`
/// ```
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AcceptRanges, RangeUnit};
///
/// let mut headers = Headers::new();
/// headers.set(AcceptRanges(vec![RangeUnit::Bytes]));
/// ```
/// ```
/// use hyper::header::{Headers, AcceptRanges, RangeUnit};
///
/// let mut headers = Headers::new();
/// headers.set(AcceptRanges(vec![RangeUnit::None]));
/// ```
/// ```
/// use hyper::header::{Headers, AcceptRanges, RangeUnit};
///
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptRanges(vec![
/// RangeUnit::Unregistered("nibbles".to_owned()),
/// RangeUnit::Bytes,
/// RangeUnit::Unregistered("doublets".to_owned()),
/// RangeUnit::Unregistered("quadlets".to_owned()),
/// ])
/// );
/// ```
(AcceptRanges, "Accept-Ranges") => (RangeUnit)+
/// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2)
///
/// The `Accept` header field can be used by user agents to specify
/// response media types that are acceptable. Accept header fields can
/// be used to indicate that the request is specifically limited to a
/// small set of desired types, as in the case of a request for an
/// in-line image
///
/// # ABNF
/// ```plain
/// Accept = #( media-range [ accept-params ] )
///
/// media-range = ( "*/*"
/// / ( type "/" "*" )
/// / ( type "/" subtype )
/// ) *( OWS ";" OWS parameter )
/// accept-params = weight *( accept-ext )
/// accept-ext = OWS ";" OWS token [ "=" ( token / quoted-string ) ]
/// ```
///
/// # Example values
/// * `audio/*; q=0.2, audio/basic` (`*` value won't parse correctly)
/// * `text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, Accept, qitem};
/// use hyper::mime::{Mime, TopLevel, SubLevel};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// Accept(vec![
/// qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])),
/// ])
/// );
/// ```
/// ```
/// use hyper::header::{Headers, Accept, qitem};
/// use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
///
/// let mut headers = Headers::new();
/// headers.set(
/// Accept(vec![
/// qitem(Mime(TopLevel::Application, SubLevel::Json,
/// vec![(Attr::Charset, Value::Utf8)])),
/// ])
/// );
/// ```
/// ```
/// use hyper::header::{Headers, Accept, QualityItem, Quality, qitem};
/// use hyper::mime::{Mime, TopLevel, SubLevel};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// Accept(vec![
/// qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])),
/// qitem(Mime(TopLevel::Application,
/// SubLevel::Ext("xhtml+xml".to_owned()), vec![])),
/// QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]),
/// Quality(900)),
/// qitem(Mime(TopLevel::Image,
/// SubLevel::Ext("webp".to_owned()), vec![])),
/// QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]),
/// Quality(800))
/// ])
/// );
/// ```
///
/// # Notes
/// * Using always Mime types to represent `media-range` differs from the ABNF.
/// * **FIXME**: `accept-ext` is not supported.
(Accept, "Accept") => (QualityItem<Mime>)+
/// `Content-Encoding` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.2.2)
///
/// The `Content-Encoding` header field indicates what content codings
/// have been applied to the representation, beyond those inherent in the
/// media type, and thus what decoding mechanisms have to be applied in
/// order to obtain data in the media type referenced by the Content-Type
/// header field. Content-Encoding is primarily used to allow a
/// representation's data to be compressed without losing the identity of
/// its underlying media type.
///
/// # ABNF
/// ```plain
/// Content-Encoding = 1#content-coding
/// ```
///
/// # Example values
/// * `gzip`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, ContentEncoding, Encoding};
///
/// let mut headers = Headers::new();
/// headers.set(ContentEncoding(vec![Encoding::Chunked]));
/// ```
/// ```
/// use hyper::header::{Headers, ContentEncoding, Encoding};
///
/// let mut headers = Headers::new();
/// headers.set(
/// ContentEncoding(vec![
/// Encoding::Gzip,
/// Encoding::Chunked,
/// ])
/// );
/// ```
(ContentEncoding, "Content-Encoding") => (Encoding)+
/// `If-Unmodified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.4)
///
/// The `If-Unmodified-Since` header field makes the request method
/// conditional on the selected representation's last modification date
/// being earlier than or equal to the date provided in the field-value.
/// This field accomplishes the same purpose as If-Match for cases where
/// the user agent does not have an entity-tag for the representation.
///
/// # ABNF
/// ```plain
/// If-Unmodified-Since = HTTP-date
/// ```
///
/// # Example values
/// * `Sat, 29 Oct 1994 19:43:31 GMT`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate time;
/// # fn main() {
/// // extern crate time;
///
/// use hyper::header::{Headers, IfUnmodifiedSince, HttpDate};
/// use time::{self, Duration};
///
/// let mut headers = Headers::new();
/// headers.set(IfUnmodifiedSince(HttpDate(time::now() - Duration::days(1))));
/// # }
/// ```
(IfUnmodifiedSince, "If-Unmodified-Since") => [HttpDate]
/// `Location` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.2)
///
/// The `Location` header field is used in some responses to refer to a
/// specific resource in relation to the response. The type of
/// relationship is defined by the combination of request method and
/// status code semantics.
///
/// # ABNF
/// ```plain
/// Location = URI-reference
/// ```
///
/// # Example values
/// * `/People.html#tim`
/// * `http://www.example.net/index.html`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, Location};
///
/// let mut headers = Headers::new();
/// headers.set(Location("/People.html#tim".to_owned()));
/// ```
/// ```
/// use hyper::header::{Headers, Location};
///
/// let mut headers = Headers::new();
/// headers.set(Location("http://www.example.com/index.html".to_owned()));
/// ```
// TODO: Use URL
/// `Content-Language` header, defined in
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2)
///
/// The `Content-Language` header field describes the natural language(s)
/// of the intended audience for the representation. Note that this
/// might not be equivalent to all the languages used within the
/// representation.
///
/// # ABNF
/// ```plain
/// Content-Language = 1#language-tag
/// ```
///
/// # Example values
/// * `da`
/// * `mi, en`
///
/// # Examples
/// ```
/// # extern crate hyper;
/// # #[macro_use] extern crate language_tags;
/// # use hyper::header::{Headers, ContentLanguage, qitem};
/// #
/// # fn main() {
/// let mut headers = Headers::new();
/// headers.set(
/// ContentLanguage(vec![
/// qitem(langtag!(en)),
/// ])
/// );
/// # }
/// ```
/// ```
/// # extern crate hyper;
/// # #[macro_use] extern crate language_tags;
/// # use hyper::header::{Headers, ContentLanguage, qitem};
/// #
/// # fn main() {
///
/// let mut headers = Headers::new();
/// headers.set(
/// ContentLanguage(vec![
/// qitem(langtag!(da)),
/// qitem(langtag!(en;;;GB)),
/// ])
/// );
/// # }
/// ```
(ContentLanguage, "Content-Language") => (QualityItem<LanguageTag>)+
/// `Vary` header, defined in [RFC7231](https://tools.ietf.org/html/rfc7231#section-7.1.4)
///
/// The "Vary" header field in a response describes what parts of a
/// request message, aside from the method, Host header field, and
/// request target, might influence the origin server's process for
/// selecting and representing this response. The value consists of
/// either a single asterisk ("*") or a list of header field names
/// (case-insensitive).
///
/// # ABNF
/// ```plain
/// Vary = "*" / 1#field-name
/// ```
///
/// # Example values
/// * `accept-encoding, accept-language`
///
/// # Example
/// ```
/// use hyper::header::{Headers, Vary};
///
/// let mut headers = Headers::new();
/// headers.set(Vary::Any);
/// ```
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate unicase;
/// # fn main() {
/// // extern crate unicase;
///
/// use hyper::header::{Headers, Vary};
/// use unicase::UniCase;
///
/// let mut headers = Headers::new();
/// headers.set(
/// Vary::Items(vec![
/// UniCase("accept-encoding".to_owned()),
/// UniCase("accept-language".to_owned()),
/// ])
/// );
/// # }
/// ```
(Vary, "Vary") => {Any / (UniCase<String>)+}
/// `Access-Control-Request-Method` header, part of
/// [CORS](http://www.w3.org/TR/cors/#access-control-request-method-request-header)
///
/// The `Access-Control-Request-Method` header indicates which method will be
/// used in the actual request as part of the preflight request.
/// # ABNF
/// ```plain
/// Access-Control-Request-Method: \"Access-Control-Request-Method\" \":\" Method
/// ```
///
/// # Example values
/// * `GET`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AccessControlRequestMethod};
/// use hyper::method::Method;
///
/// let mut headers = Headers::new();
/// headers.set(AccessControlRequestMethod(Method::Get));
/// ```
(AccessControlRequestMethod, "Access-Control-Request-Method") => [Method]
/// Create a message stream for the given match rule.
///
/// If `conn` is a bus connection and match rule is for a signal, the match rule will be
/// registered with the bus and queued for deregistration when the stream is dropped. If you'd
/// like immediate deregistration, use [`AsyncDrop::async_drop`]. The reason match rules are
/// only registered with the bus for signals is that D-Bus specification only allows signals to
/// be broadcasted and unicast messages are always sent to their destination (regardless of any
/// match rules registered by the destination) by the bus. Hence there is no need to register
/// match rules for non-signal messages with the bus.
///
/// Having said that, stream created by this method can still very useful as it allows you to
/// avoid needless task wakeups and simplify your stream consuming code.
///
/// You can optionally also request the capacity of the underlying message queue through
/// `max_queued`. If specified, the capacity is guaranteed to be at least `max_queued`. If not
/// specified, the default of 64 is assumed. The capacity can also be changed later through
/// [`MessageStream::set_max_queued`].
///
/// # Example
///
/// ```
/// use async_io::Timer;
/// use zbus::{AsyncDrop, Connection, MatchRule, MessageStream, fdo::NameOwnerChanged};
/// use futures_util::{TryStreamExt, future::select, future::Either::{Left, Right}, pin_mut};
///
/// # zbus::block_on(async {
/// let conn = Connection::session().await?;
/// let rule = MatchRule::builder()
/// .msg_type(zbus::MessageType::Signal)
/// .sender("org.freedesktop.DBus")?
/// .interface("org.freedesktop.DBus")?
/// .member("NameOwnerChanged")?
/// .add_arg("org.freedesktop.zbus.MatchRuleStreamTest42")?
/// .build();
/// let mut stream = MessageStream::for_match_rule(
/// rule,
/// &conn,
/// // For such a specific match rule, we don't need a big queue.
/// Some(1),
/// ).await?;
///
/// let rule_str = "type='signal',sender='org.freedesktop.DBus',\
/// interface='org.freedesktop.DBus',member='NameOwnerChanged',\
/// arg0='org.freedesktop.zbus.MatchRuleStreamTest42'";
/// assert_eq!(
/// stream.match_rule().map(|r| r.to_string()).as_deref(),
/// Some(rule_str),
/// );
///
/// // We register 2 names, starting with the uninteresting one. If `stream` wasn't filtering
/// // messages based on the match rule, we'd receive method return call for each of these 2
/// // calls first.
/// //
/// // Note that the `NameOwnerChanged` signal will not be sent by the bus for the first name
/// // we register since we setup an arg filter.
/// conn.request_name("org.freedesktop.zbus.MatchRuleStreamTest44")
/// .await?;
/// conn.request_name("org.freedesktop.zbus.MatchRuleStreamTest42")
/// .await?;
///
/// let msg = stream.try_next().await?.unwrap();
/// let signal = NameOwnerChanged::from_message(msg).unwrap();
/// assert_eq!(signal.args()?.name(), "org.freedesktop.zbus.MatchRuleStreamTest42");
/// stream.async_drop().await;
///
/// // Ensure the match rule is deregistered and this connection doesn't receive
/// // `NameOwnerChanged` signals.
/// let stream = MessageStream::from(&conn).try_filter_map(|msg| async move {
/// Ok(NameOwnerChanged::from_message(msg))
/// });
/// conn.release_name("org.freedesktop.zbus.MatchRuleStreamTest42").await?;
///
/// pin_mut!(stream);
/// let next = stream.try_next();
/// pin_mut!(next);
/// let timeout = Timer::after(std::time::Duration::from_millis(50));
/// pin_mut!(timeout);
/// match select(next, timeout).await {
/// Left((msg, _)) => unreachable!("unexpected message: {:?}", msg),
/// Right((_, _)) => (),
/// }
///
/// # Ok::<(), zbus::Error>(())
/// # }).unwrap();
/// ```
///
/// # Caveats
///
/// Since this method relies on [`MatchRule::matches`], it inherits its caveats.
pub async fn for_match_rule<R>(
/// Match the given message against this rule.
///
/// # Caveats
///
/// Since this method doesn't have any knowledge of names on the bus (or even connection to a
/// bus) matching always succeeds for:
///
/// * `sender` in the rule (if set) that is a well-known name. The `sender` on a message is
/// always a unique name.
/// * `destination` in the rule when `destination` on the `msg` is a well-known name. The
/// `destination` on match rule is always a unique name.
pub fn matches(&self, msg: &zbus::Message) -> Result<bool> {
/// Executes the command as a child process, returning a handle to it.
///
/// By default, stdin, stdout and stderr are inherited from the parent.
///
/// This method will spawn the child process synchronously and return a
/// handle to a future-aware child process. The `Child` returned implements
/// `Future` itself to acquire the `ExitStatus` of the child, and otherwise
/// the `Child` has methods to acquire handles to the stdin, stdout, and
/// stderr streams.
///
/// All I/O this child does will be associated with the current default
/// event loop.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use tokio::process::Command;
///
/// async fn run_ls() -> std::process::ExitStatus {
/// Command::new("ls")
/// .spawn()
/// .expect("ls command failed to start")
/// .wait()
/// .await
/// .expect("ls command failed to run")
/// }
/// ```
///
/// # Caveats
///
/// ## Dropping/Cancellation
///
/// Similar to the behavior to the standard library, and unlike the futures
/// paradigm of dropping-implies-cancellation, a spawned process will, by
/// default, continue to execute even after the `Child` handle has been dropped.
///
/// The [`Command::kill_on_drop`] method can be used to modify this behavior
/// and kill the child process if the `Child` wrapper is dropped before it
/// has exited.
///
/// ## Unix Processes
///
/// On Unix platforms processes must be "reaped" by their parent process after
/// they have exited in order to release all OS resources. A child process which
/// has exited, but has not yet been reaped by its parent is considered a "zombie"
/// process. Such processes continue to count against limits imposed by the system,
/// and having too many zombie processes present can prevent additional processes
/// from being spawned.
///
/// The tokio runtime will, on a best-effort basis, attempt to reap and clean up
/// any process which it has spawned. No additional guarantees are made with regard to
/// how quickly or how often this procedure will take place.
///
/// It is recommended to avoid dropping a [`Child`] process handle before it has been
/// fully `await`ed if stricter cleanup guarantees are required.
///
/// [`Command`]: crate::process::Command
/// [`Command::kill_on_drop`]: crate::process::Command::kill_on_drop
/// [`Child`]: crate::process::Child
///
/// # Errors
///
/// On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
/// if the system process limit is reached (which includes other applications
/// running on the system).
pub fn spawn(&mut self) -> io::Result<Child> {
/// Notifies a number of active listeners.
///
/// The number is allowed to be zero or exceed the current number of listeners.
///
/// The [`Notification`] trait is used to define what kind of notification is delivered.
/// The default implementation (implemented on `usize`) is a notification that only notifies
/// *at least* the specified number of listeners.
///
/// In certain cases, this function emits a `SeqCst` fence before notifying listeners.
///
/// This function returns the number of [`EventListener`]s that were notified by this call.
///
/// # Caveats
///
/// If the `std` feature is disabled, the notification will be delayed under high contention,
/// such as when another thread is taking a while to `notify` the event. In this circumstance,
/// this function will return `0` instead of the number of listeners actually notified. Therefore
/// if the `std` feature is disabled the return value of this function should not be relied upon
/// for soundness and should be used only as a hint.
///
/// If the `std` feature is enabled, no spurious returns are possible, since the `std`
/// implementation uses system locking primitives to ensure there is no unavoidable
/// contention.
///
/// # Examples
///
/// Use the default notification strategy:
///
/// ```
/// use event_listener::Event;
///
/// let event = Event::new();
///
/// // This notification gets lost because there are no listeners.
/// event.notify(1);
///
/// let listener1 = event.listen();
/// let listener2 = event.listen();
/// let listener3 = event.listen();
///
/// // Notifies two listeners.
/// //
/// // Listener queueing is fair, which means `listener1` and `listener2`
/// // get notified here since they start listening before `listener3`.
/// event.notify(2);
/// ```
///
/// Notify without emitting a `SeqCst` fence. This uses the [`relaxed`] notification strategy.
/// This is equivalent to calling [`Event::notify_relaxed()`].
///
/// [`relaxed`]: IntoNotification::relaxed
///
/// ```
/// use event_listener::{prelude::*, Event};
/// use std::sync::atomic::{self, Ordering};
///
/// let event = Event::new();
///
/// // This notification gets lost because there are no listeners.
/// event.notify(1.relaxed());
///
/// let listener1 = event.listen();
/// let listener2 = event.listen();
/// let listener3 = event.listen();
///
/// // We should emit a fence manually when using relaxed notifications.
/// atomic::fence(Ordering::SeqCst);
///
/// // Notifies two listeners.
/// //
/// // Listener queueing is fair, which means `listener1` and `listener2`
/// // get notified here since they start listening before `listener3`.
/// event.notify(2.relaxed());
/// ```
///
/// Notify additional listeners. In contrast to [`Event::notify()`], this method will notify `n`
/// *additional* listeners that were previously unnotified. This uses the [`additional`]
/// notification strategy. This is equivalent to calling [`Event::notify_additional()`].
///
/// [`additional`]: IntoNotification::additional
///
/// ```
/// use event_listener::{prelude::*, Event};
///
/// let event = Event::new();
///
/// // This notification gets lost because there are no listeners.
/// event.notify(1.additional());
///
/// let listener1 = event.listen();
/// let listener2 = event.listen();
/// let listener3 = event.listen();
///
/// // Notifies two listeners.
/// //
/// // Listener queueing is fair, which means `listener1` and `listener2`
/// // get notified here since they start listening before `listener3`.
/// event.notify(1.additional());
/// event.notify(1.additional());
/// ```
///
/// Notifies with the [`additional`] and [`relaxed`] strategies at the same time. This is
/// equivalent to calling [`Event::notify_additional_relaxed()`].
///
/// ```
/// use event_listener::{prelude::*, Event};
/// use std::sync::atomic::{self, Ordering};
///
/// let event = Event::new();
///
/// // This notification gets lost because there are no listeners.
/// event.notify(1.additional().relaxed());
///
/// let listener1 = event.listen();
/// let listener2 = event.listen();
/// let listener3 = event.listen();
///
/// // We should emit a fence manually when using relaxed notifications.
/// atomic::fence(Ordering::SeqCst);
///
/// // Notifies two listeners.
/// //
/// // Listener queueing is fair, which means `listener1` and `listener2`
/// // get notified here since they start listening before `listener3`.
/// event.notify(1.additional().relaxed());
/// event.notify(1.additional().relaxed());
/// ```
#[inline]
/// Notifies a number of active listeners.
///
/// The number is allowed to be zero or exceed the current number of listeners.
///
/// The [`Notification`] trait is used to define what kind of notification is delivered.
/// The default implementation (implemented on `usize`) is a notification that only notifies
/// *at least* the specified number of listeners.
///
/// In certain cases, this function emits a `SeqCst` fence before notifying listeners.
///
/// This function returns the number of [`EventListener`]s that were notified by this call.
///
/// # Caveats
///
/// If the `std` feature is disabled, the notification will be delayed under high contention,
/// such as when another thread is taking a while to `notify` the event. In this circumstance,
/// this function will return `0` instead of the number of listeners actually notified. Therefore
/// if the `std` feature is disabled the return value of this function should not be relied upon
/// for soundness and should be used only as a hint.
///
/// If the `std` feature is enabled, no spurious returns are possible, since the `std`
/// implementation uses system locking primitives to ensure there is no unavoidable
/// contention.
///
/// # Examples
///
/// Use the default notification strategy:
///
/// ```
/// use event_listener::Event;
///
/// let event = Event::new();
///
/// // This notification gets lost because there are no listeners.
/// event.notify(1);
///
/// let listener1 = event.listen();
/// let listener2 = event.listen();
/// let listener3 = event.listen();
///
/// // Notifies two listeners.
/// //
/// // Listener queueing is fair, which means `listener1` and `listener2`
/// // get notified here since they start listening before `listener3`.
/// event.notify(2);
/// ```
///
/// Notify without emitting a `SeqCst` fence. This uses the [`relaxed`] notification strategy.
/// This is equivalent to calling [`Event::notify_relaxed()`].
///
/// [`relaxed`]: IntoNotification::relaxed
///
/// ```
/// use event_listener::{IntoNotification, Event};
/// use std::sync::atomic::{self, Ordering};
///
/// let event = Event::new();
///
/// // This notification gets lost because there are no listeners.
/// event.notify(1.relaxed());
///
/// let listener1 = event.listen();
/// let listener2 = event.listen();
/// let listener3 = event.listen();
///
/// // We should emit a fence manually when using relaxed notifications.
/// atomic::fence(Ordering::SeqCst);
///
/// // Notifies two listeners.
/// //
/// // Listener queueing is fair, which means `listener1` and `listener2`
/// // get notified here since they start listening before `listener3`.
/// event.notify(2.relaxed());
/// ```
///
/// Notify additional listeners. In contrast to [`Event::notify()`], this method will notify `n`
/// *additional* listeners that were previously unnotified. This uses the [`additional`]
/// notification strategy. This is equivalent to calling [`Event::notify_additional()`].
///
/// [`additional`]: IntoNotification::additional
///
/// ```
/// use event_listener::{IntoNotification, Event};
///
/// let event = Event::new();
///
/// // This notification gets lost because there are no listeners.
/// event.notify(1.additional());
///
/// let listener1 = event.listen();
/// let listener2 = event.listen();
/// let listener3 = event.listen();
///
/// // Notifies two listeners.
/// //
/// // Listener queueing is fair, which means `listener1` and `listener2`
/// // get notified here since they start listening before `listener3`.
/// event.notify(1.additional());
/// event.notify(1.additional());
/// ```
///
/// Notifies with the [`additional`] and [`relaxed`] strategies at the same time. This is
/// equivalent to calling [`Event::notify_additional_relaxed()`].
///
/// ```
/// use event_listener::{IntoNotification, Event};
/// use std::sync::atomic::{self, Ordering};
///
/// let event = Event::new();
///
/// // This notification gets lost because there are no listeners.
/// event.notify(1.additional().relaxed());
///
/// let listener1 = event.listen();
/// let listener2 = event.listen();
/// let listener3 = event.listen();
///
/// // We should emit a fence manually when using relaxed notifications.
/// atomic::fence(Ordering::SeqCst);
///
/// // Notifies two listeners.
/// //
/// // Listener queueing is fair, which means `listener1` and `listener2`
/// // get notified here since they start listening before `listener3`.
/// event.notify(1.additional().relaxed());
/// event.notify(1.additional().relaxed());
/// ```
#[inline]
/// Controls whether a `kill` operation should be invoked on a spawned child
/// process when its corresponding `Child` handle is dropped.
///
/// By default, this value is assumed to be `false`, meaning the next spawned
/// process will not be killed on drop, similar to the behavior of the standard
/// library.
///
/// # Caveats
///
/// On Unix platforms processes must be "reaped" by their parent process after
/// they have exited in order to release all OS resources. A child process which
/// has exited, but has not yet been reaped by its parent is considered a "zombie"
/// process. Such processes continue to count against limits imposed by the system,
/// and having too many zombie processes present can prevent additional processes
/// from being spawned.
///
/// Although issuing a `kill` signal to the child process is a synchronous
/// operation, the resulting zombie process cannot be `.await`ed inside of the
/// destructor to avoid blocking other tasks. The tokio runtime will, on a
/// best-effort basis, attempt to reap and clean up such processes in the
/// background, but no additional guarantees are made with regard to
/// how quickly or how often this procedure will take place.
///
/// If stronger guarantees are required, it is recommended to avoid dropping
/// a [`Child`] handle where possible, and instead utilize `child.wait().await`
/// or `child.kill().await` where possible.
pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Command {
/// Create a message iterator for the given match rule.
///
/// This is a wrapper around [`crate::MessageStream::for_match_rule`]. Unlike the underlying
/// `MessageStream`, the match rule is immediately deregistered when the iterator is dropped.
///
/// # Example
///
/// ```
/// use zbus::{blocking::{Connection, MessageIterator}, MatchRule, fdo::NameOwnerChanged};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let conn = Connection::session()?;
/// let rule = MatchRule::builder()
/// .msg_type(zbus::MessageType::Signal)
/// .sender("org.freedesktop.DBus")?
/// .interface("org.freedesktop.DBus")?
/// .member("NameOwnerChanged")?
/// .add_arg("org.freedesktop.zbus.MatchRuleIteratorTest42")?
/// .build();
/// let mut iter = MessageIterator::for_match_rule(
/// rule,
/// &conn,
/// // For such a specific match rule, we don't need a big queue.
/// Some(1),
/// )?;
///
/// let rule_str = "type='signal',sender='org.freedesktop.DBus',\
/// interface='org.freedesktop.DBus',member='NameOwnerChanged',\
/// arg0='org.freedesktop.zbus.MatchRuleIteratorTest42'";
/// assert_eq!(
/// iter.match_rule().map(|r| r.to_string()).as_deref(),
/// Some(rule_str),
/// );
///
/// // We register 2 names, starting with the uninteresting one. If `iter` wasn't filtering
/// // messages based on the match rule, we'd receive method return call for each of these 2
/// // calls first.
/// //
/// // Note that the `NameOwnerChanged` signal will not be sent by the bus for the first name
/// // we register since we setup an arg filter.
/// conn.request_name("org.freedesktop.zbus.MatchRuleIteratorTest44")?;
/// conn.request_name("org.freedesktop.zbus.MatchRuleIteratorTest42")?;
///
/// let msg = iter.next().unwrap()?;
/// let signal = NameOwnerChanged::from_message(msg).unwrap();
/// assert_eq!(signal.args()?.name(), "org.freedesktop.zbus.MatchRuleIteratorTest42");
///
/// # Ok(())
/// # }
/// ```
///
/// # Caveats
///
/// Since this method relies on [`MatchRule::matches`], it inherits its caveats.
pub fn for_match_rule<R>(rule: R, conn: &Connection, max_queued: Option<usize>) -> Result<Self>
/// Low level API to directly bind a parameter to a given index.
///
/// Note that the index is one-based, that is, the first parameter index is
/// 1 and not 0. This is consistent with the SQLite API and the values given
/// to parameters bound as `?NNN`.
///
/// The valid values for `one_based_col_index` begin at `1`, and end at
/// [`Statement::parameter_count`], inclusive.
///
/// # Caveats
///
/// This should not generally be used, but is available for special cases
/// such as:
///
/// - binding parameters where a gap exists.
/// - binding named and positional parameters in the same query.
/// - separating parameter binding from query execution.
///
/// In general, statements that have had *any* parameters bound this way
/// should have *all* parameters bound this way, and be queried or executed
/// by [`Statement::raw_query`] or [`Statement::raw_execute`], other usage
/// is unsupported and will likely, probably in surprising ways.
///
/// That is: Do not mix the "raw" statement functions with the rest of the
/// API, or the results may be surprising, and may even change in future
/// versions without comment.
///
/// # Example
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// fn query(conn: &Connection) -> Result<()> {
/// let mut stmt = conn.prepare("SELECT * FROM test WHERE name = :name AND value > ?2")?;
/// let name_index = stmt.parameter_index(":name")?.expect("No such parameter");
/// stmt.raw_bind_parameter(name_index, "foo")?;
/// stmt.raw_bind_parameter(2, 100)?;
/// let mut rows = stmt.raw_query();
/// while let Some(row) = rows.next()? {
/// // ...
/// }
/// Ok(())
/// }
/// ```
#[inline]
/// Returns a list of the type parameters which are referenced in this
/// field's type.
///
/// # Caveat
///
/// If the field contains any macros in type position, all parameters will
/// be considered bound. This is because we cannot determine which type
/// parameters are bound by type macros.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// struct A<T, U> {
/// a: Option<T>,
/// b: U,
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// assert_eq!(
/// s.variants()[0].bindings()[0].referenced_ty_params(),
/// &["e::format_ident!("T")]
/// );
/// ```
pub fn referenced_ty_params(&self) -> Vec<&'a Ident> {
/// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
///
/// Creates an `impl` block with the required generic type fields filled in
/// to implement the unsafe trait `path`.
///
/// This method also adds where clauses to the impl requiring that all
/// referenced type parmaeters implement the trait `path`.
///
/// # Hygiene and Paths
///
/// This method wraps the impl block inside of a `const` (see the example
/// below). In this scope, the first segment of the passed-in path is
/// `extern crate`-ed in. If you don't want to generate that `extern crate`
/// item, use a global path.
///
/// This means that if you are implementing `my_crate::Trait`, you simply
/// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
/// entirety of the definition, you can refer to your crate as `my_crate`.
///
/// # Caveat
///
/// If the method contains any macros in type position, all parameters will
/// be considered bound. This is because we cannot determine which type
/// parameters are bound by type macros.
///
/// # Panics
///
/// Panics if the path string parameter is not a valid `TraitBound`.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A<T, U> {
/// B(T),
/// C(Option<U>),
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.filter_variants(|v| v.ast().ident != "B");
///
/// assert_eq!(
/// s.unsafe_bound_impl(quote!(krate::Trait), quote!{
/// fn a() {}
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// #[doc(hidden)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// unsafe impl<T, U> krate::Trait for A<T, U>
/// where Option<U>: krate::Trait,
/// U: krate::Trait
/// {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
/// ```
pub fn unsafe_bound_impl<P: ToTokens, B: ToTokens>(&self, path: P, body: B) -> TokenStream {
/// Returns the peer credentials.
///
/// The fields are populated on the best effort basis. Some or all fields may not even make
/// sense for certain sockets or on certain platforms and hence will be set to `None`.
///
/// # Caveats
///
/// Currently `unix_group_ids` and `linux_security_label` fields are not populated.
#[allow(deprecated)]
/// Controls whether a `kill` operation should be invoked on a spawned child
/// process when its corresponding `Child` handle is dropped.
///
/// By default, this value is assumed to be `false`, meaning the next spawned
/// process will not be killed on drop, similar to the behavior of the standard
/// library.
///
/// # Caveats
///
/// On Unix platforms processes must be "reaped" by their parent process after
/// they have exited in order to release all OS resources. A child process which
/// has exited, but has not yet been reaped by its parent is considered a "zombie"
/// process. Such processes continue to count against limits imposed by the system,
/// and having too many zombie processes present can prevent additional processes
/// from being spawned.
///
/// Although issuing a `kill` signal to the child process is a synchronous
/// operation, the resulting zombie process cannot be `.await`ed inside of the
/// destructor to avoid blocking other tasks. The tokio runtime will, on a
/// best-effort basis, attempt to reap and clean up such processes in the
/// background, but makes no additional guarantees are made with regards
/// how quickly or how often this procedure will take place.
///
/// If stronger guarantees are required, it is recommended to avoid dropping
/// a [`Child`] handle where possible, and instead utilize `child.wait().await`
/// or `child.kill().await` where possible.
pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Command {
/// Executes the command as a child process, returning a handle to it.
///
/// By default, stdin, stdout and stderr are inherited from the parent.
///
/// This method will spawn the child process synchronously and return a
/// handle to a future-aware child process. The `Child` returned implements
/// `Future` itself to acquire the `ExitStatus` of the child, and otherwise
/// the `Child` has methods to acquire handles to the stdin, stdout, and
/// stderr streams.
///
/// All I/O this child does will be associated with the current default
/// event loop.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use tokio::process::Command;
///
/// async fn run_ls() -> std::process::ExitStatus {
/// Command::new("ls")
/// .spawn()
/// .expect("ls command failed to start")
/// .wait()
/// .await
/// .expect("ls command failed to run")
/// }
/// ```
///
/// # Caveats
///
/// ## Dropping/Cancellation
///
/// Similar to the behavior to the standard library, and unlike the futures
/// paradigm of dropping-implies-cancellation, a spawned process will, by
/// default, continue to execute even after the `Child` handle has been dropped.
///
/// The [`Command::kill_on_drop`] method can be used to modify this behavior
/// and kill the child process if the `Child` wrapper is dropped before it
/// has exited.
///
/// ## Unix Processes
///
/// On Unix platforms processes must be "reaped" by their parent process after
/// they have exited in order to release all OS resources. A child process which
/// has exited, but has not yet been reaped by its parent is considered a "zombie"
/// process. Such processes continue to count against limits imposed by the system,
/// and having too many zombie processes present can prevent additional processes
/// from being spawned.
///
/// The tokio runtime will, on a best-effort basis, attempt to reap and clean up
/// any process which it has spawned. No additional guarantees are made with regards
/// how quickly or how often this procedure will take place.
///
/// It is recommended to avoid dropping a [`Child`] process handle before it has been
/// fully `await`ed if stricter cleanup guarantees are required.
///
/// [`Command`]: crate::process::Command
/// [`Command::kill_on_drop`]: crate::process::Command::kill_on_drop
/// [`Child`]: crate::process::Child
///
/// # Errors
///
/// On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
/// if the system process limit is reached (which includes other applications
/// running on the system).
pub fn spawn(&mut self) -> io::Result<Child> {
/// Polls the I/O handle for writability.
///
/// When this method returns [`Poll::Ready`], that means the OS has delivered an event
/// indicating writability since the last time this task has called the method and received
/// [`Poll::Pending`].
///
/// # Caveats
///
/// Two different tasks should not call this method concurrently. Otherwise, conflicting tasks
/// will just keep waking each other in turn, thus wasting CPU time.
///
/// Note that the [`AsyncWrite`] implementation for [`Async`] also uses this method.
///
/// # Examples
///
/// ```
/// use async_io::Async;
/// use futures_lite::future;
/// use std::net::{TcpStream, ToSocketAddrs};
///
/// # futures_lite::future::block_on(async {
/// let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
/// let stream = Async::<TcpStream>::connect(addr).await?;
///
/// // Wait until the stream is writable.
/// future::poll_fn(|cx| stream.poll_writable(cx)).await?;
/// # std::io::Result::Ok(()) });
/// ```
pub fn poll_writable(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
/// Low level API to execute a statement given that all parameters were
/// bound explicitly with the [`Statement::raw_bind_parameter`] API.
///
/// # Caveats
///
/// Any unbound parameters will have `NULL` as their value.
///
/// This should not generally be used outside of special cases, and
/// functions in the [`Statement::execute`] family should be preferred.
///
/// # Failure
///
/// Will return `Err` if the executed statement returns rows (in which case
/// `query` should be used instead), or the underlying SQLite call fails.
#[inline]
/// Wraps a raw C string with a safe C string wrapper.
///
/// This function will wrap the provided `ptr` with a `CStr` wrapper, which
/// allows inspection and interoperation of non-owned C strings. The total
/// size of the terminated buffer must be smaller than [`isize::MAX`] **bytes**
/// in memory (a restriction from [`slice::from_raw_parts`]).
///
/// # Safety
///
/// * The memory pointed to by `ptr` must contain a valid nul terminator at the
/// end of the string.
///
/// * `ptr` must be [valid] for reads of bytes up to and including the nul terminator.
/// This means in particular:
///
/// * The entire memory range of this `CStr` must be contained within a single allocated object!
/// * `ptr` must be non-null even for a zero-length cstr.
///
/// * The memory referenced by the returned `CStr` must not be mutated for
/// the duration of lifetime `'a`.
///
/// * The nul terminator must be within `isize::MAX` from `ptr`
///
/// > **Note**: This operation is intended to be a 0-cost cast but it is
/// > currently implemented with an up-front calculation of the length of
/// > the string. This is not guaranteed to always be the case.
///
/// # Caveat
///
/// The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse,
/// it's suggested to tie the lifetime to whichever source lifetime is safe in the context,
/// such as by providing a helper function taking the lifetime of a host value for the slice,
/// or by explicit annotation.
///
/// # Examples
///
/// ```ignore (extern-declaration)
/// use std::ffi::{c_char, CStr};
///
/// extern "C" {
/// fn my_string() -> *const c_char;
/// }
///
/// unsafe {
/// let slice = CStr::from_ptr(my_string());
/// println!("string returned: {}", slice.to_str().unwrap());
/// }
/// ```
///
/// ```
/// #![feature(const_cstr_from_ptr)]
///
/// use std::ffi::{c_char, CStr};
///
/// const HELLO_PTR: *const c_char = {
/// const BYTES: &[u8] = b"Hello, world!\0";
/// BYTES.as_ptr().cast()
/// };
/// const HELLO: &CStr = unsafe { CStr::from_ptr(HELLO_PTR) };
/// ```
///
/// [valid]: core::ptr#safety
#[inline] // inline is necessary for codegen to see strlen.
/// Returns a guard listening for a notification.
///
/// This method emits a `SeqCst` fence after registering a listener. For now, this method
/// is an alias for calling [`EventListener::new()`], pinning it to the heap, and then
/// inserting it into a list.
///
/// # Examples
///
/// ```
/// use event_listener::Event;
///
/// let event = Event::new();
/// let listener = event.listen();
/// ```
///
/// # Caveats
///
/// The above example is equivalent to this code:
///
/// ```no_compile
/// use event_listener::{Event, EventListener};
///
/// let event = Event::new();
/// let mut listener = Box::pin(EventListener::new());
/// listener.listen(&event);
/// ```
///
/// It creates a new listener, pins it to the heap, and inserts it into the linked list
/// of listeners. While this type of usage is simple, it may be desired to eliminate this
/// heap allocation. In this case, consider using the [`EventListener::new`] constructor
/// directly, which allows for greater control over where the [`EventListener`] is
/// allocated. However, users of this `new` method must be careful to ensure that the
/// [`EventListener`] is `listen`ing before waiting on it; panics may occur otherwise.
#[cold]
/// Executes the command as a child process, returning a handle to it.
///
/// By default, stdin, stdout and stderr are inherited from the parent.
///
/// This method will spawn the child process synchronously and return a
/// handle to a future-aware child process. The `Child` returned implements
/// `Future` itself to acquire the `ExitStatus` of the child, and otherwise
/// the `Child` has methods to acquire handles to the stdin, stdout, and
/// stderr streams.
///
/// All I/O this child does will be associated with the current default
/// event loop.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use tokio::process::Command;
///
/// async fn run_ls() -> std::process::ExitStatus {
/// Command::new("ls")
/// .spawn()
/// .expect("ls command failed to start")
/// .wait()
/// .await
/// .expect("ls command failed to run")
/// }
/// ```
///
/// # Caveats
///
/// ## Dropping/Cancellation
///
/// Similar to the behavior to the standard library, and unlike the futures
/// paradigm of dropping-implies-cancellation, a spawned process will, by
/// default, continue to execute even after the `Child` handle has been dropped.
///
/// The [`Command::kill_on_drop`] method can be used to modify this behavior
/// and kill the child process if the `Child` wrapper is dropped before it
/// has exited.
///
/// ## Unix Processes
///
/// On Unix platforms processes must be "reaped" by their parent process after
/// they have exited in order to release all OS resources. A child process which
/// has exited, but has not yet been reaped by its parent is considered a "zombie"
/// process. Such processes continue to count against limits imposed by the system,
/// and having too many zombie processes present can prevent additional processes
/// from being spawned.
///
/// The tokio runtime will, on a best-effort basis, attempt to reap and clean up
/// any process which it has spawned. No additional guarantees are made with regard to
/// how quickly or how often this procedure will take place.
///
/// It is recommended to avoid dropping a [`Child`] process handle before it has been
/// fully `await`ed if stricter cleanup guarantees are required.
///
/// [`Command`]: crate::process::Command
/// [`Command::kill_on_drop`]: crate::process::Command::kill_on_drop
/// [`Child`]: crate::process::Child
///
/// # Errors
///
/// On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
/// if the system process limit is reached (which includes other applications
/// running on the system).
pub fn spawn(&mut self) -> io::Result<Child> {
/// Returns a guard listening for a notification.
///
/// This method emits a `SeqCst` fence after registering a listener. For now, this method
/// is an alias for calling [`EventListener::new()`], pinning it to the heap, and then
/// inserting it into a list.
///
/// # Examples
///
/// ```
/// use event_listener::Event;
///
/// let event = Event::new();
/// let listener = event.listen();
/// ```
///
/// # Caveats
///
/// The above example is equivalent to this code:
///
/// ```
/// use event_listener::{Event, EventListener};
///
/// let event = Event::new();
/// let mut listener = Box::pin(EventListener::new());
/// listener.as_mut().listen(&event);
/// ```
///
/// It creates a new listener, pins it to the heap, and inserts it into the linked list
/// of listeners. While this type of usage is simple, it may be desired to eliminate this
/// heap allocation. In this case, consider using the [`EventListener::new`] constructor
/// directly, which allows for greater control over where the [`EventListener`] is
/// allocated. However, users of this `new` method must be careful to ensure that the
/// [`EventListener`] is `listen`ing before waiting on it; panics may occur otherwise.
#[cold]
/// Get the number of listeners currently listening to this [`Event`].
///
/// This call returns the number of [`EventListener`]s that are currently listening to
/// this event. It does this by acquiring the internal event lock and reading the listener
/// count. Therefore it is only available for `std`-enabled platforms.
///
/// # Caveats
///
/// This function returns just a snapshot of the number of listeners at this point in time.
/// Due to the nature of multi-threaded CPUs, it is possible that this number will be
/// inaccurate by the time that this function returns.
///
/// It is possible for the actual number to change at any point. Therefore, the number should
/// only ever be used as a hint.
///
/// # Examples
///
/// ```
/// use event_listener::Event;
///
/// let event = Event::new();
///
/// assert_eq!(event.total_listeners(), 0);
///
/// let listener1 = event.listen();
/// assert_eq!(event.total_listeners(), 1);
///
/// let listener2 = event.listen();
/// assert_eq!(event.total_listeners(), 2);
///
/// drop(listener1);
/// drop(listener2);
/// assert_eq!(event.total_listeners(), 0);
/// ```
#[cfg(feature = "std")]
/// Updates [`self.extension`] to `Some(extension)` or to `None` if
/// `extension` is empty.
///
/// Returns `false` and does nothing if [`self.file_name`] is [`None`],
/// returns `true` and updates the extension otherwise.
///
/// If [`self.extension`] is [`None`], the extension is added; otherwise
/// it is replaced.
///
/// If `extension` is the empty string, [`self.extension`] will be [`None`]
/// afterwards, not `Some("")`.
///
/// # Caveats
///
/// The new `extension` may contain dots and will be used in its entirety,
/// but only the part after the final dot will be reflected in
/// [`self.extension`].
///
/// If the file stem contains internal dots and `extension` is empty, part
/// of the old file stem will be considered the new [`self.extension`].
///
/// See the examples below.
///
/// [`self.file_name`]: Path::file_name
/// [`self.extension`]: Path::extension
///
/// # Examples
///
/// ```
/// use std::path::{Path, PathBuf};
///
/// let mut p = PathBuf::from("/feel/the");
///
/// p.set_extension("force");
/// assert_eq!(Path::new("/feel/the.force"), p.as_path());
///
/// p.set_extension("dark.side");
/// assert_eq!(Path::new("/feel/the.dark.side"), p.as_path());
///
/// p.set_extension("cookie");
/// assert_eq!(Path::new("/feel/the.dark.cookie"), p.as_path());
///
/// p.set_extension("");
/// assert_eq!(Path::new("/feel/the.dark"), p.as_path());
///
/// p.set_extension("");
/// assert_eq!(Path::new("/feel/the"), p.as_path());
///
/// p.set_extension("");
/// assert_eq!(Path::new("/feel/the"), p.as_path());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// The database is opened in read-only mode.
/// If the database does not already exist, an error is returned.
const SQLITE_OPEN_READ_ONLY = ffi::SQLITE_OPEN_READONLY;
/// The database is opened for reading and writing if possible,
/// or reading only if the file is write protected by the operating system.
/// In either case the database must already exist, otherwise an error is returned.
const SQLITE_OPEN_READ_WRITE = ffi::SQLITE_OPEN_READWRITE;
/// The database is created if it does not already exist
const SQLITE_OPEN_CREATE = ffi::SQLITE_OPEN_CREATE;
/// The filename can be interpreted as a URI if this flag is set.
const SQLITE_OPEN_URI = ffi::SQLITE_OPEN_URI;
/// The database will be opened as an in-memory database.
const SQLITE_OPEN_MEMORY = ffi::SQLITE_OPEN_MEMORY;
/// The new database connection will not use a per-connection mutex (the
/// connection will use the "multi-thread" threading mode, in SQLite
/// parlance).
///
/// This is used by default, as proper `Send`/`Sync` usage (in
/// particular, the fact that [`Connection`] does not implement `Sync`)
/// ensures thread-safety without the need to perform locking around all
/// calls.
const SQLITE_OPEN_NO_MUTEX = ffi::SQLITE_OPEN_NOMUTEX;
/// The new database connection will use a per-connection mutex -- the
/// "serialized" threading mode, in SQLite parlance.
///
/// # Caveats
///
/// This flag should probably never be used with `rusqlite`, as we
/// ensure thread-safety statically (we implement [`Send`] and not
/// [`Sync`]). That said
///
/// Critically, even if this flag is used, the [`Connection`] is not
/// safe to use across multiple threads simultaneously. To access a
/// database from multiple threads, you should either create multiple
/// connections, one for each thread (if you have very many threads,
/// wrapping the `rusqlite::Connection` in a mutex is also reasonable).
///
/// This is both because of the additional per-connection state stored
/// by `rusqlite` (for example, the prepared statement cache), and
/// because not all of SQLites functions are fully thread safe, even in
/// serialized/`SQLITE_OPEN_FULLMUTEX` mode.
///
/// All that said, it's fairly harmless to enable this flag with
/// `rusqlite`, it will just slow things down while providing no
/// benefit.
const SQLITE_OPEN_FULL_MUTEX = ffi::SQLITE_OPEN_FULLMUTEX;
/// The database is opened with shared cache enabled.
///
/// This is frequently useful for in-memory connections, but note that
/// broadly speaking it's discouraged by SQLite itself, which states
/// "Any use of shared cache is discouraged" in the official
/// [documentation](https://www.sqlite.org/c3ref/enable_shared_cache.html).
const SQLITE_OPEN_SHARED_CACHE = 0x0002_0000;
/// The database is opened shared cache disabled.
const SQLITE_OPEN_PRIVATE_CACHE = 0x0004_0000;
/// The database filename is not allowed to be a symbolic link. (3.31.0)
const SQLITE_OPEN_NOFOLLOW = 0x0100_0000;
/// Extended result codes. (3.37.0)
const SQLITE_OPEN_EXRESCODE = 0x0200_0000;
/// Low level API to get `Rows` for this query given that all parameters
/// were bound explicitly with the [`Statement::raw_bind_parameter`] API.
///
/// # Caveats
///
/// Any unbound parameters will have `NULL` as their value.
///
/// This should not generally be used outside of special cases, and
/// functions in the [`Statement::query`] family should be preferred.
///
/// Note that if the SQL does not return results, [`Statement::raw_execute`]
/// should be used instead.
#[inline]
/// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
///
/// Creates an `impl` block with the required generic type fields filled in
/// to implement the trait `path`.
///
/// This method also adds where clauses to the impl requiring that all
/// referenced type parmaeters implement the trait `path`.
///
/// # Hygiene and Paths
///
/// This method wraps the impl block inside of a `const` (see the example
/// below). In this scope, the first segment of the passed-in path is
/// `extern crate`-ed in. If you don't want to generate that `extern crate`
/// item, use a global path.
///
/// This means that if you are implementing `my_crate::Trait`, you simply
/// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
/// entirety of the definition, you can refer to your crate as `my_crate`.
///
/// # Caveat
///
/// If the method contains any macros in type position, all parameters will
/// be considered bound. This is because we cannot determine which type
/// parameters are bound by type macros.
///
/// # Panics
///
/// Panics if the path string parameter is not a valid `TraitBound`.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A<T, U> {
/// B(T),
/// C(Option<U>),
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.filter_variants(|v| v.ast().ident != "B");
///
/// assert_eq!(
/// s.bound_impl(quote!(krate::Trait), quote!{
/// fn a() {}
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// #[doc(hidden)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// impl<T, U> krate::Trait for A<T, U>
/// where Option<U>: krate::Trait,
/// U: krate::Trait
/// {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
/// ```
pub fn bound_impl<P: ToTokens, B: ToTokens>(&self, path: P, body: B) -> TokenStream {
/// Executes the command as a child process, returning a handle to it.
///
/// By default, stdin, stdout and stderr are inherited from the parent.
///
/// This method will spawn the child process synchronously and return a
/// handle to a future-aware child process. The `Child` returned implements
/// `Future` itself to acquire the `ExitStatus` of the child, and otherwise
/// the `Child` has methods to acquire handles to the stdin, stdout, and
/// stderr streams.
///
/// All I/O this child does will be associated with the current default
/// event loop.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use tokio::process::Command;
///
/// async fn run_ls() -> std::process::ExitStatus {
/// Command::new("ls")
/// .spawn()
/// .expect("ls command failed to start")
/// .wait()
/// .await
/// .expect("ls command failed to run")
/// }
/// ```
///
/// # Caveats
///
/// ## Dropping/Cancellation
///
/// Similar to the behavior to the standard library, and unlike the futures
/// paradigm of dropping-implies-cancellation, a spawned process will, by
/// default, continue to execute even after the `Child` handle has been dropped.
///
/// The [`Command::kill_on_drop`] method can be used to modify this behavior
/// and kill the child process if the `Child` wrapper is dropped before it
/// has exited.
///
/// ## Unix Processes
///
/// On Unix platforms processes must be "reaped" by their parent process after
/// they have exited in order to release all OS resources. A child process which
/// has exited, but has not yet been reaped by its parent is considered a "zombie"
/// process. Such processes continue to count against limits imposed by the system,
/// and having too many zombie processes present can prevent additional processes
/// from being spawned.
///
/// The tokio runtime will, on a best-effort basis, attempt to reap and clean up
/// any process which it has spawned. No additional guarantees are made with regards
/// how quickly or how often this procedure will take place.
///
/// It is recommended to avoid dropping a [`Child`] process handle before it has been
/// fully `await`ed if stricter cleanup guarantees are required.
///
/// [`Command`]: crate::process::Command
/// [`Command::kill_on_drop`]: crate::process::Command::kill_on_drop
/// [`Child`]: crate::process::Child
///
/// # Errors
///
/// On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
/// if the system process limit is reached (which includes other applications
/// running on the system).
pub fn spawn(&mut self) -> io::Result<Child> {
/// Controls whether a `kill` operation should be invoked on a spawned child
/// process when its corresponding `Child` handle is dropped.
///
/// By default, this value is assumed to be `false`, meaning the next spawned
/// process will not be killed on drop, similar to the behavior of the standard
/// library.
///
/// # Caveats
///
/// On Unix platforms processes must be "reaped" by their parent process after
/// they have exited in order to release all OS resources. A child process which
/// has exited, but has not yet been reaped by its parent is considered a "zombie"
/// process. Such processes continue to count against limits imposed by the system,
/// and having too many zombie processes present can prevent additional processes
/// from being spawned.
///
/// Although issuing a `kill` signal to the child process is a synchronous
/// operation, the resulting zombie process cannot be `.await`ed inside of the
/// destructor to avoid blocking other tasks. The tokio runtime will, on a
/// best-effort basis, attempt to reap and clean up such processes in the
/// background, but makes no additional guarantees are made with regards
/// how quickly or how often this procedure will take place.
///
/// If stronger guarantees are required, it is recommended to avoid dropping
/// a [`Child`] handle where possible, and instead utilize `child.wait().await`
/// or `child.kill().await` where possible.
pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Command {
/// Returns an iterator over all objects.
///
/// # Caveat
///
/// Every object that is inserted at the moment this function is called and persists at least
/// until the end of iteration will be returned. Since this iterator traverses a lock-free
/// linked list that may be concurrently modified, some additional caveats apply:
///
/// 1. If a new object is inserted during iteration, it may or may not be returned.
/// 2. If an object is deleted during iteration, it may or may not be returned.
/// 3. The iteration may be aborted when it lost in a race condition. In this case, the winning
/// thread will continue to iterate over the same list.
pub(crate) fn iter<'g>(&'g self, guard: &'g Guard) -> Iter<'g, T, C> {
/// Register a well-known name for this connection.
///
/// When connecting to a bus, the name is requested from the bus. In case of p2p connection, the
/// name (if requested) is used of self-identification.
///
/// You can request multiple names for the same connection. Use [`Connection::release_name`] for
/// deregistering names registered through this method.
///
/// Note that exclusive ownership without queueing is requested (using
/// [`RequestNameFlags::ReplaceExisting`] and [`RequestNameFlags::DoNotQueue`] flags) since that
/// is the most typical case. If that is not what you want, you should use
/// [`Connection::request_name_with_flags`] instead (but make sure then that name is requested
/// **after** you've setup your service implementation with the `ObjectServer`).
///
/// # Caveats
///
/// The associated `ObjectServer` will only handle method calls destined for the unique name of
/// this connection or any of the registered well-known names. If no well-known name is
/// registered, the method calls destined to all well-known names will be handled.
///
/// Since names registered through any other means than `Connection` or [`ConnectionBuilder`]
/// API are not known to the connection, method calls destined to those names will only be
/// handled by the associated `ObjectServer` if none of the names are registered through
/// `Connection*` API. Simply put, either register all the names through `Connection*` API or
/// none of them.
///
/// # Errors
///
/// Fails with `zbus::Error::NameTaken` if the name is already owned by another peer.
pub async fn request_name<'w, W>(&self, well_known_name: W) -> Result<()>
/// Asks the client to refresh the inlay hints currently shown in editors. As a result, the
/// client should ask the server to recompute the inlay hints for these editors.
///
/// This is useful if a server detects a configuration change which requires a re-calculation
/// of all inlay hints. Note that the client still has the freedom to delay the re-calculation
/// of the inlay hints if for example an editor is currently not visible.
///
/// This corresponds to the [`workspace/inlayHint/refresh`] request.
///
/// [`workspace/inlayHint/refresh`]: https://microsoft.github.io/language-server-protocol/specification#workspace_inlayHint_refresh
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0.
pub async fn inlay_hint_refresh(&self) -> jsonrpc::Result<()> {
/// Indicates this long-running operation is complete.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn finish(self) {
/// Registers a new capability with the client.
///
/// This corresponds to the [`client/registerCapability`] request.
///
/// [`client/registerCapability`]: https://microsoft.github.io/language-server-protocol/specification#client_registerCapability
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
pub async fn register_capability(
/// Sends a custom request to the client.
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
pub async fn send_request<R>(&self, params: R::Params) -> jsonrpc::Result<R::Result>
/// Asks the client to refresh the code lenses currently shown in editors. As a result, the
/// client should ask the server to recompute the code lenses for these editors.
///
/// This is useful if a server detects a configuration change which requires a re-calculation
/// of all code lenses.
///
/// Note that the client still has the freedom to delay the re-calculation of the code lenses
/// if for example an editor is currently not visible.
///
/// This corresponds to the [`workspace/codeLens/refresh`] request.
///
/// [`workspace/codeLens/refresh`]: https://microsoft.github.io/language-server-protocol/specification#codeLens_refresh
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
pub async fn code_lens_refresh(&self) -> jsonrpc::Result<()> {
/// Same as [`OngoingProgress::report`](OngoingProgress#method.report-2), except it also
/// displays an optional more detailed progress message.
///
/// This message is expected to contain information complementary to the `title` string passed
/// into [`Client::progress`], such as `"3/25 files"`, `"project/src/module2"`, or
/// `"node_modules/some_dep"`.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn report_with_message<M>(&self, message: M, percentage: u32)
/// Updates the progress percentage displayed in the client UI, where a value of `100` for
/// example is considered 100% by the client.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn report(&self, percentage: u32) {
/// Starts reporting progress to the client, returning an [`OngoingProgress`] handle.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn begin(self) -> OngoingProgress<B, C> {
/// Sends a custom notification to the client.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn send_notification<N>(&self, params: N::Params)
/// Submits validation diagnostics for an open file with the given URI.
///
/// This corresponds to the [`textDocument/publishDiagnostics`] notification.
///
/// [`textDocument/publishDiagnostics`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_publishDiagnostics
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn publish_diagnostics(
/// Starts a stream of `$/progress` notifications for a client-provided [`ProgressToken`].
///
/// This method also takes a `title` argument briefly describing the kind of operation being
/// performed, e.g. "Indexing" or "Linking Dependencies".
///
/// [`ProgressToken`]: https://docs.rs/lsp-types/latest/lsp_types/type.ProgressToken.html
///
/// # Initialization
///
/// These notifications will only be sent if the server is initialized.
///
/// # Examples
///
/// ```no_run
/// # use tower_lsp::{lsp_types::*, Client};
/// #
/// # struct Mock {
/// # client: Client,
/// # }
/// #
/// # impl Mock {
/// # async fn completion(&self, params: CompletionParams) {
/// # let work_done_token = ProgressToken::Number(1);
/// #
/// let progress = self
/// .client
/// .progress(work_done_token, "Progress Title")
/// .with_message("Working...")
/// .with_percentage(0)
/// .begin()
/// .await;
///
/// for percent in 1..=100 {
/// let msg = format!("Working... [{percent}/100]");
/// progress.report_with_message(msg, percent).await;
/// }
///
/// progress.finish_with_message("Done!").await;
/// # }
/// # }
/// ```
pub fn progress<T>(&self, token: ProgressToken, title: T) -> Progress
/// Fetches the current open list of workspace folders.
///
/// Returns `None` if only a single file is open in the tool. Returns an empty `Vec` if a
/// workspace is open but no folders are configured.
///
/// This corresponds to the [`workspace/workspaceFolders`] request.
///
/// [`workspace/workspaceFolders`]: https://microsoft.github.io/language-server-protocol/specification#workspace_workspaceFolders
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.6.0.
pub async fn workspace_folders(&self) -> jsonrpc::Result<Option<Vec<WorkspaceFolder>>> {
/// Unregisters a capability with the client.
///
/// This corresponds to the [`client/unregisterCapability`] request.
///
/// [`client/unregisterCapability`]: https://microsoft.github.io/language-server-protocol/specification#client_unregisterCapability
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
pub async fn unregister_capability(
/// Asks the client to display a particular resource referenced by a URI in the user interface.
///
/// Returns `Ok(true)` if the document was successfully shown, or `Ok(false)` otherwise.
///
/// This corresponds to the [`window/showDocument`] request.
///
/// [`window/showDocument`]: https://microsoft.github.io/language-server-protocol/specification#window_showDocument
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
pub async fn show_document(&self, params: ShowDocumentParams) -> jsonrpc::Result<bool> {
/// Same as [`OngoingProgress::finish`], except it also displays an optional more detailed
/// progress message.
///
/// This message is expected to contain information complementary to the `title` string passed
/// into [`Client::progress`], such as `"3/25 files"`, `"project/src/module2"`, or
/// `"node_modules/some_dep"`.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn finish_with_message<M>(self, message: M)
/// Asks the client to refresh the inline values currently shown in editors. As a result, the
/// client should ask the server to recompute the inline values for these editors.
///
/// This is useful if a server detects a configuration change which requires a re-calculation
/// of all inline values. Note that the client still has the freedom to delay the
/// re-calculation of the inline values if for example an editor is currently not visible.
///
/// This corresponds to the [`workspace/inlineValue/refresh`] request.
///
/// [`workspace/inlineValue/refresh`]: https://microsoft.github.io/language-server-protocol/specification#workspace_inlineValue_refresh
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0.
pub async fn inline_value_refresh(&self) -> jsonrpc::Result<()> {
/// Asks the client to refresh the editors for which this server provides semantic tokens. As a
/// result, the client should ask the server to recompute the semantic tokens for these
/// editors.
///
/// This is useful if a server detects a project-wide configuration change which requires a
/// re-calculation of all semantic tokens. Note that the client still has the freedom to delay
/// the re-calculation of the semantic tokens if for example an editor is currently not visible.
///
/// This corresponds to the [`workspace/semanticTokens/refresh`] request.
///
/// [`workspace/semanticTokens/refresh`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_semanticTokens
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.16.0.
pub async fn semantic_tokens_refresh(&self) -> jsonrpc::Result<()> {
/// Updates the secondary progress message visible in the client UI.
///
/// This message is expected to contain information complementary to the `title` string passed
/// into [`Client::progress`], such as `"3/25 files"`, `"project/src/module2"`, or
/// `"node_modules/some_dep"`.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn report<M>(&self, message: M)
/// Requests a workspace resource be edited on the client side and returns whether the edit was
/// applied.
///
/// This corresponds to the [`workspace/applyEdit`] request.
///
/// [`workspace/applyEdit`]: https://microsoft.github.io/language-server-protocol/specification#workspace_applyEdit
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
pub async fn apply_edit(
/// Asks the client to refresh all needed document and workspace diagnostics.
///
/// This is useful if a server detects a project wide configuration change which requires a
/// re-calculation of all diagnostics.
///
/// This corresponds to the [`workspace/diagnostic/refresh`] request.
///
/// [`workspace/diagnostic/refresh`]: https://microsoft.github.io/language-server-protocol/specification#diagnostic_refresh
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.17.0.
pub async fn workspace_diagnostic_refresh(&self) -> jsonrpc::Result<()> {
/// Updates the progress percentage displayed in the client UI, where a value of `100` for
/// example is considered 100% by the client.
///
/// If `enable_cancel_btn` is `None`, the state of the "cancel" button in the UI is unchanged.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn report(&self, percentage: u32, enable_cancel_btn: Option<bool>) {
/// Same as [`OngoingProgress::report`](OngoingProgress#method.report-3), except it also
/// displays an optional more detailed progress message.
///
/// This message is expected to contain information complementary to the `title` string passed
/// into [`Client::progress`], such as `"3/25 files"`, `"project/src/module2"`, or
/// `"node_modules/some_dep"`.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn report_with_message<M>(
/// Updates the secondary progress message visible in the client UI and optionally
/// enables/disables the "cancel" button.
///
/// This message is expected to contain information complementary to the `title` string passed
/// into [`Client::progress`], such as `"3/25 files"`, `"project/src/module2"`, or
/// `"node_modules/some_dep"`.
///
/// If `enable_cancel_btn` is `None`, the state of the "cancel" button in the UI is unchanged.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn report_with_message<M>(&self, message: M, enable_cancel_btn: Option<bool>)
/// Enables or disables the "cancel" button in the client UI.
///
/// # Initialization
///
/// This notification will only be sent if the server is initialized.
pub async fn report(&self, enable_cancel_btn: bool) {
/// Fetches configuration settings from the client.
///
/// The request can fetch several configuration settings in one roundtrip. The order of the
/// returned configuration settings correspond to the order of the passed
/// [`ConfigurationItem`]s (e.g. the first item in the response is the result for the first
/// configuration item in the params).
///
/// This corresponds to the [`workspace/configuration`] request.
///
/// [`workspace/configuration`]: https://microsoft.github.io/language-server-protocol/specification#workspace_configuration
///
/// # Initialization
///
/// If the request is sent to the client before the server has been initialized, this will
/// immediately return `Err` with JSON-RPC error code `-32002` ([read more]).
///
/// [read more]: https://microsoft.github.io/language-server-protocol/specification#initialize
///
/// # Compatibility
///
/// This request was introduced in specification version 3.6.0.
pub async fn configuration(
/// Either get the value or initialize it with the given closure.
///
/// The cell will not be initialized if the closure returns an error.
///
/// # Blocking
///
/// In contrast to the `get_or_try_init` method, this method blocks the current thread of
/// execution instead of awaiting.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a `OnceCell` can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Example
///
/// ```rust
/// use async_lock::OnceCell;
/// #
/// # // Prevent explicit type errors.
/// # fn _explicit(_: &Result<&i32, ()>) {}
///
/// let cell = OnceCell::new();
///
/// let result = cell.get_or_try_init_blocking(|| Err(()));
/// assert!(result.is_err());
///
/// let result = cell.get_or_try_init_blocking(|| Ok(1));
/// # _explicit(&result);
/// assert_eq!(result.unwrap(), &1);
///
/// let result = cell.get_or_try_init_blocking(|| Err(()));
///
/// assert_eq!(result.unwrap(), &1);
/// ```
pub fn get_or_try_init_blocking<E>(
/// Acquires an owned, reference-counted write lock.
///
/// Returns a guard that releases the lock when dropped.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`write_arc`][RwLock::write_arc] method, this method will
/// block the current thread until the write lock is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a lock can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use async_lock::RwLock;
///
/// let lock = Arc::new(RwLock::new(1));
///
/// let writer = lock.write_arc_blocking();
/// assert!(lock.try_read().is_none());
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Acquires the mutex and clones a reference to it using the blocking strategy.
///
/// Returns an owned guard that releases the mutex when dropped.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`lock_arc`][Mutex::lock_arc] method,
/// this method will block the current thread until the lock is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a mutex can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use async_lock::Mutex;
/// use std::sync::Arc;
///
/// let mutex = Arc::new(Mutex::new(10));
/// let guard = mutex.lock_arc_blocking();
/// assert_eq!(*guard, 10);
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Either get the value or initialize it with the given closure.
///
/// The cell will not be initialized if the closure returns an error.
///
/// # Blocking
///
/// In contrast to the `get_or_try_init` method, this method blocks the current thread of
/// execution instead of awaiting.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a `OnceCell` can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Example
///
/// ```rust
/// use async_lock::OnceCell;
/// #
/// # // Prevent explicit type errors.
/// # fn _explicit(_: &Result<&i32, ()>) {}
///
/// let cell = OnceCell::new();
///
/// let result = cell.get_or_try_init_blocking(|| Err(()));
/// assert!(result.is_err());
///
/// let result = cell.get_or_try_init_blocking(|| Ok(1));
/// # _explicit(&result);
/// assert_eq!(result.unwrap(), &1);
///
/// let result = cell.get_or_try_init_blocking(|| Err(()));
///
/// assert_eq!(result.unwrap(), &1);
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Blocks the current thread until all tasks reach this point.
///
/// Barriers are reusable after all tasks have synchronized, and can be used continuously.
///
/// Returns a [`BarrierWaitResult`] indicating whether this task is the "leader", meaning the
/// last task to call this method.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`wait`][`Barrier::wait`] method,
/// this method will block the current thread until the wait is complete.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a barrier can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use async_lock::Barrier;
/// use futures_lite::future;
/// use std::sync::Arc;
/// use std::thread;
///
/// let barrier = Arc::new(Barrier::new(5));
///
/// for _ in 0..5 {
/// let b = barrier.clone();
/// thread::spawn(move || {
/// // The same messages will be printed together.
/// // There will NOT be interleaving of "before" and "after".
/// println!("before wait");
/// b.wait_blocking();
/// println!("after wait");
/// });
/// }
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Try to set the value of the cell.
///
/// If the cell is already initialized, this method returns the original
/// value back.
///
/// # Blocking
///
/// In contrast to the `set` method, this method blocks the current thread of
/// execution instead of awaiting.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a `OnceCell` can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Example
///
/// ```rust
/// use async_lock::OnceCell;
///
/// let cell = OnceCell::new();
///
/// assert_eq!(cell.set_blocking(1), Ok(&1));
/// assert_eq!(cell.get(), Some(&1));
/// assert_eq!(cell.set_blocking(2), Err(2));
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Sends a message into this channel using the blocking strategy.
///
/// If the channel is full, this method will block until there is room.
/// If the channel is closed, this method returns an error.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`send`](Self::send) method,
/// this method will block the current thread until the message is sent.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a channel can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Examples
///
/// ```
/// use async_channel::{unbounded, SendError};
///
/// let (s, r) = unbounded();
///
/// assert_eq!(s.send_blocking(1), Ok(()));
/// drop(r);
/// assert_eq!(s.send_blocking(2), Err(SendError(2)));
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Acquires a read lock.
///
/// Returns a guard that releases the lock when dropped.
///
/// Note that attempts to acquire a read lock will block if there are also concurrent attempts
/// to acquire a write lock.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`read`][`RwLock::read`] method,
/// this method will block the current thread until the read lock is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a lock can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use async_lock::RwLock;
///
/// let lock = RwLock::new(1);
///
/// let reader = lock.read_blocking();
/// assert_eq!(*reader, 1);
///
/// assert!(lock.try_read().is_some());
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Acquires the mutex using the blocking strategy.
///
/// Returns a guard that releases the mutex when dropped.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`lock`][Mutex::lock] method,
/// this method will block the current thread until the lock is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a mutex can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use async_lock::Mutex;
///
/// let mutex = Mutex::new(10);
/// let guard = mutex.lock_blocking();
/// assert_eq!(*guard, 10);
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Try to set the value of the cell.
///
/// If the cell is already initialized, this method returns the original
/// value back.
///
/// # Blocking
///
/// In contrast to the `set` method, this method blocks the current thread of
/// execution instead of awaiting.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a `OnceCell` can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Example
///
/// ```rust
/// use async_lock::OnceCell;
///
/// let cell = OnceCell::new();
///
/// assert_eq!(cell.set_blocking(1), Ok(&1));
/// assert_eq!(cell.get(), Some(&1));
/// assert_eq!(cell.set_blocking(2), Err(2));
/// ```
pub fn set_blocking(&self, value: T) -> Result<&T, T> {
/// Attempts to acquire an owned, reference-counted read lock
/// with the possiblity to upgrade to a write lock.
///
/// Returns a guard that releases the lock when dropped.
///
/// Upgradable read lock reserves the right to be upgraded to a write lock, which means there
/// can be at most one upgradable read lock at a time.
///
/// Note that attempts to acquire an upgradable read lock will block if there are concurrent
/// attempts to acquire another upgradable read lock or a write lock.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`upgradable_read_arc`][`RwLock::upgradable_read_arc`]
/// method, this method will block the current thread until the read lock is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a lock can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use async_lock::{RwLock, RwLockUpgradableReadGuardArc};
///
/// let lock = Arc::new(RwLock::new(1));
///
/// let reader = lock.upgradable_read_arc_blocking();
/// assert_eq!(*reader, 1);
/// assert_eq!(*lock.try_read().unwrap(), 1);
///
/// let mut writer = RwLockUpgradableReadGuardArc::upgrade_blocking(reader);
/// *writer = 2;
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Acquires an owned, reference-counted read lock.
///
/// Returns a guard that releases the lock when dropped.
///
/// Note that attempts to acquire a read lock will block if there are also concurrent attempts
/// to acquire a write lock.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`read_arc`][`RwLock::read_arc`] method,
/// this method will block the current thread until the read lock is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a lock can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use async_lock::RwLock;
///
/// let lock = Arc::new(RwLock::new(1));
///
/// let reader = lock.read_arc_blocking();
/// assert_eq!(*reader, 1);
///
/// assert!(lock.try_read().is_some());
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Waits for a permit for a concurrent operation.
///
/// Returns a guard that releases the permit when dropped.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`acquire`][Semaphore::acquire] method,
/// this method will block the current thread until the permit is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a semaphore can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use async_lock::Semaphore;
///
/// let s = Semaphore::new(2);
/// let guard = s.acquire_blocking();
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Wait for the cell to be initialized, and then return a reference to the
/// inner value.
///
/// # Blocking
///
/// In contrast to the `wait` method, this method blocks the current thread of
/// execution instead of awaiting.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a `OnceCell` can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Example
///
/// ```rust
/// use async_lock::OnceCell;
/// use std::sync::Arc;
/// use std::time::Duration;
/// use std::thread::{sleep, spawn};
///
/// let cell = Arc::new(OnceCell::new());
/// let cell2 = cell.clone();
///
/// spawn(move || {
/// sleep(Duration::from_millis(5));
/// cell2.set_blocking(1);
/// });
///
/// assert_eq!(cell.wait_blocking(), &1);
/// ```
pub fn wait_blocking(&self) -> &T {
/// Receives a message from the channel using the blocking strategy.
///
/// If the channel is empty, this method waits until there is a message.
/// If the channel is closed, this method receives a message or returns an error if there are
/// no more messages.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`recv`](Self::recv) method,
/// this method will block the current thread until the message is sent.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a channel can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Examples
///
/// ```
/// use async_channel::{unbounded, RecvError};
///
/// let (s, r) = unbounded();
///
/// assert_eq!(s.send_blocking(1), Ok(()));
/// drop(s);
///
/// assert_eq!(r.recv_blocking(), Ok(1));
/// assert_eq!(r.recv_blocking(), Err(RecvError));
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Acquires a write lock.
///
/// Returns a guard that releases the lock when dropped.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`write`] method, this method will
/// block the current thread until the write lock is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a lock can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use async_lock::RwLock;
///
/// let lock = RwLock::new(1);
///
/// let writer = lock.write_blocking();
/// assert!(lock.try_read().is_none());
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Wait for the cell to be initialized, and then return a reference to the
/// inner value.
///
/// # Blocking
///
/// In contrast to the `wait` method, this method blocks the current thread of
/// execution instead of awaiting.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a `OnceCell` can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Example
///
/// ```rust
/// use async_lock::OnceCell;
/// use std::sync::Arc;
/// use std::time::Duration;
/// use std::thread::{sleep, spawn};
///
/// let cell = Arc::new(OnceCell::new());
/// let cell2 = cell.clone();
///
/// spawn(move || {
/// sleep(Duration::from_millis(5));
/// cell2.set_blocking(1);
/// });
///
/// assert_eq!(cell.wait_blocking(), &1);
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Either get the value or initialize it with the given closure.
///
/// Many tasks may call this function, but the value will only be set once
/// and only one closure will be invoked.
///
/// # Blocking
///
/// In contrast to the `get_or_init` method, this method blocks the current thread of
/// execution instead of awaiting.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a `OnceCell` can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Example
///
/// ```rust
/// use async_lock::OnceCell;
///
/// let cell = OnceCell::new();
/// assert_eq!(cell.get_or_init_blocking(|| 1), &1);
/// assert_eq!(cell.get_or_init_blocking(|| 2), &1);
/// ```
pub fn get_or_init_blocking(&self, closure: impl FnOnce() -> T + Unpin) -> &T {
/// Waits for an owned permit for a concurrent operation.
///
/// Returns a guard that releases the permit when dropped.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`acquire_arc`][Semaphore::acquire_arc] method,
/// this method will block the current thread until the permit is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a semaphore can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use async_lock::Semaphore;
///
/// let s = Arc::new(Semaphore::new(2));
/// let guard = s.acquire_arc_blocking();
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Upgrades into a write lock.
///
/// # Blocking
///
/// This function will block the current thread until it is able to acquire the write lock.
///
/// # Examples
///
/// ```
/// use async_lock::{RwLock, RwLockUpgradableReadGuard};
///
/// let lock = RwLock::new(1);
///
/// let reader = lock.upgradable_read_blocking();
/// assert_eq!(*reader, 1);
///
/// let mut writer = RwLockUpgradableReadGuard::upgrade_blocking(reader);
/// *writer = 2;
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Attempts to acquire a read lock with the possiblity to upgrade to a write lock.
///
/// Returns a guard that releases the lock when dropped.
///
/// Upgradable read lock reserves the right to be upgraded to a write lock, which means there
/// can be at most one upgradable read lock at a time.
///
/// Note that attempts to acquire an upgradable read lock will block if there are concurrent
/// attempts to acquire another upgradable read lock or a write lock.
///
/// # Blocking
///
/// Rather than using asynchronous waiting, like the [`upgradable_read`][`RwLock::upgradable_read`]
/// method, this method will block the current thread until the read lock is acquired.
///
/// This method should not be used in an asynchronous context. It is intended to be
/// used in a way that a lock can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in a deadlock.
///
/// # Examples
///
/// ```
/// use async_lock::{RwLock, RwLockUpgradableReadGuard};
///
/// let lock = RwLock::new(1);
///
/// let reader = lock.upgradable_read_blocking();
/// assert_eq!(*reader, 1);
/// assert_eq!(*lock.try_read().unwrap(), 1);
///
/// let mut writer = RwLockUpgradableReadGuard::upgrade_blocking(reader);
/// *writer = 2;
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Upgrades into a write lock.
///
/// # Blocking
///
/// This function will block the current thread until it is able to acquire the write lock.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use async_lock::{RwLock, RwLockUpgradableReadGuardArc};
///
/// let lock = Arc::new(RwLock::new(1));
///
/// let reader = lock.upgradable_read_arc_blocking();
/// assert_eq!(*reader, 1);
///
/// let mut writer = RwLockUpgradableReadGuardArc::upgrade_blocking(reader);
/// *writer = 2;
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Either get the value or initialize it with the given closure.
///
/// Many tasks may call this function, but the value will only be set once
/// and only one closure will be invoked.
///
/// # Blocking
///
/// In contrast to the `get_or_init` method, this method blocks the current thread of
/// execution instead of awaiting.
///
/// This method should not be used in an asynchronous context. It is intended
/// to be used such that a `OnceCell` can be used in both asynchronous and synchronous contexts.
/// Calling this method in an asynchronous context may result in deadlocks.
///
/// # Example
///
/// ```rust
/// use async_lock::OnceCell;
///
/// let cell = OnceCell::new();
/// assert_eq!(cell.get_or_init_blocking(|| 1), &1);
/// assert_eq!(cell.get_or_init_blocking(|| 2), &1);
/// ```
#[cfg(all(feature = "std", not(target_family = "wasm")))]
/// Persist the temporary file at the target path.
///
/// If a file exists at the target path, persist will atomically replace it.
/// If this method fails, it will return `self` in the resulting
/// [`PathPersistError`].
///
/// Note: Temporary files cannot be persisted across filesystems. Also
/// neither the file contents nor the containing directory are
/// synchronized, so the update may not yet have reached the disk when
/// `persist` returns.
///
/// # Security
///
/// Only use this method if you're positive that a temporary file cleaner
/// won't have deleted your file. Otherwise, you might end up persisting an
/// attacker controlled file.
///
/// # Errors
///
/// If the file cannot be moved to the new location, `Err` is returned.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let mut file = NamedTempFile::new()?;
/// writeln!(file, "Brian was here. Briefly.")?;
///
/// let path = file.into_temp_path();
/// path.persist("./saved_file.txt")?;
/// # Ok(())
/// # }
/// ```
///
/// [`PathPersistError`]: struct.PathPersistError.html
pub fn persist<P: AsRef<Path>>(mut self, new_path: P) -> Result<(), PathPersistError> {
/// The permissions to create the tempfile or [tempdir](Self::tempdir) with.
/// This allows to them differ from the default mode of `0o600` on Unix.
///
/// # Security
///
/// By default, the permissions of tempfiles on unix are set for it to be
/// readable and writable by the owner only, yielding the greatest amount
/// of security.
/// As this method allows to widen the permissions, security would be
/// reduced in such cases.
///
/// # Platform Notes
/// ## Unix
///
/// The actual permission bits set on the tempfile or tempdir will be affected by the
/// `umask` applied by the underlying syscall.
///
///
/// ## Windows and others
///
/// This setting is unsupported and trying to set a file or directory read-only
/// will cause an error to be returned..
///
/// # Examples
///
/// Create a named temporary file that is world-readable.
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// #[cfg(unix)]
/// {
/// use std::os::unix::fs::PermissionsExt;
/// let all_read_write = std::fs::Permissions::from_mode(0o666);
/// let tempfile = Builder::new().permissions(all_read_write).tempfile()?;
/// let actual_permissions = tempfile.path().metadata()?.permissions();
/// assert_ne!(
/// actual_permissions.mode() & !0o170000,
/// 0o600,
/// "we get broader permissions than the default despite umask"
/// );
/// }
/// # Ok(())
/// # }
/// ```
///
/// Create a named temporary directory that is restricted to the owner.
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// #[cfg(unix)]
/// {
/// use std::os::unix::fs::PermissionsExt;
/// let owner_rwx = std::fs::Permissions::from_mode(0o700);
/// let tempdir = Builder::new().permissions(owner_rwx).tempdir()?;
/// let actual_permissions = tempdir.path().metadata()?.permissions();
/// assert_eq!(
/// actual_permissions.mode() & !0o170000,
/// 0o700,
/// "we get the narrow permissions we asked for"
/// );
/// }
/// # Ok(())
/// # }
/// ```
pub fn permissions(&mut self, permissions: std::fs::Permissions) -> &mut Self {
/// Create a new named temporary file.
///
/// See [`Builder`] for more configuration.
///
/// # Security
///
/// This will create a temporary file in the default temporary file
/// directory (platform dependent). This has security implications on many
/// platforms so please read the security section of this type's
/// documentation.
///
/// Reasons to use this method:
///
/// 1. The file has a short lifetime and your temporary file cleaner is
/// sane (doesn't delete recently accessed files).
///
/// 2. You trust every user on your system (i.e. you are the only user).
///
/// 3. You have disabled your system's temporary file cleaner or verified
/// that your system doesn't have a temporary file cleaner.
///
/// Reasons not to use this method:
///
/// 1. You'll fix it later. No you won't.
///
/// 2. You don't care about the security of the temporary file. If none of
/// the "reasons to use this method" apply, referring to a temporary
/// file by name may allow an attacker to create/overwrite your
/// non-temporary files. There are exceptions but if you don't already
/// know them, don't use this method.
///
/// # Errors
///
/// If the file can not be created, `Err` is returned.
///
/// # Examples
///
/// Create a named temporary file and write some data to it:
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), ::std::io::Error> {
/// let mut file = NamedTempFile::new()?;
///
/// writeln!(file, "Brian was here. Briefly.")?;
/// # Ok(())
/// # }
/// ```
///
/// [`Builder`]: struct.Builder.html
pub fn new() -> io::Result<NamedTempFile> {
/// Persist the temporary file at the target path if and only if no file exists there.
///
/// If a file exists at the target path, fail. If this method fails, it will
/// return `self` in the resulting PersistError.
///
/// Note: Temporary files cannot be persisted across filesystems. Also Note:
/// This method is not atomic. It can leave the original link to the
/// temporary file behind.
///
/// # Security
///
/// This method persists the temporary file using its path and may not be
/// secure in the in all cases. Please read the security section on the top
/// level documentation of this type for details.
///
/// # Errors
///
/// If the file cannot be moved to the new location or a file already exists there,
/// `Err` is returned.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let file = NamedTempFile::new()?;
///
/// let mut persisted_file = file.persist_noclobber("./saved_file.txt")?;
/// writeln!(persisted_file, "Brian was here. Briefly.")?;
/// # Ok(())
/// # }
/// ```
pub fn persist_noclobber<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
/// Persist the temporary file at the target path if and only if no file exists there.
///
/// If a file exists at the target path, fail. If this method fails, it will
/// return `self` in the resulting [`PathPersistError`].
///
/// Note: Temporary files cannot be persisted across filesystems. Also Note:
/// This method is not atomic. It can leave the original link to the
/// temporary file behind.
///
/// # Security
///
/// Only use this method if you're positive that a temporary file cleaner
/// won't have deleted your file. Otherwise, you might end up persisting an
/// attacker controlled file.
///
/// # Errors
///
/// If the file cannot be moved to the new location or a file already exists
/// there, `Err` is returned.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let mut file = NamedTempFile::new()?;
/// writeln!(file, "Brian was here. Briefly.")?;
///
/// let path = file.into_temp_path();
/// path.persist_noclobber("./saved_file.txt")?;
/// # Ok(())
/// # }
/// ```
///
/// [`PathPersistError`]: struct.PathPersistError.html
pub fn persist_noclobber<P: AsRef<Path>>(
/// Get the temporary file's path.
///
/// # Security
///
/// Referring to a temporary file's path may not be secure in all cases.
/// Please read the security section on the top level documentation of this
/// type for details.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), ::std::io::Error> {
/// let file = NamedTempFile::new()?;
///
/// println!("{:?}", file.path());
/// # Ok(())
/// # }
/// ```
#[inline]
/// The URL scheme.
pub scheme: Scheme,
/// The user to impersonate on the remote.
user: Option<String>,
/// The password associated with a user.
password: Option<String>,
/// The host to which to connect. Localhost is implied if `None`.
host: Option<String>,
/// When serializing, use the alternative forms as it was parsed as such.
serialize_alternative_form: bool,
/// The port to use when connecting to a host. If `None`, standard ports depending on `scheme` will be used.
pub port: Option<u16>,
/// The path portion of the URL, usually the location of the git repository.
///
/// # Security-Warning
///
/// URLs allow paths to start with `-` which makes it possible to mask command-line arguments as path which then leads to
/// the invocation of programs from an attacker controlled URL. See <https://secure.phabricator.com/T12961> for details.
///
/// If this value is going to be used in a command-line application, call [Self::path_argument_safe()] instead.
pub path: BString,
/// Create the named temporary file in the specified directory.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the file cannot be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// let tempfile = Builder::new().tempfile_in("./")?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<NamedTempFile> {
/// Create the named temporary file.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the file cannot be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// let tempfile = Builder::new().tempfile()?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile(&self) -> io::Result<NamedTempFile> {
/// Persist the temporary file at the target path.
///
/// If a file exists at the target path, persist will atomically replace it.
/// If this method fails, it will return `self` in the resulting
/// [`PathPersistError`].
///
/// Note: Temporary files cannot be persisted across filesystems. Also
/// neither the file contents nor the containing directory are
/// synchronized, so the update may not yet have reached the disk when
/// `persist` returns.
///
/// # Security
///
/// Only use this method if you're positive that a temporary file cleaner
/// won't have deleted your file. Otherwise, you might end up persisting an
/// attacker controlled file.
///
/// # Errors
///
/// If the file cannot be moved to the new location, `Err` is returned.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let mut file = NamedTempFile::new()?;
/// writeln!(file, "Brian was here. Briefly.")?;
///
/// let path = file.into_temp_path();
/// path.persist("./saved_file.txt")?;
/// # Ok(())
/// # }
/// ```
///
/// [`PathPersistError`]: struct.PathPersistError.html
pub fn persist<P: AsRef<Path>>(mut self, new_path: P) -> Result<(), PathPersistError> {
/// Securely reopen the temporary file.
///
/// This function is useful when you need multiple independent handles to
/// the same file. It's perfectly fine to drop the original `NamedTempFile`
/// while holding on to `File`s returned by this function; the `File`s will
/// remain usable. However, they may not be nameable.
///
/// # Errors
///
/// If the file cannot be reopened, `Err` is returned.
///
/// # Security
///
/// Unlike `File::open(my_temp_file.path())`, `NamedTempFile::reopen()`
/// guarantees that the re-opened file is the _same_ file, even in the
/// presence of pathological temporary file cleaners.
///
/// # Examples
///
/// ```no_run
/// # use std::io;
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let file = NamedTempFile::new()?;
///
/// let another_handle = file.reopen()?;
/// # Ok(())
/// # }
/// ```
pub fn reopen(&self) -> io::Result<File> {
/// Create a new named temporary file.
///
/// See [`Builder`] for more configuration.
///
/// # Security
///
/// This will create a temporary file in the default temporary file
/// directory (platform dependent). This has security implications on many
/// platforms so please read the security section of this type's
/// documentation.
///
/// Reasons to use this method:
///
/// 1. The file has a short lifetime and your temporary file cleaner is
/// sane (doesn't delete recently accessed files).
///
/// 2. You trust every user on your system (i.e. you are the only user).
///
/// 3. You have disabled your system's temporary file cleaner or verified
/// that your system doesn't have a temporary file cleaner.
///
/// Reasons not to use this method:
///
/// 1. You'll fix it later. No you won't.
///
/// 2. You don't care about the security of the temporary file. If none of
/// the "reasons to use this method" apply, referring to a temporary
/// file by name may allow an attacker to create/overwrite your
/// non-temporary files. There are exceptions but if you don't already
/// know them, don't use this method.
///
/// # Errors
///
/// If the file can not be created, `Err` is returned.
///
/// # Examples
///
/// Create a named temporary file and write some data to it:
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), ::std::io::Error> {
/// let mut file = NamedTempFile::new()?;
///
/// writeln!(file, "Brian was here. Briefly.")?;
/// # Ok(())
/// # }
/// ```
///
/// [`Builder`]: struct.Builder.html
pub fn new() -> io::Result<NamedTempFile> {
/// Attempts to create a temporary file (or file-like object) using the
/// provided closure. The closure is passed a temporary file path and
/// returns an [`std::io::Result`]. The path provided to the closure will be
/// inside of [`std::env::temp_dir()`]. Use [`Builder::make_in`] to provide
/// a custom temporary directory. If the closure returns one of the
/// following errors, then another randomized file path is tried:
/// - [`std::io::ErrorKind::AlreadyExists`]
/// - [`std::io::ErrorKind::AddrInUse`]
///
/// This can be helpful for taking full control over the file creation, but
/// leaving the temporary file path construction up to the library. This
/// also enables creating a temporary UNIX domain socket, since it is not
/// possible to bind to a socket that already exists.
///
/// Note that [`Builder::append`] is ignored when using [`Builder::make`].
///
/// # Security
///
/// This has the same [security implications][security] as
/// [`NamedTempFile`], but with additional caveats. Specifically, it is up
/// to the closure to ensure that the file does not exist and that such a
/// check is *atomic*. Otherwise, a [time-of-check to time-of-use
/// bug][TOCTOU] could be introduced.
///
/// For example, the following is **not** secure:
///
/// ```
/// # use std::io;
/// # use std::fs::File;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// // This is NOT secure!
/// let tempfile = Builder::new().make(|path| {
/// if path.is_file() {
/// return Err(io::ErrorKind::AlreadyExists.into());
/// }
///
/// // Between the check above and the usage below, an attacker could
/// // have replaced `path` with another file, which would get truncated
/// // by `File::create`.
///
/// File::create(path)
/// })?;
/// # Ok(())
/// # }
/// ```
/// Note that simply using [`std::fs::File::create`] alone is not correct
/// because it does not fail if the file already exists:
/// ```
/// # use std::io;
/// # use std::fs::File;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// // This could overwrite an existing file!
/// let tempfile = Builder::new().make(|path| File::create(path))?;
/// # Ok(())
/// # }
/// ```
/// For creating regular temporary files, use [`Builder::tempfile`] instead
/// to avoid these problems. This function is meant to enable more exotic
/// use-cases.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the closure returns any error besides
/// [`std::io::ErrorKind::AlreadyExists`] or
/// [`std::io::ErrorKind::AddrInUse`], then `Err` is returned.
///
/// # Examples
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// # #[cfg(unix)]
/// use std::os::unix::net::UnixListener;
/// # #[cfg(unix)]
/// let tempsock = Builder::new().make(|path| UnixListener::bind(path))?;
/// # Ok(())
/// # }
/// ```
///
/// [TOCTOU]: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn make<F, R>(&self, f: F) -> io::Result<NamedTempFile<R>>
/// Set the trust level of the `.git` directory we are about to open.
///
/// This can be set manually to force trust even though otherwise it might
/// not be fully trusted, leading to limitations in how configuration files
/// are interpreted.
///
/// If not called explicitly, it will be determined by looking at its
/// ownership via [`gix_sec::Trust::from_path_ownership()`].
///
/// # Security Warning
///
/// Use with extreme care and only if it's absolutely known that the repository
/// is always controlled by the desired user. Using this capability _only_ saves
/// a permission check and only so if the [`open()`][Self::open()] method is used,
/// as opposed to discovery.
pub fn with(mut self, trust: gix_sec::Trust) -> Self {
/// Persist the temporary file at the target path if and only if no file exists there.
///
/// If a file exists at the target path, fail. If this method fails, it will
/// return `self` in the resulting [`PathPersistError`].
///
/// Note: Temporary files cannot be persisted across filesystems. Also Note:
/// This method is not atomic. It can leave the original link to the
/// temporary file behind.
///
/// # Security
///
/// Only use this method if you're positive that a temporary file cleaner
/// won't have deleted your file. Otherwise, you might end up persisting an
/// attacker controlled file.
///
/// # Errors
///
/// If the file cannot be moved to the new location or a file already exists
/// there, `Err` is returned.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let mut file = NamedTempFile::new()?;
/// writeln!(file, "Brian was here. Briefly.")?;
///
/// let path = file.into_temp_path();
/// path.persist_noclobber("./saved_file.txt")?;
/// # Ok(())
/// # }
/// ```
///
/// [`PathPersistError`]: struct.PathPersistError.html
pub fn persist_noclobber<P: AsRef<Path>>(
/// Persist the temporary file at the target path if and only if no file exists there.
///
/// If a file exists at the target path, fail. If this method fails, it will
/// return `self` in the resulting PersistError.
///
/// Note: Temporary files cannot be persisted across filesystems. Also Note:
/// This method is not atomic. It can leave the original link to the
/// temporary file behind.
///
/// # Security
///
/// This method persists the temporary file using its path and may not be
/// secure in all cases. Please read the security section on the top
/// level documentation of this type for details.
///
/// # Errors
///
/// If the file cannot be moved to the new location or a file already exists there,
/// `Err` is returned.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let file = NamedTempFile::new()?;
///
/// let mut persisted_file = file.persist_noclobber("./saved_file.txt")?;
/// writeln!(persisted_file, "Brian was here. Briefly.")?;
/// # Ok(())
/// # }
/// ```
pub fn persist_noclobber<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
/// Returns the host mentioned in the url, if present.
///
/// # Security-Warning
///
/// URLs allow hosts to start with `-` which makes it possible to mask command-line arguments as host which then leads to
/// the invocation of programs from an attacker controlled URL. See <https://secure.phabricator.com/T12961> for details.
///
/// If this value is going to be used in a command-line application, call [Self::host_argument_safe()] instead.
pub fn host(&self) -> Option<&str> {
/// Create the named temporary file in the specified directory.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the file cannot be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// let tempfile = Builder::new().tempfile_in("./")?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<NamedTempFile> {
/// Securely reopen the temporary file.
///
/// This function is useful when you need multiple independent handles to
/// the same file. It's perfectly fine to drop the original `NamedTempFile`
/// while holding on to `File`s returned by this function; the `File`s will
/// remain usable. However, they may not be nameable.
///
/// # Errors
///
/// If the file cannot be reopened, `Err` is returned.
///
/// # Security
///
/// Unlike `File::open(my_temp_file.path())`, `NamedTempFile::reopen()`
/// guarantees that the re-opened file is the _same_ file, even in the
/// presence of pathological temporary file cleaners.
///
/// # Examples
///
/// ```no_run
/// # use std::io;
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let file = NamedTempFile::new()?;
///
/// let another_handle = file.reopen()?;
/// # Ok(())
/// # }
/// ```
pub fn reopen(&self) -> io::Result<File> {
/// Attempts to create a temporary file (or file-like object) using the
/// provided closure. The closure is passed a temporary file path and
/// returns an [`std::io::Result`]. The path provided to the closure will be
/// inside of [`std::env::temp_dir()`]. Use [`Builder::make_in`] to provide
/// a custom temporary directory. If the closure returns one of the
/// following errors, then another randomized file path is tried:
/// - [`std::io::ErrorKind::AlreadyExists`]
/// - [`std::io::ErrorKind::AddrInUse`]
///
/// This can be helpful for taking full control over the file creation, but
/// leaving the temporary file path construction up to the library. This
/// also enables creating a temporary UNIX domain socket, since it is not
/// possible to bind to a socket that already exists.
///
/// Note that [`Builder::append`] is ignored when using [`Builder::make`].
///
/// # Security
///
/// This has the same [security implications][security] as
/// [`NamedTempFile`], but with additional caveats. Specifically, it is up
/// to the closure to ensure that the file does not exist and that such a
/// check is *atomic*. Otherwise, a [time-of-check to time-of-use
/// bug][TOCTOU] could be introduced.
///
/// For example, the following is **not** secure:
///
/// ```
/// # use std::io;
/// # use std::fs::File;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// // This is NOT secure!
/// let tempfile = Builder::new().make(|path| {
/// if path.is_file() {
/// return Err(io::ErrorKind::AlreadyExists.into());
/// }
///
/// // Between the check above and the usage below, an attacker could
/// // have replaced `path` with another file, which would get truncated
/// // by `File::create`.
///
/// File::create(path)
/// })?;
/// # Ok(())
/// # }
/// ```
/// Note that simply using [`std::fs::File::create`] alone is not correct
/// because it does not fail if the file already exists:
/// ```
/// # use std::io;
/// # use std::fs::File;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// // This could overwrite an existing file!
/// let tempfile = Builder::new().make(|path| File::create(path))?;
/// # Ok(())
/// # }
/// ```
/// For creating regular temporary files, use [`Builder::tempfile`] instead
/// to avoid these problems. This function is meant to enable more exotic
/// use-cases.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the closure returns any error besides
/// [`std::io::ErrorKind::AlreadyExists`] or
/// [`std::io::ErrorKind::AddrInUse`], then `Err` is returned.
///
/// # Examples
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// # #[cfg(unix)]
/// use std::os::unix::net::UnixListener;
/// # #[cfg(unix)]
/// let tempsock = Builder::new().make(|path| UnixListener::bind(path))?;
/// # Ok(())
/// # }
/// ```
///
/// [TOCTOU]: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn make<F, R>(&self, f: F) -> io::Result<NamedTempFile<R>>
/// Get the temporary file's path.
///
/// # Security
///
/// Referring to a temporary file's path may not be secure in all cases.
/// Please read the security section on the top level documentation of this
/// type for details.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), ::std::io::Error> {
/// let file = NamedTempFile::new()?;
///
/// println!("{:?}", file.path());
/// # Ok(())
/// # }
/// ```
#[inline]
/// Persist the temporary file at the target path.
///
/// If a file exists at the target path, persist will atomically replace it.
/// If this method fails, it will return `self` in the resulting
/// [`PersistError`].
///
/// Note: Temporary files cannot be persisted across filesystems. Also
/// neither the file contents nor the containing directory are
/// synchronized, so the update may not yet have reached the disk when
/// `persist` returns.
///
/// # Security
///
/// This method persists the temporary file using its path and may not be
/// secure in the in all cases. Please read the security section on the top
/// level documentation of this type for details.
///
/// # Errors
///
/// If the file cannot be moved to the new location, `Err` is returned.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let file = NamedTempFile::new()?;
///
/// let mut persisted_file = file.persist("./saved_file.txt")?;
/// writeln!(persisted_file, "Brian was here. Briefly.")?;
/// # Ok(())
/// # }
/// ```
///
/// [`PersistError`]: struct.PersistError.html
pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
/// Create the named temporary file.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the file cannot be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// let tempfile = Builder::new().tempfile()?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile(&self) -> io::Result<NamedTempFile> {
/// Persist the temporary file at the target path.
///
/// If a file exists at the target path, persist will atomically replace it.
/// If this method fails, it will return `self` in the resulting
/// [`PersistError`].
///
/// Note: Temporary files cannot be persisted across filesystems. Also
/// neither the file contents nor the containing directory are
/// synchronized, so the update may not yet have reached the disk when
/// `persist` returns.
///
/// # Security
///
/// This method persists the temporary file using its path and may not be
/// secure in all cases. Please read the security section on the top
/// level documentation of this type for details.
///
/// # Errors
///
/// If the file cannot be moved to the new location, `Err` is returned.
///
/// # Examples
///
/// ```no_run
/// # use std::io::{self, Write};
/// use tempfile::NamedTempFile;
///
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// let file = NamedTempFile::new()?;
///
/// let mut persisted_file = file.persist("./saved_file.txt")?;
/// writeln!(persisted_file, "Brian was here. Briefly.")?;
/// # Ok(())
/// # }
/// ```
///
/// [`PersistError`]: struct.PersistError.html
pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>> {
/// Same as `Frame::ip`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn ip(&self) -> *mut c_void {
/// Lossy converts to a `Cow<str>`, will allocate if `Bytes` is not valid
/// UTF-8 or if `BytesOrWideString` is `Wide`.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn to_str_lossy(&self) -> Cow<'a, str> {
/// Prints a `BacktraceFrame` with this frame formatter.
///
/// This will recursively print all `BacktraceSymbol` instances within the
/// `BacktraceFrame`.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[cfg(feature = "std")]
/// Same as `Symbol::lineno`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn lineno(&self) -> Option<u32> {
/// Prints a `BacktraceSymbol` within a `BacktraceFrame`.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[cfg(feature = "std")]
/// Same as `Symbol::colno`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn colno(&self) -> Option<u32> {
/// Prints a `BacktraceFrame` with this frame formatter.
///
/// This will recursively print all `BacktraceSymbol` instances within the
/// `BacktraceFrame`.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[cfg(feature = "std")]
/// Returns the frames from when this backtrace was captured.
///
/// The first entry of this slice is likely the function `Backtrace::new`,
/// and the last frame is likely something about how this thread or the main
/// function started.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn frames(&self) -> &[BacktraceFrame] {
/// If this backtrace was created from `new_unresolved` then this function
/// will resolve all addresses in the backtrace to their symbolic names.
///
/// If this backtrace has been previously resolved or was created through
/// `new`, this function does nothing.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn resolve(&mut self) {
/// Same as `Symbol::addr`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn addr(&self) -> Option<*mut c_void> {
/// Captures a backtrace at the callsite of this function, returning an
/// owned representation.
///
/// This function is useful for representing a backtrace as an object in
/// Rust. This returned value can be sent across threads and printed
/// elsewhere, and the purpose of this value is to be entirely self
/// contained.
///
/// Note that on some platforms acquiring a full backtrace and resolving it
/// can be extremely expensive. If the cost is too much for your application
/// it's recommended to instead use `Backtrace::new_unresolved()` which
/// avoids the symbol resolution step (which typically takes the longest)
/// and allows deferring that to a later date.
///
/// # Examples
///
/// ```
/// use backtrace::Backtrace;
///
/// let current_backtrace = Backtrace::new();
/// ```
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[inline(never)] // want to make sure there's a frame here to remove
/// Returns the file name where this function was defined.
///
/// This is currently only available when libbacktrace or gimli is being
/// used (e.g. unix platforms other) and when a binary is compiled with
/// debuginfo. If neither of these conditions is met then this will likely
/// return `None`.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[cfg(feature = "std")]
/// Same as `Symbol::name`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn name(&self) -> Option<SymbolName<'_>> {
/// Same as `Frame::module_base_address`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn module_base_address(&self) -> Option<*mut c_void> {
/// Same as `Frame::symbol_address`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn symbol_address(&self) -> *mut c_void {
/// Provides a `Path` representation of `BytesOrWideString`.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn into_path_buf(self) -> PathBuf {
/// Returns the file name where this function was defined.
///
/// This is currently only available when libbacktrace or gimli is being
/// used (e.g. unix platforms other) and when a binary is compiled with
/// debuginfo. If neither of these conditions is met then this will likely
/// return `None`.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[cfg(feature = "std")]
/// Similar to `new` except that this does not resolve any symbols, this
/// simply captures the backtrace as a list of addresses.
///
/// At a later time the `resolve` function can be called to resolve this
/// backtrace's symbols into readable names. This function exists because
/// the resolution process can sometimes take a significant amount of time
/// whereas any one backtrace may only be rarely printed.
///
/// # Examples
///
/// ```
/// use backtrace::Backtrace;
///
/// let mut current_backtrace = Backtrace::new_unresolved();
/// println!("{:?}", current_backtrace); // no symbol names
/// current_backtrace.resolve();
/// println!("{:?}", current_backtrace); // symbol names now present
/// ```
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[inline(never)] // want to make sure there's a frame here to remove
/// Prints a `BacktraceSymbol` within a `BacktraceFrame`.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[cfg(feature = "std")]
/// Same as `Symbol::filename`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn filename(&self) -> Option<&Path> {
/// Returns the list of symbols that this frame corresponds to.
///
/// Normally there is only one symbol per frame, but sometimes if a number
/// of functions are inlined into one frame then multiple symbols will be
/// returned. The first symbol listed is the "innermost function", whereas
/// the last symbol is the outermost (last caller).
///
/// Note that if this frame came from an unresolved backtrace then this will
/// return an empty list.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn symbols(&self) -> &[BacktraceSymbol] {
/// An attribute, like `#[repr(transparent)]`.
///
/// <br>
///
/// # Syntax
///
/// Rust has six types of attributes.
///
/// - Outer attributes like `#[repr(transparent)]`. These appear outside or
/// in front of the item they describe.
///
/// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
/// of the item they describe, usually a module.
///
/// - Outer one-line doc comments like `/// Example`.
///
/// - Inner one-line doc comments like `//! Please file an issue`.
///
/// - Outer documentation blocks `/** Example */`.
///
/// - Inner documentation blocks `/*! Please file an issue */`.
///
/// The `style` field of type `AttrStyle` distinguishes whether an attribute
/// is outer or inner.
///
/// Every attribute has a `path` that indicates the intended interpretation
/// of the rest of the attribute's contents. The path and the optional
/// additional contents are represented together in the `meta` field of the
/// attribute in three possible varieties:
///
/// - Meta::Path — attributes whose information content conveys just a
/// path, for example the `#[test]` attribute.
///
/// - Meta::List — attributes that carry arbitrary tokens after the
/// path, surrounded by a delimiter (parenthesis, bracket, or brace). For
/// example `#[derive(Copy)]` or `#[precondition(x < 5)]`.
///
/// - Meta::NameValue — attributes with an `=` sign after the path,
/// followed by a Rust expression. For example `#[path =
/// "sys/windows.rs"]`.
///
/// All doc comments are represented in the NameValue style with a path of
/// "doc", as this is how they are processed by the compiler and by
/// `macro_rules!` macros.
///
/// ```text
/// #[derive(Copy, Clone)]
/// ~~~~~~Path
/// ^^^^^^^^^^^^^^^^^^^Meta::List
///
/// #[path = "sys/windows.rs"]
/// ~~~~Path
/// ^^^^^^^^^^^^^^^^^^^^^^^Meta::NameValue
///
/// #[test]
/// ^^^^Meta::Path
/// ```
///
/// <br>
///
/// # Parsing from tokens to Attribute
///
/// This type does not implement the [`Parse`] trait and thus cannot be
/// parsed directly by [`ParseStream::parse`]. Instead use
/// [`ParseStream::call`] with one of the two parser functions
/// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on
/// which you intend to parse.
///
/// [`Parse`]: parse::Parse
/// [`ParseStream::parse`]: parse::ParseBuffer::parse
/// [`ParseStream::call`]: parse::ParseBuffer::call
///
/// ```
/// use syn::{Attribute, Ident, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Parses a unit struct with attributes.
/// //
/// // #[path = "s.tmpl"]
/// // struct S;
/// struct UnitStruct {
/// attrs: Vec<Attribute>,
/// struct_token: Token![struct],
/// name: Ident,
/// semi_token: Token![;],
/// }
///
/// impl Parse for UnitStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(UnitStruct {
/// attrs: input.call(Attribute::parse_outer)?,
/// struct_token: input.parse()?,
/// name: input.parse()?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// ```
///
/// <p><br></p>
///
/// # Parsing from Attribute to structured arguments
///
/// The grammar of attributes in Rust is very flexible, which makes the
/// syntax tree not that useful on its own. In particular, arguments of the
/// `Meta::List` variety of attribute are held in an arbitrary `tokens:
/// TokenStream`. Macros are expected to check the `path` of the attribute,
/// decide whether they recognize it, and then parse the remaining tokens
/// according to whatever grammar they wish to require for that kind of
/// attribute. Use [`parse_args()`] to parse those tokens into the expected
/// data structure.
///
/// [`parse_args()`]: Attribute::parse_args
///
/// <p><br></p>
///
/// # Doc comments
///
/// The compiler transforms doc comments, such as `/// comment` and `/*!
/// comment */`, into attributes before macros are expanded. Each comment is
/// expanded into an attribute of the form `#[doc = r"comment"]`.
///
/// As an example, the following `mod` items are expanded identically:
///
/// ```
/// # use syn::{ItemMod, parse_quote};
/// let doc: ItemMod = parse_quote! {
/// /// Single line doc comments
/// /// We write so many!
/// /**
/// * Multi-line comments...
/// * May span many lines
/// */
/// mod example {
/// //! Of course, they can be inner too
/// /*! And fit in a single line */
/// }
/// };
/// let attr: ItemMod = parse_quote! {
/// #[doc = r" Single line doc comments"]
/// #[doc = r" We write so many!"]
/// #[doc = r"
/// * Multi-line comments...
/// * May span many lines
/// "]
/// mod example {
/// #![doc = r" Of course, they can be inner too"]
/// #![doc = r" And fit in a single line "]
/// }
/// };
/// assert_eq!(doc, attr);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// Creates a new instance of [`Arg`] from a usage string. Allows creation of basic settings
/// for the [`Arg`]. The syntax is flexible, but there are some rules to follow.
///
/// **NOTE**: Not all settings may be set using the usage string method. Some properties are
/// only available via the builder pattern.
///
/// **NOTE**: Only ASCII values are officially supported in [`Arg::from_usage`] strings. Some
/// UTF-8 codepoints may work just fine, but this is not guaranteed.
///
/// # Syntax
///
/// Usage strings typically following the form:
///
/// ```notrust
/// [explicit name] [short] [long] [value names] [help string]
/// ```
///
/// This is not a hard rule as the attributes can appear in other orders. There are also
/// several additional sigils which denote additional settings. Below are the details of each
/// portion of the string.
///
/// ### Explicit Name
///
/// This is an optional field, if it's omitted the argument will use one of the additional
/// fields as the name using the following priority order:
///
/// * Explicit Name (This always takes precedence when present)
/// * Long
/// * Short
/// * Value Name
///
/// `clap` determines explicit names as the first string of characters between either `[]` or
/// `<>` where `[]` has the dual notation of meaning the argument is optional, and `<>` meaning
/// the argument is required.
///
/// Explicit names may be followed by:
/// * The multiple denotation `...`
///
/// Example explicit names as follows (`ename` for an optional argument, and `rname` for a
/// required argument):
///
/// ```notrust
/// [ename] -s, --long 'some flag'
/// <rname> -r, --longer 'some other flag'
/// ```
///
/// ### Short
///
/// This is set by placing a single character after a leading `-`.
///
/// Shorts may be followed by
/// * The multiple denotation `...`
/// * An optional comma `,` which is cosmetic only
/// * Value notation
///
/// Example shorts are as follows (`-s`, and `-r`):
///
/// ```notrust
/// -s, --long 'some flag'
/// <rname> -r [val], --longer 'some option'
/// ```
///
/// ### Long
///
/// This is set by placing a word (no spaces) after a leading `--`.
///
/// Shorts may be followed by
/// * The multiple denotation `...`
/// * Value notation
///
/// Example longs are as follows (`--some`, and `--rapid`):
///
/// ```notrust
/// -s, --some 'some flag'
/// --rapid=[FILE] 'some option'
/// ```
///
/// ### Values (Value Notation)
///
/// This is set by placing a word(s) between `[]` or `<>` optionally after `=` (although this
/// is cosmetic only and does not affect functionality). If an explicit name has **not** been
/// set, using `<>` will denote a required argument, and `[]` will denote an optional argument
///
/// Values may be followed by
/// * The multiple denotation `...`
/// * More Value notation
///
/// More than one value will also implicitly set the arguments number of values, i.e. having
/// two values, `--option [val1] [val2]` specifies that in order for option to be satisified it
/// must receive exactly two values
///
/// Example values are as follows (`FILE`, and `SPEED`):
///
/// ```notrust
/// -s, --some [FILE] 'some option'
/// --rapid=<SPEED>... 'some required multiple option'
/// ```
///
/// ### Help String
///
/// The help string is denoted between a pair of single quotes `''` and may contain any
/// characters.
///
/// Example help strings are as follows:
///
/// ```notrust
/// -s, --some [FILE] 'some option'
/// --rapid=<SPEED>... 'some required multiple option'
/// ```
///
/// ### Additional Sigils
///
/// Multiple notation `...` (three consecutive dots/periods) specifies that this argument may
/// be used multiple times. Do not confuse multiple occurrences (`...`) with multiple values.
/// `--option val1 val2` is a single occurrence with multiple values. `--flag --flag` is
/// multiple occurrences (and then you can obviously have instances of both as well)
///
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
/// App::new("prog")
/// .args(&[
/// Arg::from_usage("--config <FILE> 'a required file for the configuration and no short'"),
/// Arg::from_usage("-d, --debug... 'turns on debugging information and allows multiples'"),
/// Arg::from_usage("[input] 'an optional input file to use'")
/// ])
/// # ;
/// ```
/// [`Arg`]: ./struct.Arg.html
/// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
pub fn from_usage(u: &'a str) -> Self {
/// An attribute, like `#[repr(transparent)]`.
///
/// <br>
///
/// # Syntax
///
/// Rust has six types of attributes.
///
/// - Outer attributes like `#[repr(transparent)]`. These appear outside or
/// in front of the item they describe.
///
/// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
/// of the item they describe, usually a module.
///
/// - Outer one-line doc comments like `/// Example`.
///
/// - Inner one-line doc comments like `//! Please file an issue`.
///
/// - Outer documentation blocks `/** Example */`.
///
/// - Inner documentation blocks `/*! Please file an issue */`.
///
/// The `style` field of type `AttrStyle` distinguishes whether an attribute
/// is outer or inner.
///
/// Every attribute has a `path` that indicates the intended interpretation
/// of the rest of the attribute's contents. The path and the optional
/// additional contents are represented together in the `meta` field of the
/// attribute in three possible varieties:
///
/// - Meta::Path — attributes whose information content conveys just a
/// path, for example the `#[test]` attribute.
///
/// - Meta::List — attributes that carry arbitrary tokens after the
/// path, surrounded by a delimiter (parenthesis, bracket, or brace). For
/// example `#[derive(Copy)]` or `#[precondition(x < 5)]`.
///
/// - Meta::NameValue — attributes with an `=` sign after the path,
/// followed by a Rust expression. For example `#[path =
/// "sys/windows.rs"]`.
///
/// All doc comments are represented in the NameValue style with a path of
/// "doc", as this is how they are processed by the compiler and by
/// `macro_rules!` macros.
///
/// ```text
/// #[derive(Copy, Clone)]
/// ~~~~~~Path
/// ^^^^^^^^^^^^^^^^^^^Meta::List
///
/// #[path = "sys/windows.rs"]
/// ~~~~Path
/// ^^^^^^^^^^^^^^^^^^^^^^^Meta::NameValue
///
/// #[test]
/// ^^^^Meta::Path
/// ```
///
/// <br>
///
/// # Parsing from tokens to Attribute
///
/// This type does not implement the [`Parse`] trait and thus cannot be
/// parsed directly by [`ParseStream::parse`]. Instead use
/// [`ParseStream::call`] with one of the two parser functions
/// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on
/// which you intend to parse.
///
/// [`Parse`]: parse::Parse
/// [`ParseStream::parse`]: parse::ParseBuffer::parse
/// [`ParseStream::call`]: parse::ParseBuffer::call
///
/// ```
/// use syn::{Attribute, Ident, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Parses a unit struct with attributes.
/// //
/// // #[path = "s.tmpl"]
/// // struct S;
/// struct UnitStruct {
/// attrs: Vec<Attribute>,
/// struct_token: Token![struct],
/// name: Ident,
/// semi_token: Token![;],
/// }
///
/// impl Parse for UnitStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(UnitStruct {
/// attrs: input.call(Attribute::parse_outer)?,
/// struct_token: input.parse()?,
/// name: input.parse()?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// ```
///
/// <p><br></p>
///
/// # Parsing from Attribute to structured arguments
///
/// The grammar of attributes in Rust is very flexible, which makes the
/// syntax tree not that useful on its own. In particular, arguments of the
/// `Meta::List` variety of attribute are held in an arbitrary `tokens:
/// TokenStream`. Macros are expected to check the `path` of the attribute,
/// decide whether they recognize it, and then parse the remaining tokens
/// according to whatever grammar they wish to require for that kind of
/// attribute. Use [`parse_args()`] to parse those tokens into the expected
/// data structure.
///
/// [`parse_args()`]: Attribute::parse_args
///
/// <p><br></p>
///
/// # Doc comments
///
/// The compiler transforms doc comments, such as `/// comment` and `/*!
/// comment */`, into attributes before macros are expanded. Each comment is
/// expanded into an attribute of the form `#[doc = r"comment"]`.
///
/// As an example, the following `mod` items are expanded identically:
///
/// ```
/// # use syn::{ItemMod, parse_quote};
/// let doc: ItemMod = parse_quote! {
/// /// Single line doc comments
/// /// We write so many!
/// /**
/// * Multi-line comments...
/// * May span many lines
/// */
/// mod example {
/// //! Of course, they can be inner too
/// /*! And fit in a single line */
/// }
/// };
/// let attr: ItemMod = parse_quote! {
/// #[doc = r" Single line doc comments"]
/// #[doc = r" We write so many!"]
/// #[doc = r"
/// * Multi-line comments...
/// * May span many lines
/// "]
/// mod example {
/// #![doc = r" Of course, they can be inner too"]
/// #![doc = r" And fit in a single line "]
/// }
/// };
/// assert_eq!(doc, attr);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// Generate an impl block for the given struct. This impl block will
/// automatically use hygiene tricks to avoid polluting the caller's
/// namespace, and will automatically add trait bounds for generic type
/// parameters.
///
/// # Syntax
///
/// This function accepts its arguments as a `TokenStream`. The recommended way
/// to call this function is passing the result of invoking the `quote!`
/// macro to it.
///
/// ```ignore
/// s.gen_impl(quote! {
/// // You can write any items which you want to import into scope here.
/// // For example, you may want to include an `extern crate` for the
/// // crate which implements your trait. These items will only be
/// // visible to the code you generate, and won't be exposed to the
/// // consuming crate
/// extern crate krate;
///
/// // You can also add `use` statements here to bring types or traits
/// // into scope.
/// //
/// // WARNING: Try not to use common names here, because the stable
/// // version of syn does not support hygiene and you could accidentally
/// // shadow types from the caller crate.
/// use krate::Trait as MyTrait;
///
/// // The actual impl block is a `gen impl` or `gen unsafe impl` block.
/// // You can use `@Self` to refer to the structure's type.
/// gen impl MyTrait for @Self {
/// fn f(&self) { ... }
/// }
/// })
/// ```
///
/// The most common usage of this trait involves loading the crate the
/// target trait comes from with `extern crate`, and then invoking a `gen
/// impl` block.
///
/// # Hygiene
///
/// This method tries to handle hygiene intelligenly for both stable and
/// unstable proc-macro implementations, however there are visible
/// differences.
///
/// The output of every `gen_impl` function is wrapped in a dummy `const`
/// value, to ensure that it is given its own scope, and any values brought
/// into scope are not leaked to the calling crate.
///
/// By default, the above invocation may generate an output like the
/// following:
///
/// ```ignore
/// const _DERIVE_krate_Trait_FOR_Struct: () = {
/// extern crate krate;
/// use krate::Trait as MyTrait;
/// impl<T> MyTrait for Struct<T> where T: MyTrait {
/// fn f(&self) { ... }
/// }
/// };
/// ```
///
/// The `Structure` may also be confired with the [`underscore_const`] method
/// to generate `const _` instead.
///
/// ```ignore
/// const _: () = {
/// extern crate krate;
/// use krate::Trait as MyTrait;
/// impl<T> MyTrait for Struct<T> where T: MyTrait {
/// fn f(&self) { ... }
/// }
/// };
/// ```
///
/// ### Using the `std` crate
///
/// If you are using `quote!()` to implement your trait, with the
/// `proc-macro2/nightly` feature, `std` isn't considered to be in scope for
/// your macro. This means that if you use types from `std` in your
/// procedural macro, you'll want to explicitly load it with an `extern
/// crate std;`.
///
/// ### Absolute paths
///
/// You should generally avoid using absolute paths in your generated code,
/// as they will resolve very differently when using the stable and nightly
/// versions of `proc-macro2`. Instead, load the crates you need to use
/// explictly with `extern crate` and
///
/// # Trait Bounds
///
/// This method will automatically add trait bounds for any type parameters
/// which are referenced within the types of non-ignored fields.
///
/// Additional type parameters may be added with the generics syntax after
/// the `impl` keyword.
///
/// ### Type Macro Caveat
///
/// If the method contains any macros in type position, all parameters will
/// be considered bound. This is because we cannot determine which type
/// parameters are bound by type macros.
///
/// # Errors
///
/// This function will generate a `compile_error!` if additional type
/// parameters added by `impl<..>` conflict with generic type parameters on
/// the original struct.
///
/// # Panics
///
/// This function will panic if the input `TokenStream` is not well-formed.
///
/// # Example Usage
///
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A<T, U> {
/// B(T),
/// C(Option<U>),
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.filter_variants(|v| v.ast().ident != "B");
///
/// assert_eq!(
/// s.gen_impl(quote! {
/// extern crate krate;
/// gen impl krate::Trait for @Self {
/// fn a() {}
/// }
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// impl<T, U> krate::Trait for A<T, U>
/// where
/// Option<U>: krate::Trait,
/// U: krate::Trait
/// {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
///
/// // NOTE: You can also add extra generics after the impl
/// assert_eq!(
/// s.gen_impl(quote! {
/// extern crate krate;
/// gen impl<X: krate::OtherTrait> krate::Trait<X> for @Self
/// where
/// X: Send + Sync,
/// {
/// fn a() {}
/// }
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// const _DERIVE_krate_Trait_X_FOR_A: () = {
/// extern crate krate;
/// impl<X: krate::OtherTrait, T, U> krate::Trait<X> for A<T, U>
/// where
/// X: Send + Sync,
/// Option<U>: krate::Trait<X>,
/// U: krate::Trait<X>
/// {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
///
/// // NOTE: you can generate multiple traits with a single call
/// assert_eq!(
/// s.gen_impl(quote! {
/// extern crate krate;
///
/// gen impl krate::Trait for @Self {
/// fn a() {}
/// }
///
/// gen impl krate::OtherTrait for @Self {
/// fn b() {}
/// }
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// impl<T, U> krate::Trait for A<T, U>
/// where
/// Option<U>: krate::Trait,
/// U: krate::Trait
/// {
/// fn a() {}
/// }
///
/// impl<T, U> krate::OtherTrait for A<T, U>
/// where
/// Option<U>: krate::OtherTrait,
/// U: krate::OtherTrait
/// {
/// fn b() {}
/// }
/// };
/// }.to_string()
/// );
/// ```
///
/// Use `add_bounds` to change which bounds are generated.
pub fn gen_impl(&self, cfg: TokenStream) -> TokenStream {
/// An attribute like `#[repr(transparent)]`.
///
/// *This type is available only if Syn is built with the `"derive"` or `"full"`
/// feature.*
///
/// <br>
///
/// # Syntax
///
/// Rust has six types of attributes.
///
/// - Outer attributes like `#[repr(transparent)]`. These appear outside or
/// in front of the item they describe.
/// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
/// of the item they describe, usually a module.
/// - Outer doc comments like `/// # Example`.
/// - Inner doc comments like `//! Please file an issue`.
/// - Outer block comments `/** # Example */`.
/// - Inner block comments `/*! Please file an issue */`.
///
/// The `style` field of type `AttrStyle` distinguishes whether an attribute
/// is outer or inner. Doc comments and block comments are promoted to
/// attributes, as this is how they are processed by the compiler and by
/// `macro_rules!` macros.
///
/// The `path` field gives the possibly colon-delimited path against which
/// the attribute is resolved. It is equal to `"doc"` for desugared doc
/// comments. The `tokens` field contains the rest of the attribute body as
/// tokens.
///
/// ```text
/// #[derive(Copy)] #[crate::precondition x < 5]
/// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~
/// path tokens path tokens
/// ```
///
/// <br>
///
/// # Parsing from tokens to Attribute
///
/// This type does not implement the [`Parse`] trait and thus cannot be
/// parsed directly by [`ParseStream::parse`]. Instead use
/// [`ParseStream::call`] with one of the two parser functions
/// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on
/// which you intend to parse.
///
/// [`Parse`]: parse::Parse
/// [`ParseStream::parse`]: parse::ParseBuffer::parse
/// [`ParseStream::call`]: parse::ParseBuffer::call
///
/// ```
/// use syn::{Attribute, Ident, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Parses a unit struct with attributes.
/// //
/// // #[path = "s.tmpl"]
/// // struct S;
/// struct UnitStruct {
/// attrs: Vec<Attribute>,
/// struct_token: Token![struct],
/// name: Ident,
/// semi_token: Token![;],
/// }
///
/// impl Parse for UnitStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(UnitStruct {
/// attrs: input.call(Attribute::parse_outer)?,
/// struct_token: input.parse()?,
/// name: input.parse()?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// ```
///
/// <p><br></p>
///
/// # Parsing from Attribute to structured arguments
///
/// The grammar of attributes in Rust is very flexible, which makes the
/// syntax tree not that useful on its own. In particular, arguments of the
/// attribute are held in an arbitrary `tokens: TokenStream`. Macros are
/// expected to check the `path` of the attribute, decide whether they
/// recognize it, and then parse the remaining tokens according to whatever
/// grammar they wish to require for that kind of attribute.
///
/// If the attribute you are parsing is expected to conform to the
/// conventional structured form of attribute, use [`parse_meta()`] to
/// obtain that structured representation. If the attribute follows some
/// other grammar of its own, use [`parse_args()`] to parse that into the
/// expected data structure.
///
/// [`parse_meta()`]: Attribute::parse_meta
/// [`parse_args()`]: Attribute::parse_args
///
/// <p><br></p>
///
/// # Doc comments
///
/// The compiler transforms doc comments, such as `/// comment` and `/*!
/// comment */`, into attributes before macros are expanded. Each comment is
/// expanded into an attribute of the form `#[doc = r"comment"]`.
///
/// As an example, the following `mod` items are expanded identically:
///
/// ```
/// # use syn::{ItemMod, parse_quote};
/// let doc: ItemMod = parse_quote! {
/// /// Single line doc comments
/// /// We write so many!
/// /**
/// * Multi-line comments...
/// * May span many lines
/// */
/// mod example {
/// //! Of course, they can be inner too
/// /*! And fit in a single line */
/// }
/// };
/// let attr: ItemMod = parse_quote! {
/// #[doc = r" Single line doc comments"]
/// #[doc = r" We write so many!"]
/// #[doc = r"
/// * Multi-line comments...
/// * May span many lines
/// "]
/// mod example {
/// #![doc = r" Of course, they can be inner too"]
/// #![doc = r" And fit in a single line "]
/// }
/// };
/// assert_eq!(doc, attr);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// Does not advance the position of the parse stream.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(Ident)` *(does not accept keywords)*
/// - `input.peek(Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
///
/// # Example
///
/// In this example we finish parsing the list of supertraits when the next
/// token in the input is either `where` or an opening curly brace.
///
/// ```
/// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parses a trait definition containing no associated items.
/// //
/// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
/// struct MarkerTrait {
/// trait_token: Token![trait],
/// ident: Ident,
/// generics: Generics,
/// colon_token: Option<Token![:]>,
/// supertraits: Punctuated<TypeParamBound, Token![+]>,
/// brace_token: token::Brace,
/// }
///
/// impl Parse for MarkerTrait {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let trait_token: Token![trait] = input.parse()?;
/// let ident: Ident = input.parse()?;
/// let mut generics: Generics = input.parse()?;
/// let colon_token: Option<Token![:]> = input.parse()?;
///
/// let mut supertraits = Punctuated::new();
/// if colon_token.is_some() {
/// loop {
/// supertraits.push_value(input.parse()?);
/// if input.peek(Token![where]) || input.peek(token::Brace) {
/// break;
/// }
/// supertraits.push_punct(input.parse()?);
/// }
/// }
///
/// generics.where_clause = input.parse()?;
/// let content;
/// let empty_brace_token = braced!(content in input);
///
/// Ok(MarkerTrait {
/// trait_token,
/// ident,
/// generics,
/// colon_token,
/// supertraits,
/// brace_token: empty_brace_token,
/// })
/// }
/// }
/// ```
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// Does not advance the position of the parse stream.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(Ident)` *(does not accept keywords)*
/// - `input.peek(Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
///
/// # Example
///
/// In this example we finish parsing the list of supertraits when the next
/// token in the input is either `where` or an opening curly brace.
///
/// ```
/// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parses a trait definition containing no associated items.
/// //
/// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
/// struct MarkerTrait {
/// trait_token: Token![trait],
/// ident: Ident,
/// generics: Generics,
/// colon_token: Option<Token![:]>,
/// supertraits: Punctuated<TypeParamBound, Token![+]>,
/// brace_token: token::Brace,
/// }
///
/// impl Parse for MarkerTrait {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let trait_token: Token![trait] = input.parse()?;
/// let ident: Ident = input.parse()?;
/// let mut generics: Generics = input.parse()?;
/// let colon_token: Option<Token![:]> = input.parse()?;
///
/// let mut supertraits = Punctuated::new();
/// if colon_token.is_some() {
/// loop {
/// supertraits.push_value(input.parse()?);
/// if input.peek(Token![where]) || input.peek(token::Brace) {
/// break;
/// }
/// supertraits.push_punct(input.parse()?);
/// }
/// }
///
/// generics.where_clause = input.parse()?;
/// let content;
/// let empty_brace_token = braced!(content in input);
///
/// Ok(MarkerTrait {
/// trait_token,
/// ident,
/// generics,
/// colon_token,
/// supertraits,
/// brace_token: empty_brace_token,
/// })
/// }
/// }
/// ```
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// An attribute, like `#[repr(transparent)]`.
///
/// <br>
///
/// # Syntax
///
/// Rust has six types of attributes.
///
/// - Outer attributes like `#[repr(transparent)]`. These appear outside or
/// in front of the item they describe.
///
/// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
/// of the item they describe, usually a module.
///
/// - Outer one-line doc comments like `/// Example`.
///
/// - Inner one-line doc comments like `//! Please file an issue`.
///
/// - Outer documentation blocks `/** Example */`.
///
/// - Inner documentation blocks `/*! Please file an issue */`.
///
/// The `style` field of type `AttrStyle` distinguishes whether an attribute
/// is outer or inner.
///
/// Every attribute has a `path` that indicates the intended interpretation
/// of the rest of the attribute's contents. The path and the optional
/// additional contents are represented together in the `meta` field of the
/// attribute in three possible varieties:
///
/// - Meta::Path — attributes whose information content conveys just a
/// path, for example the `#[test]` attribute.
///
/// - Meta::List — attributes that carry arbitrary tokens after the
/// path, surrounded by a delimiter (parenthesis, bracket, or brace). For
/// example `#[derive(Copy)]` or `#[precondition(x < 5)]`.
///
/// - Meta::NameValue — attributes with an `=` sign after the path,
/// followed by a Rust expression. For example `#[path =
/// "sys/windows.rs"]`.
///
/// All doc comments are represented in the NameValue style with a path of
/// "doc", as this is how they are processed by the compiler and by
/// `macro_rules!` macros.
///
/// ```text
/// #[derive(Copy, Clone)]
/// ~~~~~~Path
/// ^^^^^^^^^^^^^^^^^^^Meta::List
///
/// #[path = "sys/windows.rs"]
/// ~~~~Path
/// ^^^^^^^^^^^^^^^^^^^^^^^Meta::NameValue
///
/// #[test]
/// ^^^^Meta::Path
/// ```
///
/// <br>
///
/// # Parsing from tokens to Attribute
///
/// This type does not implement the [`Parse`] trait and thus cannot be
/// parsed directly by [`ParseStream::parse`]. Instead use
/// [`ParseStream::call`] with one of the two parser functions
/// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on
/// which you intend to parse.
///
/// [`Parse`]: crate::parse::Parse
/// [`ParseStream::parse`]: crate::parse::ParseBuffer::parse
/// [`ParseStream::call`]: crate::parse::ParseBuffer::call
///
/// ```
/// use syn::{Attribute, Ident, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Parses a unit struct with attributes.
/// //
/// // #[path = "s.tmpl"]
/// // struct S;
/// struct UnitStruct {
/// attrs: Vec<Attribute>,
/// struct_token: Token![struct],
/// name: Ident,
/// semi_token: Token![;],
/// }
///
/// impl Parse for UnitStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(UnitStruct {
/// attrs: input.call(Attribute::parse_outer)?,
/// struct_token: input.parse()?,
/// name: input.parse()?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// ```
///
/// <p><br></p>
///
/// # Parsing from Attribute to structured arguments
///
/// The grammar of attributes in Rust is very flexible, which makes the
/// syntax tree not that useful on its own. In particular, arguments of the
/// `Meta::List` variety of attribute are held in an arbitrary `tokens:
/// TokenStream`. Macros are expected to check the `path` of the attribute,
/// decide whether they recognize it, and then parse the remaining tokens
/// according to whatever grammar they wish to require for that kind of
/// attribute. Use [`parse_args()`] to parse those tokens into the expected
/// data structure.
///
/// [`parse_args()`]: Attribute::parse_args
///
/// <p><br></p>
///
/// # Doc comments
///
/// The compiler transforms doc comments, such as `/// comment` and `/*!
/// comment */`, into attributes before macros are expanded. Each comment is
/// expanded into an attribute of the form `#[doc = r"comment"]`.
///
/// As an example, the following `mod` items are expanded identically:
///
/// ```
/// # use syn::{ItemMod, parse_quote};
/// let doc: ItemMod = parse_quote! {
/// /// Single line doc comments
/// /// We write so many!
/// /**
/// * Multi-line comments...
/// * May span many lines
/// */
/// mod example {
/// //! Of course, they can be inner too
/// /*! And fit in a single line */
/// }
/// };
/// let attr: ItemMod = parse_quote! {
/// #[doc = r" Single line doc comments"]
/// #[doc = r" We write so many!"]
/// #[doc = r"
/// * Multi-line comments...
/// * May span many lines
/// "]
/// mod example {
/// #![doc = r" Of course, they can be inner too"]
/// #![doc = r" And fit in a single line "]
/// }
/// };
/// assert_eq!(doc, attr);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// Does not advance the position of the parse stream.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(syn::Ident)` *(does not accept keywords)*
/// - `input.peek(syn::Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
///
/// # Example
///
/// In this example we finish parsing the list of supertraits when the next
/// token in the input is either `where` or an opening curly brace.
///
/// ```
/// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parses a trait definition containing no associated items.
/// //
/// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
/// struct MarkerTrait {
/// trait_token: Token![trait],
/// ident: Ident,
/// generics: Generics,
/// colon_token: Option<Token![:]>,
/// supertraits: Punctuated<TypeParamBound, Token![+]>,
/// brace_token: token::Brace,
/// }
///
/// impl Parse for MarkerTrait {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let trait_token: Token![trait] = input.parse()?;
/// let ident: Ident = input.parse()?;
/// let mut generics: Generics = input.parse()?;
/// let colon_token: Option<Token![:]> = input.parse()?;
///
/// let mut supertraits = Punctuated::new();
/// if colon_token.is_some() {
/// loop {
/// supertraits.push_value(input.parse()?);
/// if input.peek(Token![where]) || input.peek(token::Brace) {
/// break;
/// }
/// supertraits.push_punct(input.parse()?);
/// }
/// }
///
/// generics.where_clause = input.parse()?;
/// let content;
/// let empty_brace_token = braced!(content in input);
///
/// Ok(MarkerTrait {
/// trait_token,
/// ident,
/// generics,
/// colon_token,
/// supertraits,
/// brace_token: empty_brace_token,
/// })
/// }
/// }
/// ```
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// Does not advance the position of the parse stream.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(Ident)` *(does not accept keywords)*
/// - `input.peek(Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
///
/// # Example
///
/// In this example we finish parsing the list of supertraits when the next
/// token in the input is either `where` or an opening curly brace.
///
/// ```
/// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parses a trait definition containing no associated items.
/// //
/// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
/// struct MarkerTrait {
/// trait_token: Token![trait],
/// ident: Ident,
/// generics: Generics,
/// colon_token: Option<Token![:]>,
/// supertraits: Punctuated<TypeParamBound, Token![+]>,
/// brace_token: token::Brace,
/// }
///
/// impl Parse for MarkerTrait {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let trait_token: Token![trait] = input.parse()?;
/// let ident: Ident = input.parse()?;
/// let mut generics: Generics = input.parse()?;
/// let colon_token: Option<Token![:]> = input.parse()?;
///
/// let mut supertraits = Punctuated::new();
/// if colon_token.is_some() {
/// loop {
/// supertraits.push_value(input.parse()?);
/// if input.peek(Token![where]) || input.peek(token::Brace) {
/// break;
/// }
/// supertraits.push_punct(input.parse()?);
/// }
/// }
///
/// generics.where_clause = input.parse()?;
/// let content;
/// let empty_brace_token = braced!(content in input);
///
/// Ok(MarkerTrait {
/// trait_token,
/// ident,
/// generics,
/// colon_token,
/// supertraits,
/// brace_token: empty_brace_token,
/// })
/// }
/// }
/// ```
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(Ident)` *(does not accept keywords)*
/// - `input.peek(Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// An attribute, like `#[repr(transparent)]`.
///
/// <br>
///
/// # Syntax
///
/// Rust has six types of attributes.
///
/// - Outer attributes like `#[repr(transparent)]`. These appear outside or
/// in front of the item they describe.
///
/// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
/// of the item they describe, usually a module.
///
/// - Outer one-line doc comments like `/// Example`.
///
/// - Inner one-line doc comments like `//! Please file an issue`.
///
/// - Outer documentation blocks `/** Example */`.
///
/// - Inner documentation blocks `/*! Please file an issue */`.
///
/// The `style` field of type `AttrStyle` distinguishes whether an attribute
/// is outer or inner.
///
/// Every attribute has a `path` that indicates the intended interpretation
/// of the rest of the attribute's contents. The path and the optional
/// additional contents are represented together in the `meta` field of the
/// attribute in three possible varieties:
///
/// - Meta::Path — attributes whose information content conveys just a
/// path, for example the `#[test]` attribute.
///
/// - Meta::List — attributes that carry arbitrary tokens after the
/// path, surrounded by a delimiter (parenthesis, bracket, or brace). For
/// example `#[derive(Copy)]` or `#[precondition(x < 5)]`.
///
/// - Meta::NameValue — attributes with an `=` sign after the path,
/// followed by a Rust expression. For example `#[path =
/// "sys/windows.rs"]`.
///
/// All doc comments are represented in the NameValue style with a path of
/// "doc", as this is how they are processed by the compiler and by
/// `macro_rules!` macros.
///
/// ```text
/// #[derive(Copy, Clone)]
/// ~~~~~~Path
/// ^^^^^^^^^^^^^^^^^^^Meta::List
///
/// #[path = "sys/windows.rs"]
/// ~~~~Path
/// ^^^^^^^^^^^^^^^^^^^^^^^Meta::NameValue
///
/// #[test]
/// ^^^^Meta::Path
/// ```
///
/// <br>
///
/// # Parsing from tokens to Attribute
///
/// This type does not implement the [`Parse`] trait and thus cannot be
/// parsed directly by [`ParseStream::parse`]. Instead use
/// [`ParseStream::call`] with one of the two parser functions
/// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on
/// which you intend to parse.
///
/// [`Parse`]: parse::Parse
/// [`ParseStream::parse`]: parse::ParseBuffer::parse
/// [`ParseStream::call`]: parse::ParseBuffer::call
///
/// ```
/// use syn::{Attribute, Ident, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Parses a unit struct with attributes.
/// //
/// // #[path = "s.tmpl"]
/// // struct S;
/// struct UnitStruct {
/// attrs: Vec<Attribute>,
/// struct_token: Token![struct],
/// name: Ident,
/// semi_token: Token![;],
/// }
///
/// impl Parse for UnitStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(UnitStruct {
/// attrs: input.call(Attribute::parse_outer)?,
/// struct_token: input.parse()?,
/// name: input.parse()?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// ```
///
/// <p><br></p>
///
/// # Parsing from Attribute to structured arguments
///
/// The grammar of attributes in Rust is very flexible, which makes the
/// syntax tree not that useful on its own. In particular, arguments of the
/// `Meta::List` variety of attribute are held in an arbitrary `tokens:
/// TokenStream`. Macros are expected to check the `path` of the attribute,
/// decide whether they recognize it, and then parse the remaining tokens
/// according to whatever grammar they wish to require for that kind of
/// attribute. Use [`parse_args()`] to parse those tokens into the expected
/// data structure.
///
/// [`parse_args()`]: Attribute::parse_args
///
/// <p><br></p>
///
/// # Doc comments
///
/// The compiler transforms doc comments, such as `/// comment` and `/*!
/// comment */`, into attributes before macros are expanded. Each comment is
/// expanded into an attribute of the form `#[doc = r"comment"]`.
///
/// As an example, the following `mod` items are expanded identically:
///
/// ```
/// # use syn::{ItemMod, parse_quote};
/// let doc: ItemMod = parse_quote! {
/// /// Single line doc comments
/// /// We write so many!
/// /**
/// * Multi-line comments...
/// * May span many lines
/// */
/// mod example {
/// //! Of course, they can be inner too
/// /*! And fit in a single line */
/// }
/// };
/// let attr: ItemMod = parse_quote! {
/// #[doc = r" Single line doc comments"]
/// #[doc = r" We write so many!"]
/// #[doc = r"
/// * Multi-line comments...
/// * May span many lines
/// "]
/// mod example {
/// #![doc = r" Of course, they can be inner too"]
/// #![doc = r" And fit in a single line "]
/// }
/// };
/// assert_eq!(doc, attr);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// Does not advance the position of the parse stream.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(syn::Ident)` *(does not accept keywords)*
/// - `input.peek(syn::Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
///
/// # Example
///
/// In this example we finish parsing the list of supertraits when the next
/// token in the input is either `where` or an opening curly brace.
///
/// ```
/// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parses a trait definition containing no associated items.
/// //
/// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
/// struct MarkerTrait {
/// trait_token: Token![trait],
/// ident: Ident,
/// generics: Generics,
/// colon_token: Option<Token![:]>,
/// supertraits: Punctuated<TypeParamBound, Token![+]>,
/// brace_token: token::Brace,
/// }
///
/// impl Parse for MarkerTrait {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let trait_token: Token![trait] = input.parse()?;
/// let ident: Ident = input.parse()?;
/// let mut generics: Generics = input.parse()?;
/// let colon_token: Option<Token![:]> = input.parse()?;
///
/// let mut supertraits = Punctuated::new();
/// if colon_token.is_some() {
/// loop {
/// supertraits.push_value(input.parse()?);
/// if input.peek(Token![where]) || input.peek(token::Brace) {
/// break;
/// }
/// supertraits.push_punct(input.parse()?);
/// }
/// }
///
/// generics.where_clause = input.parse()?;
/// let content;
/// let empty_brace_token = braced!(content in input);
///
/// Ok(MarkerTrait {
/// trait_token,
/// ident,
/// generics,
/// colon_token,
/// supertraits,
/// brace_token: empty_brace_token,
/// })
/// }
/// }
/// ```
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(Ident)` *(does not accept keywords)*
/// - `input.peek(Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// Does not advance the position of the parse stream.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(syn::Ident)` *(does not accept keywords)*
/// - `input.peek(syn::Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
///
/// # Example
///
/// In this example we finish parsing the list of supertraits when the next
/// token in the input is either `where` or an opening curly brace.
///
/// ```
/// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parses a trait definition containing no associated items.
/// //
/// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
/// struct MarkerTrait {
/// trait_token: Token![trait],
/// ident: Ident,
/// generics: Generics,
/// colon_token: Option<Token![:]>,
/// supertraits: Punctuated<TypeParamBound, Token![+]>,
/// brace_token: token::Brace,
/// }
///
/// impl Parse for MarkerTrait {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let trait_token: Token![trait] = input.parse()?;
/// let ident: Ident = input.parse()?;
/// let mut generics: Generics = input.parse()?;
/// let colon_token: Option<Token![:]> = input.parse()?;
///
/// let mut supertraits = Punctuated::new();
/// if colon_token.is_some() {
/// loop {
/// supertraits.push_value(input.parse()?);
/// if input.peek(Token![where]) || input.peek(token::Brace) {
/// break;
/// }
/// supertraits.push_punct(input.parse()?);
/// }
/// }
///
/// generics.where_clause = input.parse()?;
/// let content;
/// let empty_brace_token = braced!(content in input);
///
/// Ok(MarkerTrait {
/// trait_token,
/// ident,
/// generics,
/// colon_token,
/// supertraits,
/// brace_token: empty_brace_token,
/// })
/// }
/// }
/// ```
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// Does not advance the position of the parse stream.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(syn::Ident)` *(does not accept keywords)*
/// - `input.peek(syn::Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
///
/// # Example
///
/// In this example we finish parsing the list of supertraits when the next
/// token in the input is either `where` or an opening curly brace.
///
/// ```
/// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parses a trait definition containing no associated items.
/// //
/// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
/// struct MarkerTrait {
/// trait_token: Token![trait],
/// ident: Ident,
/// generics: Generics,
/// colon_token: Option<Token![:]>,
/// supertraits: Punctuated<TypeParamBound, Token![+]>,
/// brace_token: token::Brace,
/// }
///
/// impl Parse for MarkerTrait {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let trait_token: Token![trait] = input.parse()?;
/// let ident: Ident = input.parse()?;
/// let mut generics: Generics = input.parse()?;
/// let colon_token: Option<Token![:]> = input.parse()?;
///
/// let mut supertraits = Punctuated::new();
/// if colon_token.is_some() {
/// loop {
/// supertraits.push_value(input.parse()?);
/// if input.peek(Token![where]) || input.peek(token::Brace) {
/// break;
/// }
/// supertraits.push_punct(input.parse()?);
/// }
/// }
///
/// generics.where_clause = input.parse()?;
/// let content;
/// let empty_brace_token = braced!(content in input);
///
/// Ok(MarkerTrait {
/// trait_token,
/// ident,
/// generics,
/// colon_token,
/// supertraits,
/// brace_token: empty_brace_token,
/// })
/// }
/// }
/// ```
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// An attribute like `#[repr(transparent)]`.
///
/// *This type is available only if Syn is built with the `"derive"` or `"full"`
/// feature.*
///
/// <br>
///
/// # Syntax
///
/// Rust has six types of attributes.
///
/// - Outer attributes like `#[repr(transparent)]`. These appear outside or
/// in front of the item they describe.
/// - Inner attributes like `#![feature(proc_macro)]`. These appear inside
/// of the item they describe, usually a module.
/// - Outer doc comments like `/// # Example`.
/// - Inner doc comments like `//! Please file an issue`.
/// - Outer block comments `/** # Example */`.
/// - Inner block comments `/*! Please file an issue */`.
///
/// The `style` field of type `AttrStyle` distinguishes whether an attribute
/// is outer or inner. Doc comments and block comments are promoted to
/// attributes, as this is how they are processed by the compiler and by
/// `macro_rules!` macros.
///
/// The `path` field gives the possibly colon-delimited path against which
/// the attribute is resolved. It is equal to `"doc"` for desugared doc
/// comments. The `tokens` field contains the rest of the attribute body as
/// tokens.
///
/// ```text
/// #[derive(Copy)] #[crate::precondition x < 5]
/// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~
/// path tokens path tokens
/// ```
///
/// <br>
///
/// # Parsing from tokens to Attribute
///
/// This type does not implement the [`Parse`] trait and thus cannot be
/// parsed directly by [`ParseStream::parse`]. Instead use
/// [`ParseStream::call`] with one of the two parser functions
/// [`Attribute::parse_outer`] or [`Attribute::parse_inner`] depending on
/// which you intend to parse.
///
/// [`Parse`]: parse::Parse
/// [`ParseStream::parse`]: parse::ParseBuffer::parse
/// [`ParseStream::call`]: parse::ParseBuffer::call
///
/// ```
/// use syn::{Attribute, Ident, Result, Token};
/// use syn::parse::{Parse, ParseStream};
///
/// // Parses a unit struct with attributes.
/// //
/// // #[path = "s.tmpl"]
/// // struct S;
/// struct UnitStruct {
/// attrs: Vec<Attribute>,
/// struct_token: Token![struct],
/// name: Ident,
/// semi_token: Token![;],
/// }
///
/// impl Parse for UnitStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(UnitStruct {
/// attrs: input.call(Attribute::parse_outer)?,
/// struct_token: input.parse()?,
/// name: input.parse()?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// ```
///
/// <p><br></p>
///
/// # Parsing from Attribute to structured arguments
///
/// The grammar of attributes in Rust is very flexible, which makes the
/// syntax tree not that useful on its own. In particular, arguments of the
/// attribute are held in an arbitrary `tokens: TokenStream`. Macros are
/// expected to check the `path` of the attribute, decide whether they
/// recognize it, and then parse the remaining tokens according to whatever
/// grammar they wish to require for that kind of attribute.
///
/// If the attribute you are parsing is expected to conform to the
/// conventional structured form of attribute, use [`parse_meta()`] to
/// obtain that structured representation. If the attribute follows some
/// other grammar of its own, use [`parse_args()`] to parse that into the
/// expected data structure.
///
/// [`parse_meta()`]: Attribute::parse_meta
/// [`parse_args()`]: Attribute::parse_args
///
/// <p><br></p>
///
/// # Doc comments
///
/// The compiler transforms doc comments, such as `/// comment` and `/*!
/// comment */`, into attributes before macros are expanded. Each comment is
/// expanded into an attribute of the form `#[doc = r"comment"]`.
///
/// As an example, the following `mod` items are expanded identically:
///
/// ```
/// # use syn::{ItemMod, parse_quote};
/// let doc: ItemMod = parse_quote! {
/// /// Single line doc comments
/// /// We write so many!
/// /**
/// * Multi-line comments...
/// * May span many lines
/// */
/// mod example {
/// //! Of course, they can be inner too
/// /*! And fit in a single line */
/// }
/// };
/// let attr: ItemMod = parse_quote! {
/// #[doc = r" Single line doc comments"]
/// #[doc = r" We write so many!"]
/// #[doc = r"
/// * Multi-line comments...
/// * May span many lines
/// "]
/// mod example {
/// #![doc = r" Of course, they can be inner too"]
/// #![doc = r" And fit in a single line "]
/// }
/// };
/// assert_eq!(doc, attr);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(any(feature = "full", feature = "derive"))))]
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// Does not advance the position of the parse stream.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(Ident)` *(does not accept keywords)*
/// - `input.peek(Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
///
/// # Example
///
/// In this example we finish parsing the list of supertraits when the next
/// token in the input is either `where` or an opening curly brace.
///
/// ```
/// use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parses a trait definition containing no associated items.
/// //
/// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
/// struct MarkerTrait {
/// trait_token: Token![trait],
/// ident: Ident,
/// generics: Generics,
/// colon_token: Option<Token![:]>,
/// supertraits: Punctuated<TypeParamBound, Token![+]>,
/// brace_token: token::Brace,
/// }
///
/// impl Parse for MarkerTrait {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let trait_token: Token![trait] = input.parse()?;
/// let ident: Ident = input.parse()?;
/// let mut generics: Generics = input.parse()?;
/// let colon_token: Option<Token![:]> = input.parse()?;
///
/// let mut supertraits = Punctuated::new();
/// if colon_token.is_some() {
/// loop {
/// supertraits.push_value(input.parse()?);
/// if input.peek(Token![where]) || input.peek(token::Brace) {
/// break;
/// }
/// supertraits.push_punct(input.parse()?);
/// }
/// }
///
/// generics.where_clause = input.parse()?;
/// let content;
/// let empty_brace_token = braced!(content in input);
///
/// Ok(MarkerTrait {
/// trait_token,
/// ident,
/// generics,
/// colon_token,
/// supertraits,
/// brace_token: empty_brace_token,
/// })
/// }
/// }
/// ```
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// Looks at the next token in the parse stream to determine whether it
/// matches the requested type of token.
///
/// # Syntax
///
/// Note that this method does not use turbofish syntax. Pass the peek type
/// inside of parentheses.
///
/// - `input.peek(Token![struct])`
/// - `input.peek(Token![==])`
/// - `input.peek(Ident)` *(does not accept keywords)*
/// - `input.peek(Ident::peek_any)`
/// - `input.peek(Lifetime)`
/// - `input.peek(token::Brace)`
pub fn peek<T: Peek>(&self, token: T) -> bool {
/// Get the value for a given key.
///
/// If the key appears multiple times in the source then which key is returned
/// is implementation specific.
///
/// # Implementation notes
///
/// A source that can provide a more efficient implementation of this method
/// should override it.
#[cfg(not(test))]
/// Count the number of key-value pairs that can be visited.
///
/// # Implementation notes
///
/// A source that knows the number of key-value pairs upfront may provide a more
/// efficient implementation.
///
/// A subsequent call to `visit` should yield the same number of key-value pairs
/// to the visitor, unless that visitor fails part way through.
fn count(&self) -> usize {
/// Count the number of key-values that can be visited.
///
/// # Implementation notes
///
/// A source that knows the number of key-values upfront may provide a more
/// efficient implementation.
///
/// A subsequent call to `visit` should yield the same number of key-values.
fn count(&self) -> usize {
/// Returns the bounds on the remaining length of the async iterator.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
/// A [`None`] here means that either there is no known upper bound, or the
/// upper bound is larger than [`usize`].
///
/// # Implementation notes
///
/// It is not enforced that an async iterator implementation yields the declared
/// number of elements. A buggy async iterator may yield less than the lower bound
/// or more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the async iterator, but must not be
/// trusted to e.g., omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
/// That said, the implementation should provide a correct estimation,
/// because otherwise it would be a violation of the trait's protocol.
///
/// The default implementation returns <code>(0, [None])</code> which is correct for any
/// async iterator.
#[inline]
/// Get the value for a given key.
///
/// If the key appears multiple times in the source then which key is returned
/// is implementation specific.
///
/// # Implementation notes
///
/// A source that can provide a more efficient implementation of this method
/// should override it.
fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
/// Visit key-value pairs.
///
/// A source doesn't have to guarantee any ordering or uniqueness of key-value pairs.
/// If the given visitor returns an error then the source may early-return with it,
/// even if there are more key-value pairs.
///
/// # Implementation notes
///
/// A source should yield the same key-value pairs to a subsequent visitor unless
/// that visitor itself fails.
fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error>;
/// Clears texture to zero.
///
/// Note that unlike with clear_buffer, `COPY_DST` usage is not required.
///
/// # Implementation notes
///
/// - implemented either via buffer copies and render/depth target clear, path depends on texture usages
/// - behaves like texture zero init, but is performed immediately (clearing is *not* delayed via marking it as uninitialized)
///
/// # Panics
///
/// - `CLEAR_TEXTURE` extension not enabled
/// - Range is out of bounds
pub fn clear_texture(&mut self, texture: &Texture, subresource_range: &ImageSubresourceRange) {
/// Visit key-values.
///
/// A source doesn't have to guarantee any ordering or uniqueness of key-values.
/// If the given visitor returns an error then the source may early-return with it,
/// even if there are more key-values.
///
/// # Implementation notes
///
/// A source should yield the same key-values to a subsequent visitor unless
/// that visitor itself fails.
fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error>;
/// Returns the bounds on the remaining length of the stream.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
/// A [`None`] here means that either there is no known upper bound, or the
/// upper bound is larger than [`usize`].
///
/// # Implementation notes
///
/// It is not enforced that a stream implementation yields the declared
/// number of elements. A buggy stream may yield less than the lower bound
/// or more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the stream, but must not be
/// trusted to e.g., omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
/// That said, the implementation should provide a correct estimation,
/// because otherwise it would be a violation of the trait's protocol.
///
/// The default implementation returns `(0, `[`None`]`)` which is correct for any
/// stream.
#[inline]
/// Count the number of key-value pairs that can be visited.
///
/// # Implementation notes
///
/// A source that knows the number of key-value pairs upfront may provide a more
/// efficient implementation.
///
/// A subsequent call to `visit` should yield the same number of key-value pairs
/// to the visitor, unless that visitor fails part way through.
#[cfg(not(test))]
/// Visit key-value pairs.
///
/// A source doesn't have to guarantee any ordering or uniqueness of key-value pairs.
/// If the given visitor returns an error then the source may early-return with it,
/// even if there are more key-value pairs.
///
/// # Implementation notes
///
/// A source should yield the same key-value pairs to a subsequent visitor unless
/// that visitor itself fails.
fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error>;
/// Get the value for a given key.
///
/// If the key appears multiple times in the source then which key is returned
/// is implementation specific.
///
/// # Implementation notes
///
/// A source that can provide a more efficient implementation of this method
/// should override it.
fn get(&self, key: Key) -> Option<Value<'_>> {
/// Returns the bounds on the remaining length of the iterator.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
/// A [`None`] here means that either there is no known upper bound, or the
/// upper bound is larger than [`usize`].
///
/// # Implementation notes
///
/// It is not enforced that an iterator implementation yields the declared
/// number of elements. A buggy iterator may yield less than the lower bound
/// or more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the iterator, but must not be
/// trusted to e.g., omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
/// That said, the implementation should provide a correct estimation,
/// because otherwise it would be a violation of the trait's protocol.
///
/// The default implementation returns <code>(0, [None])</code> which is correct for any
/// iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let mut iter = a.iter();
///
/// assert_eq!((3, Some(3)), iter.size_hint());
/// let _ = iter.next();
/// assert_eq!((2, Some(2)), iter.size_hint());
/// ```
///
/// A more complex example:
///
/// ```
/// // The even numbers in the range of zero to nine.
/// let iter = (0..10).filter(|x| x % 2 == 0);
///
/// // We might iterate from zero to ten times. Knowing that it's five
/// // exactly wouldn't be possible without executing filter().
/// assert_eq!((0, Some(10)), iter.size_hint());
///
/// // Let's add five more numbers with chain()
/// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
///
/// // now both bounds are increased by five
/// assert_eq!((5, Some(15)), iter.size_hint());
/// ```
///
/// Returning `None` for an upper bound:
///
/// ```
/// // an infinite iterator has no upper bound
/// // and the maximum possible lower bound
/// let iter = 0..;
///
/// assert_eq!((usize::MAX, None), iter.size_hint());
/// ```
#[inline]
/// Count the number of key-value pairs that can be visited.
///
/// # Implementation notes
///
/// A source that knows the number of key-value pairs upfront may provide a more
/// efficient implementation.
///
/// A subsequent call to `visit` should yield the same number of key-value pairs
/// to the visitor, unless that visitor fails part way through.
#[cfg(not(test))]
/// Get the value for a given key.
///
/// If the key appears multiple times in the source then which key is returned
/// is implementation specific.
///
/// # Implementation notes
///
/// A source that can provide a more efficient implementation of this method
/// should override it.
#[cfg(not(test))]
/// Returns the bounds on the remaining length of the stream.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
/// A [`None`] here means that either there is no known upper bound, or the
/// upper bound is larger than [`usize`].
///
/// # Implementation notes
///
/// It is not enforced that a stream implementation yields the declared
/// number of elements. A buggy stream may yield less than the lower bound
/// or more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the stream, but must not be
/// trusted to e.g., omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
/// That said, the implementation should provide a correct estimation,
/// because otherwise it would be a violation of the trait's protocol.
///
/// The default implementation returns `(0, `[`None`]`)` which is correct for any
/// stream.
#[inline]
/// Visit key-value pairs.
///
/// A source doesn't have to guarantee any ordering or uniqueness of key-value pairs.
/// If the given visitor returns an error then the source may early-return with it,
/// even if there are more key-value pairs.
///
/// # Implementation notes
///
/// A source should yield the same key-value pairs to a subsequent visitor unless
/// that visitor itself fails.
fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error>;
/// Configure how the runtime responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the runtime's
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the runtime's execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the runtime to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`Runtime::block_on`] will panic.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a runtime configured to shutdown on
/// panic. The first spawned task panics and results in the runtime
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `block_on` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::{self, UnhandledPanic};
///
/// # pub fn main() {
/// let rt = runtime::Builder::new_current_thread()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .build()
/// .unwrap();
///
/// rt.spawn(async { panic!("boom"); });
/// rt.spawn(async {
/// // This task never completes.
/// });
///
/// rt.block_on(async {
/// // Do some work
/// # loop { tokio::task::yield_now().await; }
/// })
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: UnhandledPanic) -> &mut Self {
/// Configure how the runtime responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the runtime's
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the runtime's execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the runtime to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`Runtime::block_on`] will panic.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a runtime configured to shutdown on
/// panic. The first spawned task panics and results in the runtime
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `block_on` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::{self, UnhandledPanic};
///
/// # pub fn main() {
/// let rt = runtime::Builder::new_current_thread()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .build()
/// .unwrap();
///
/// rt.spawn(async { panic!("boom"); });
/// rt.spawn(async {
/// // This task never completes.
/// });
///
/// rt.block_on(async {
/// // Do some work
/// # loop { tokio::task::yield_now().await; }
/// })
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: UnhandledPanic) -> &mut Self {
/// Configure how the `LocalSet` responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the `LocalSet`'s
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the `LocalSet`'s execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the `LocalSet` to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`LocalSet::block_on`] and [`LocalSet::run_until`] will panic.
///
/// # Panics
///
/// This method panics if called after the `LocalSet` has started
/// running.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a `LocalSet` configured to shutdown on
/// panic. The first spawned task panics and results in the `LocalSet`
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `run_until` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::UnhandledPanic;
///
/// # #[tokio::main]
/// # async fn main() {
/// tokio::task::LocalSet::new()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .run_until(async {
/// tokio::task::spawn_local(async { panic!("boom"); });
/// tokio::task::spawn_local(async {
/// // This task never completes
/// });
///
/// // Do some work, but `run_until` will panic before it completes
/// # loop { tokio::task::yield_now().await; }
/// })
/// .await;
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: crate::runtime::UnhandledPanic) -> &mut Self {
/// Configure how the runtime responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the runtime's
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the runtime's execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the runtime to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`Runtime::block_on`] will panic.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a runtime configured to shutdown on
/// panic. The first spawned task panics and results in the runtime
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `block_on` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::{self, UnhandledPanic};
///
/// # pub fn main() {
/// let rt = runtime::Builder::new_current_thread()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .build()
/// .unwrap();
///
/// rt.spawn(async { panic!("boom"); });
/// rt.spawn(async {
/// // This task never completes.
/// });
///
/// rt.block_on(async {
/// // Do some work
/// # loop { tokio::task::yield_now().await; }
/// })
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: UnhandledPanic) -> &mut Self {
/// Configure how the `LocalSet` responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the `LocalSet`'s
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the `LocalSet`'s execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the `LocalSet` to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`LocalSet::block_on`] and [`LocalSet::run_until`] will panic.
///
/// # Panics
///
/// This method panics if called after the `LocalSet` has started
/// running.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a `LocalSet` configured to shutdown on
/// panic. The first spawned task panics and results in the `LocalSet`
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `run_until` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::UnhandledPanic;
///
/// # #[tokio::main]
/// # async fn main() {
/// tokio::task::LocalSet::new()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .run_until(async {
/// tokio::task::spawn_local(async { panic!("boom"); });
/// tokio::task::spawn_local(async {
/// // This task never completes
/// });
///
/// // Do some work, but `run_until` will panic before it completes
/// # loop { tokio::task::yield_now().await; }
/// })
/// .await;
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: crate::runtime::UnhandledPanic) -> &mut Self {
/// Disables the LIFO task scheduler heuristic.
///
/// The multi-threaded scheduler includes a heuristic for optimizing
/// message-passing patterns. This heuristic results in the **last**
/// scheduled task being polled first.
///
/// To implement this heuristic, each worker thread has a slot which
/// holds the task that should be polled next. However, this slot cannot
/// be stolen by other worker threads, which can result in lower total
/// throughput when tasks tend to have longer poll times.
///
/// This configuration option will disable this heuristic resulting in
/// all scheduled tasks being pushed into the worker-local queue, which
/// is stealable.
///
/// Consider trying this option when the task "scheduled" time is high
/// but the runtime is underutilized. Use tokio-rs/tokio-metrics to
/// collect this data.
///
/// # Unstable
///
/// This configuration option is considered a workaround for the LIFO
/// slot not being stealable. When the slot becomes stealable, we will
/// revisit whether or not this option is necessary. See
/// tokio-rs/tokio#4941.
///
/// # Examples
///
/// ```
/// use tokio::runtime;
///
/// let rt = runtime::Builder::new_multi_thread()
/// .disable_lifo_slot()
/// .build()
/// .unwrap();
/// ```
pub fn disable_lifo_slot(&mut self) -> &mut Self {
/// Configure how the runtime responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the runtime's
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the runtime's execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the runtime to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`Runtime::block_on`] will panic.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a runtime configured to shutdown on
/// panic. The first spawned task panics and results in the runtime
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `block_on` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::{self, UnhandledPanic};
///
/// # pub fn main() {
/// let rt = runtime::Builder::new_current_thread()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .build()
/// .unwrap();
///
/// rt.spawn(async { panic!("boom"); });
/// rt.spawn(async {
/// // This task never completes.
/// });
///
/// rt.block_on(async {
/// // Do some work
/// # loop { tokio::task::yield_now().await; }
/// })
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: UnhandledPanic) -> &mut Self {
/// Configure how the `LocalSet` responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the `LocalSet`'s
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the `LocalSet`'s execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the `LocalSet` to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`LocalSet::block_on`] and [`LocalSet::run_until`] will panic.
///
/// # Panics
///
/// This method panics if called after the `LocalSet` has started
/// running.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a `LocalSet` configured to shutdown on
/// panic. The first spawned task panics and results in the `LocalSet`
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `run_until` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::UnhandledPanic;
///
/// # #[tokio::main]
/// # async fn main() {
/// tokio::task::LocalSet::new()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .run_until(async {
/// tokio::task::spawn_local(async { panic!("boom"); });
/// tokio::task::spawn_local(async {
/// // This task never completes
/// });
///
/// // Do some work, but `run_until` will panic before it completes
/// # loop { tokio::task::yield_now().await; }
/// })
/// .await;
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: crate::runtime::UnhandledPanic) -> &mut Self {
/// Disables the LIFO task scheduler heuristic.
///
/// The multi-threaded scheduler includes a heuristic for optimizing
/// message-passing patterns. This heuristic results in the **last**
/// scheduled task being polled first.
///
/// To implement this heuristic, each worker thread has a slot which
/// holds the task that should be polled next. However, this slot cannot
/// be stolen by other worker threads, which can result in lower total
/// throughput when tasks tend to have longer poll times.
///
/// This configuration option will disable this heuristic resulting in
/// all scheduled tasks being pushed into the worker-local queue, which
/// is stealable.
///
/// Consider trying this option when the task "scheduled" time is high
/// but the runtime is underutilized. Use tokio-rs/tokio-metrics to
/// collect this data.
///
/// # Unstable
///
/// This configuration option is considered a workaround for the LIFO
/// slot not being stealable. When the slot becomes stealable, we will
/// revisit whether or not this option is necessary. See
/// tokio-rs/tokio#4941.
///
/// # Examples
///
/// ```
/// use tokio::runtime;
///
/// let rt = runtime::Builder::new_multi_thread()
/// .disable_lifo_slot()
/// .build()
/// .unwrap();
/// ```
pub fn disable_lifo_slot(&mut self) -> &mut Self {
/// Disables the LIFO task scheduler heuristic.
///
/// The multi-threaded scheduler includes a heuristic for optimizing
/// message-passing patterns. This heuristic results in the **last**
/// scheduled task being polled first.
///
/// To implement this heuristic, each worker thread has a slot which
/// holds the task that should be polled next. However, this slot cannot
/// be stolen by other worker threads, which can result in lower total
/// throughput when tasks tend to have longer poll times.
///
/// This configuration option will disable this heuristic resulting in
/// all scheduled tasks being pushed into the worker-local queue, which
/// is stealable.
///
/// Consider trying this option when the task "scheduled" time is high
/// but the runtime is underutilized. Use tokio-rs/tokio-metrics to
/// collect this data.
///
/// # Unstable
///
/// This configuration option is considered a workaround for the LIFO
/// slot not being stealable. When the slot becomes stealable, we will
/// revisit whether or not this option is necessary. See
/// tokio-rs/tokio#4941.
///
/// # Examples
///
/// ```
/// use tokio::runtime;
///
/// let rt = runtime::Builder::new_multi_thread()
/// .disable_lifo_slot()
/// .build()
/// .unwrap();
/// ```
pub fn disable_lifo_slot(&mut self) -> &mut Self {
/// Configure how the `LocalSet` responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the `LocalSet`'s
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the `LocalSet`'s execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the `LocalSet` to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`LocalSet::block_on`] and [`LocalSet::run_until`] will panic.
///
/// # Panics
///
/// This method panics if called after the `LocalSet` has started
/// running.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a `LocalSet` configured to shutdown on
/// panic. The first spawned task panics and results in the `LocalSet`
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `run_until` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::UnhandledPanic;
///
/// # #[tokio::main]
/// # async fn main() {
/// tokio::task::LocalSet::new()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .run_until(async {
/// tokio::task::spawn_local(async { panic!("boom"); });
/// tokio::task::spawn_local(async {
/// // This task never completes
/// });
///
/// // Do some work, but `run_until` will panic before it completes
/// # loop { tokio::task::yield_now().await; }
/// })
/// .await;
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: crate::runtime::UnhandledPanic) -> &mut Self {
/// Disables the LIFO task scheduler heuristic.
///
/// The multi-threaded scheduler includes a heuristic for optimizing
/// message-passing patterns. This heuristic results in the **last**
/// scheduled task being polled first.
///
/// To implement this heuristic, each worker thread has a slot which
/// holds the task that should be polled next. However, this slot cannot
/// be stolen by other worker threads, which can result in lower total
/// throughput when tasks tend to have longer poll times.
///
/// This configuration option will disable this heuristic resulting in
/// all scheduled tasks being pushed into the worker-local queue, which
/// is stealable.
///
/// Consider trying this option when the task "scheduled" time is high
/// but the runtime is underutilized. Use tokio-rs/tokio-metrics to
/// collect this data.
///
/// # Unstable
///
/// This configuration option is considered a workaround for the LIFO
/// slot not being stealable. When the slot becomes stealable, we will
/// revisit whether or not this option is necessary. See
/// tokio-rs/tokio#4941.
///
/// # Examples
///
/// ```
/// use tokio::runtime;
///
/// let rt = runtime::Builder::new_multi_thread()
/// .disable_lifo_slot()
/// .build()
/// .unwrap();
/// ```
pub fn disable_lifo_slot(&mut self) -> &mut Self {
/// Configure how the runtime responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the runtime's
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the runtime's execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the runtime to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`Runtime::block_on`] will panic.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a runtime configured to shutdown on
/// panic. The first spawned task panics and results in the runtime
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `block_on` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::{self, UnhandledPanic};
///
/// # pub fn main() {
/// let rt = runtime::Builder::new_current_thread()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .build()
/// .unwrap();
///
/// rt.spawn(async { panic!("boom"); });
/// rt.spawn(async {
/// // This task never completes.
/// });
///
/// rt.block_on(async {
/// // Do some work
/// # loop { tokio::task::yield_now().await; }
/// })
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: UnhandledPanic) -> &mut Self {
/// Configure how the `LocalSet` responds to an unhandled panic on a
/// spawned task.
///
/// By default, an unhandled panic (i.e. a panic not caught by
/// [`std::panic::catch_unwind`]) has no impact on the `LocalSet`'s
/// execution. The panic is error value is forwarded to the task's
/// [`JoinHandle`] and all other spawned tasks continue running.
///
/// The `unhandled_panic` option enables configuring this behavior.
///
/// * `UnhandledPanic::Ignore` is the default behavior. Panics on
/// spawned tasks have no impact on the `LocalSet`'s execution.
/// * `UnhandledPanic::ShutdownRuntime` will force the `LocalSet` to
/// shutdown immediately when a spawned task panics even if that
/// task's `JoinHandle` has not been dropped. All other spawned tasks
/// will immediately terminate and further calls to
/// [`LocalSet::block_on`] and [`LocalSet::run_until`] will panic.
///
/// # Panics
///
/// This method panics if called after the `LocalSet` has started
/// running.
///
/// # Unstable
///
/// This option is currently unstable and its implementation is
/// incomplete. The API may change or be removed in the future. See
/// tokio-rs/tokio#4516 for more details.
///
/// # Examples
///
/// The following demonstrates a `LocalSet` configured to shutdown on
/// panic. The first spawned task panics and results in the `LocalSet`
/// shutting down. The second spawned task never has a chance to
/// execute. The call to `run_until` will panic due to the runtime being
/// forcibly shutdown.
///
/// ```should_panic
/// use tokio::runtime::UnhandledPanic;
///
/// # #[tokio::main]
/// # async fn main() {
/// tokio::task::LocalSet::new()
/// .unhandled_panic(UnhandledPanic::ShutdownRuntime)
/// .run_until(async {
/// tokio::task::spawn_local(async { panic!("boom"); });
/// tokio::task::spawn_local(async {
/// // This task never completes
/// });
///
/// // Do some work, but `run_until` will panic before it completes
/// # loop { tokio::task::yield_now().await; }
/// })
/// .await;
/// # }
/// ```
///
/// [`JoinHandle`]: struct@crate::task::JoinHandle
pub fn unhandled_panic(&mut self, behavior: crate::runtime::UnhandledPanic) -> &mut Self {
/// Disables the LIFO task scheduler heuristic.
///
/// The multi-threaded scheduler includes a heuristic for optimizing
/// message-passing patterns. This heuristic results in the **last**
/// scheduled task being polled first.
///
/// To implement this heuristic, each worker thread has a slot which
/// holds the task that should be polled next. However, this slot cannot
/// be stolen by other worker threads, which can result in lower total
/// throughput when tasks tend to have longer poll times.
///
/// This configuration option will disable this heuristic resulting in
/// all scheduled tasks being pushed into the worker-local queue, which
/// is stealable.
///
/// Consider trying this option when the task "scheduled" time is high
/// but the runtime is underutilized. Use tokio-rs/tokio-metrics to
/// collect this data.
///
/// # Unstable
///
/// This configuration option is considered a workaround for the LIFO
/// slot not being stealable. When the slot becomes stealable, we will
/// revisit whether or not this option is necessary. See
/// tokio-rs/tokio#4941.
///
/// # Examples
///
/// ```
/// use tokio::runtime;
///
/// let rt = runtime::Builder::new_multi_thread()
/// .disable_lifo_slot()
/// .build()
/// .unwrap();
/// ```
pub fn disable_lifo_slot(&mut self) -> &mut Self {
/// Ensures that the buffer contains at least enough space to hold `len +
/// additional` elements. If it doesn't already, will reallocate the
/// minimum possible amount of memory necessary. Generally this will be
/// exactly the amount of memory necessary, but in principle the allocator
/// is free to give back more than we asked for.
///
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
/// the requested space. This is not really unsafe, but the unsafe code
/// *you* write that relies on the behavior of this function may break.
///
/// # Panics
///
/// Panics if the new capacity exceeds `isize::MAX` bytes.
///
/// # Aborts
///
/// Aborts on OOM.
#[cfg(not(no_global_oom_handling))]
/// Ensures that the buffer contains at least enough space to hold
/// `used_cap + needed_extra_cap` elements. If it doesn't already have
/// enough capacity, will reallocate enough space plus comfortable slack
/// space to get amortized `O(1)` behavior. Will limit this behavior
/// if it would needlessly cause itself to panic.
///
/// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
/// the requested space. This is not really unsafe, but the unsafe
/// code *you* write that relies on the behavior of this function may break.
///
/// This is ideal for implementing a bulk-push operation like `extend`.
///
/// # Panics
///
/// * Panics if the requested capacity exceeds `usize::MAX` bytes.
/// * Panics on 32-bit platforms if the requested capacity exceeds
/// `isize::MAX` bytes.
///
/// # Aborts
///
/// Aborts on OOM
///
/// # Examples
///
/// ```ignore
/// # #![feature(alloc, raw_vec_internals)]
/// # extern crate alloc;
/// # use std::ptr;
/// # use alloc::raw_vec::RawVec;
/// struct MyVec<T> {
/// buf: RawVec<T>,
/// len: usize,
/// }
///
/// impl<T: Clone> MyVec<T> {
/// pub fn push_all(&mut self, elems: &[T]) {
/// self.buf.reserve(self.len, elems.len());
/// // reserve would have aborted or panicked if the len exceeded
/// // `isize::MAX` so this is safe to do unchecked now.
/// for x in elems {
/// unsafe {
/// ptr::write(self.buf.ptr().add(self.len), x.clone());
/// }
/// self.len += 1;
/// }
/// }
/// }
/// # fn main() {
/// # let mut vector = MyVec { buf: RawVec::new(), len: 0 };
/// # vector.push_all(&[1, 3, 5, 7, 9]);
/// # }
/// ```
pub fn reserve(&mut self, used_cap: usize, needed_extra_cap: usize) {
/// Shrinks the buffer down to the specified capacity. If the given amount
/// is 0, actually completely deallocates.
///
/// # Panics
///
/// Panics if the given amount is *larger* than the current capacity.
///
/// # Aborts
///
/// Aborts on OOM.
#[cfg(not(no_global_oom_handling))]
/// Creates a `RawVec` (on the system heap) with exactly the
/// capacity and alignment requirements for a `[T; capacity]`. This is
/// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is
/// zero-sized. Note that if `T` is zero-sized this means you will
/// *not* get a `RawVec` with the requested capacity.
///
/// # Panics
///
/// Panics if the requested capacity exceeds `isize::MAX` bytes.
///
/// # Aborts
///
/// Aborts on OOM.
#[cfg(not(no_global_oom_handling))]
/// Shrinks the buffer down to the specified capacity. If the given amount
/// is 0, actually completely deallocates.
///
/// # Panics
///
/// Panics if the given amount is *larger* than the current capacity.
///
/// # Aborts
///
/// Aborts on OOM.
#[cfg(not(no_global_oom_handling))]
/// Ensures that the buffer contains at least enough space to hold
/// `used_cap + needed_extra_cap` elements. If it doesn't already,
/// will reallocate the minimum possible amount of memory necessary.
/// Generally this will be exactly the amount of memory necessary,
/// but in principle the allocator is free to give back more than
/// we asked for.
///
/// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate
/// the requested space. This is not really unsafe, but the unsafe
/// code *you* write that relies on the behavior of this function may break.
///
/// # Panics
///
/// * Panics if the requested capacity exceeds `usize::MAX` bytes.
/// * Panics on 32-bit platforms if the requested capacity exceeds
/// `isize::MAX` bytes.
///
/// # Aborts
///
/// Aborts on OOM
pub fn reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize) {
/// Ensures that the buffer contains at least enough space to hold `len +
/// additional` elements. If it doesn't already have enough capacity, will
/// reallocate enough space plus comfortable slack space to get amortized
/// *O*(1) behavior. Will limit this behavior if it would needlessly cause
/// itself to panic.
///
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
/// the requested space. This is not really unsafe, but the unsafe
/// code *you* write that relies on the behavior of this function may break.
///
/// This is ideal for implementing a bulk-push operation like `extend`.
///
/// # Panics
///
/// Panics if the new capacity exceeds `isize::MAX` _bytes_.
///
/// # Aborts
///
/// Aborts on OOM.
#[cfg(not(no_global_oom_handling))]
/// Creates a `RawVec` (on the system heap) with exactly the
/// capacity and alignment requirements for a `[T; capacity]`. This is
/// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is
/// zero-sized. Note that if `T` is zero-sized this means you will
/// *not* get a `RawVec` with the requested capacity.
///
/// # Panics
///
/// Panics if the requested capacity exceeds `isize::MAX` bytes.
///
/// # Aborts
///
/// Aborts on OOM.
#[cfg(not(any(no_global_oom_handling, test)))]
/// Doubles the size of the type's backing allocation. This is common enough
/// to want to do that it's easiest to just have a dedicated method. Slightly
/// more efficient logic can be provided for this than the general case.
///
/// This function is ideal for when pushing elements one-at-a-time because
/// you don't need to incur the costs of the more general computations
/// reserve needs to do to guard against overflow. You do however need to
/// manually check if your `len == cap`.
///
/// # Panics
///
/// * Panics if T is zero-sized on the assumption that you managed to exhaust
/// all `usize::MAX` slots in your imaginary buffer.
/// * Panics on 32-bit platforms if the requested capacity exceeds
/// `isize::MAX` bytes.
///
/// # Aborts
///
/// Aborts on OOM
///
/// # Examples
///
/// ```ignore
/// # #![feature(alloc, raw_vec_internals)]
/// # extern crate alloc;
/// # use std::ptr;
/// # use alloc::raw_vec::RawVec;
/// struct MyVec<T> {
/// buf: RawVec<T>,
/// len: usize,
/// }
///
/// impl<T> MyVec<T> {
/// pub fn push(&mut self, elem: T) {
/// if self.len == self.buf.cap() { self.buf.double(); }
/// // double would have aborted or panicked if the len exceeded
/// // `isize::MAX` so this is safe to do unchecked now.
/// unsafe {
/// ptr::write(self.buf.ptr().add(self.len), elem);
/// }
/// self.len += 1;
/// }
/// }
/// # fn main() {
/// # let mut vec = MyVec { buf: RawVec::new(), len: 0 };
/// # vec.push(1);
/// # }
/// ```
#[inline(never)]
/// Ensures that the buffer contains at least enough space to hold `len +
/// additional` elements. If it doesn't already, will reallocate the
/// minimum possible amount of memory necessary. Generally this will be
/// exactly the amount of memory necessary, but in principle the allocator
/// is free to give back more than we asked for.
///
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
/// the requested space. This is not really unsafe, but the unsafe code
/// *you* write that relies on the behavior of this function may break.
///
/// # Panics
///
/// Panics if the new capacity exceeds `isize::MAX` _bytes_.
///
/// # Aborts
///
/// Aborts on OOM.
#[cfg(not(no_global_oom_handling))]
/// Ensures that the buffer contains at least enough space to hold `len +
/// additional` elements. If it doesn't already have enough capacity, will
/// reallocate enough space plus comfortable slack space to get amortized
/// *O*(1) behavior. Will limit this behavior if it would needlessly cause
/// itself to panic.
///
/// If `len` exceeds `self.capacity()`, this may fail to actually allocate
/// the requested space. This is not really unsafe, but the unsafe
/// code *you* write that relies on the behavior of this function may break.
///
/// This is ideal for implementing a bulk-push operation like `extend`.
///
/// # Panics
///
/// Panics if the new capacity exceeds `isize::MAX` bytes.
///
/// # Aborts
///
/// Aborts on OOM.
#[cfg(not(no_global_oom_handling))]
/// Shrinks the allocation down to the specified amount. If the given amount
/// is 0, actually completely deallocates.
///
/// # Panics
///
/// Panics if the given amount is *larger* than the current capacity.
///
/// # Aborts
///
/// Aborts on OOM.
pub fn shrink_to_fit(&mut self, amount: usize) {
/// use camino::Utf8Path;
/// use std::os::unix::fs::symlink;
///
/// let link_path = Utf8Path::new("link");
/// symlink("/origin_does_not_exist/", link_path).unwrap();
/// assert_eq!(link_path.is_symlink(), true);
/// assert_eq!(link_path.exists(), false);
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`Utf8Path::symlink_metadata`] and handle its [`Result`]. Then call
/// [`fs::Metadata::is_symlink`] if it was [`Ok`].
#[must_use]
/// Parses zero or more occurrences of `T` separated by punctuation of type
/// `P`, with optional trailing punctuation.
///
/// Parsing continues until the end of this parse stream. The entire content
/// of this parse stream must consist of `T` and `P`.
///
/// # Example
///
/// ```
/// # use quote::quote;
/// #
/// use syn::{parenthesized, token, Ident, Result, Token, Type};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parse a simplified tuple struct syntax like:
/// //
/// // struct S(A, B);
/// struct TupleStruct {
/// struct_token: Token![struct],
/// ident: Ident,
/// paren_token: token::Paren,
/// fields: Punctuated<Type, Token![,]>,
/// semi_token: Token![;],
/// }
///
/// impl Parse for TupleStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let content;
/// Ok(TupleStruct {
/// struct_token: input.parse()?,
/// ident: input.parse()?,
/// paren_token: parenthesized!(content in input),
/// fields: content.parse_terminated(Type::parse, Token![,])?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// #
/// # let input = quote! {
/// # struct S(A, B);
/// # };
/// # syn::parse2::<TupleStruct>(input).unwrap();
/// ```
///
/// # See also
///
/// If your separator is anything more complicated than an invocation of the
/// `Token!` macro, this method won't be applicable and you can instead
/// directly use `Punctuated`'s parser functions: [`parse_terminated`],
/// [`parse_separated_nonempty`] etc.
///
/// [`parse_terminated`]: Punctuated::parse_terminated
/// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
///
/// ```
/// use syn::{custom_keyword, Expr, Result, Token};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// mod kw {
/// syn::custom_keyword!(fin);
/// }
///
/// struct Fin(kw::fin, Token![;]);
///
/// impl Parse for Fin {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(Self(input.parse()?, input.parse()?))
/// }
/// }
///
/// struct Thing {
/// steps: Punctuated<Expr, Fin>,
/// }
///
/// impl Parse for Thing {
/// fn parse(input: ParseStream) -> Result<Self> {
/// # if true {
/// Ok(Thing {
/// steps: Punctuated::parse_terminated(input)?,
/// })
/// # } else {
/// // or equivalently, this means the same thing:
/// # Ok(Thing {
/// steps: input.call(Punctuated::parse_terminated)?,
/// # })
/// # }
/// }
/// }
/// ```
pub fn parse_terminated<T, P>(
/// Returns `true` if the path exists on disk and is pointing at a directory.
///
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
/// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
/// assert_eq!(Utf8Path::new("./is_a_directory/").is_dir(), true);
/// assert_eq!(Utf8Path::new("a_file.txt").is_dir(), false);
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
/// [`fs::Metadata::is_dir`] if it was [`Ok`].
#[must_use]
/// Spawns a job into the fork-join scope `self`. This job will
/// execute sometime before the fork-join scope completes. The
/// job is specified as a closure, and this closure receives its
/// own reference to the scope `self` as argument. This can be
/// used to inject new jobs into `self`.
///
/// # See also
///
/// This method is akin to [`Scope::spawn()`], but with a FIFO
/// priority. The [`scope_fifo` function] has more details about
/// this distinction.
///
/// [`Scope::spawn()`]: struct.Scope.html#method.spawn
/// [`scope_fifo` function]: fn.scope_fifo.html
pub fn spawn_fifo<BODY>(&self, body: BODY)
/// Returns `true` if the path exists on disk and is pointing at a directory.
///
/// This function will traverse symbolic links to query information about the
/// destination file.
///
/// If you cannot access the metadata of the file, e.g. because of a
/// permission error or broken symbolic links, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
/// assert_eq!(Path::new("a_file.txt").is_dir(), false);
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
/// [`fs::Metadata::is_dir`] if it was [`Ok`].
#[stable(feature = "path_ext", since = "1.5.0")]
/// Returns `true` if the path exists on disk and is pointing at a regular file.
///
/// This function will traverse symbolic links to query information about the
/// destination file.
///
/// If you cannot access the metadata of the file, e.g. because of a
/// permission error or broken symbolic links, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// assert_eq!(Path::new("./is_a_directory/").is_file(), false);
/// assert_eq!(Path::new("a_file.txt").is_file(), true);
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
/// [`fs::Metadata::is_file`] if it was [`Ok`].
///
/// When the goal is simply to read from (or write to) the source, the most
/// reliable way to test the source can be read (or written to) is to open
/// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
/// a Unix-like system for example. See [`fs::File::open`] or
/// [`fs::OpenOptions::open`] for more information.
#[stable(feature = "path_ext", since = "1.5.0")]
/// Spawns a job into the fork-join scope `self`. This job will
/// execute sometime before the fork-join scope completes. The
/// job is specified as a closure, and this closure receives its
/// own reference to the scope `self` as argument. This can be
/// used to inject new jobs into `self`.
///
/// # Returns
///
/// Nothing. The spawned closures cannot pass back values to the
/// caller directly, though they can write to local variables on
/// the stack (if those variables outlive the scope) or
/// communicate through shared channels.
///
/// (The intention is to eventually integrate with Rust futures to
/// support spawns of functions that compute a value.)
///
/// # Examples
///
/// ```rust
/// # use rayon_core as rayon;
/// let mut value_a = None;
/// let mut value_b = None;
/// let mut value_c = None;
/// rayon::scope(|s| {
/// s.spawn(|s1| {
/// // ^ this is the same scope as `s`; this handle `s1`
/// // is intended for use by the spawned task,
/// // since scope handles cannot cross thread boundaries.
///
/// value_a = Some(22);
///
/// // the scope `s` will not end until all these tasks are done
/// s1.spawn(|_| {
/// value_b = Some(44);
/// });
/// });
///
/// s.spawn(|_| {
/// value_c = Some(66);
/// });
/// });
/// assert_eq!(value_a, Some(22));
/// assert_eq!(value_b, Some(44));
/// assert_eq!(value_c, Some(66));
/// ```
///
/// # See also
///
/// The [`scope` function] has more extensive documentation about
/// task spawning.
///
/// [`scope` function]: fn.scope.html
pub fn spawn<BODY>(&self, body: BODY)
/// use std::path::Path;
/// use std::os::unix::fs::symlink;
///
/// let link_path = Path::new("link");
/// symlink("/origin_does_not_exist/", link_path).unwrap();
/// assert_eq!(link_path.is_symlink(), true);
/// assert_eq!(link_path.exists(), false);
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::symlink_metadata`] and handle its [`Result`]. Then call
/// [`fs::Metadata::is_symlink`] if it was [`Ok`].
#[must_use]
/// Parses zero or more occurrences of `T` separated by punctuation of type
/// `P`, with optional trailing punctuation.
///
/// Parsing continues until the end of this parse stream. The entire content
/// of this parse stream must consist of `T` and `P`.
///
/// # Example
///
/// ```
/// # use quote::quote;
/// #
/// use syn::{parenthesized, token, Ident, Result, Token, Type};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parse a simplified tuple struct syntax like:
/// //
/// // struct S(A, B);
/// struct TupleStruct {
/// struct_token: Token![struct],
/// ident: Ident,
/// paren_token: token::Paren,
/// fields: Punctuated<Type, Token![,]>,
/// semi_token: Token![;],
/// }
///
/// impl Parse for TupleStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let content;
/// Ok(TupleStruct {
/// struct_token: input.parse()?,
/// ident: input.parse()?,
/// paren_token: parenthesized!(content in input),
/// fields: content.parse_terminated(Type::parse, Token![,])?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// #
/// # let input = quote! {
/// # struct S(A, B);
/// # };
/// # syn::parse2::<TupleStruct>(input).unwrap();
/// ```
///
/// # See also
///
/// If your separator is anything more complicated than an invocation of the
/// `Token!` macro, this method won't be applicable and you can instead
/// directly use `Punctuated`'s parser functions: [`parse_terminated`],
/// [`parse_separated_nonempty`] etc.
///
/// [`parse_terminated`]: Punctuated::parse_terminated
/// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
///
/// ```
/// use syn::{custom_keyword, Expr, Result, Token};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// mod kw {
/// syn::custom_keyword!(fin);
/// }
///
/// struct Fin(kw::fin, Token![;]);
///
/// impl Parse for Fin {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(Self(input.parse()?, input.parse()?))
/// }
/// }
///
/// struct Thing {
/// steps: Punctuated<Expr, Fin>,
/// }
///
/// impl Parse for Thing {
/// fn parse(input: ParseStream) -> Result<Self> {
/// # if true {
/// Ok(Thing {
/// steps: Punctuated::parse_terminated(input)?,
/// })
/// # } else {
/// // or equivalently, this means the same thing:
/// # Ok(Thing {
/// steps: input.call(Punctuated::parse_terminated)?,
/// # })
/// # }
/// }
/// }
/// ```
pub fn parse_terminated<T, P>(
/// Extracts the stem (non-extension) portion of [`self.file_name`].
///
/// [`self.file_name`]: Path::file_name
///
/// The stem is:
///
/// * [`None`], if there is no file name;
/// * The entire file name if there is no embedded `.`;
/// * The entire file name if the file name begins with `.` and has no other `.`s within;
/// * Otherwise, the portion of the file name before the final `.`
///
/// # Examples
///
/// ```
/// use std::path::Path;
///
/// assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
/// assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
/// ```
///
/// # See Also
/// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name
/// before the *first* `.`
///
/// [`Path::file_prefix`]: Path::file_prefix
///
#[stable(feature = "rust1", since = "1.0.0")]
/// Parses zero or more occurrences of `T` separated by punctuation of type
/// `P`, with optional trailing punctuation.
///
/// Parsing continues until the end of this parse stream. The entire content
/// of this parse stream must consist of `T` and `P`.
///
/// # Example
///
/// ```
/// # use quote::quote;
/// #
/// use syn::{parenthesized, token, Ident, Result, Token, Type};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parse a simplified tuple struct syntax like:
/// //
/// // struct S(A, B);
/// struct TupleStruct {
/// struct_token: Token![struct],
/// ident: Ident,
/// paren_token: token::Paren,
/// fields: Punctuated<Type, Token![,]>,
/// semi_token: Token![;],
/// }
///
/// impl Parse for TupleStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let content;
/// Ok(TupleStruct {
/// struct_token: input.parse()?,
/// ident: input.parse()?,
/// paren_token: parenthesized!(content in input),
/// fields: content.parse_terminated(Type::parse, Token![,])?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// #
/// # let input = quote! {
/// # struct S(A, B);
/// # };
/// # syn::parse2::<TupleStruct>(input).unwrap();
/// ```
///
/// # See also
///
/// If your separator is anything more complicated than an invocation of the
/// `Token!` macro, this method won't be applicable and you can instead
/// directly use `Punctuated`'s parser functions: [`parse_terminated`],
/// [`parse_separated_nonempty`] etc.
///
/// [`parse_terminated`]: Punctuated::parse_terminated
/// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
///
/// ```
/// use syn::{custom_keyword, Expr, Result, Token};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// mod kw {
/// syn::custom_keyword!(fin);
/// }
///
/// struct Fin(kw::fin, Token![;]);
///
/// impl Parse for Fin {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(Self(input.parse()?, input.parse()?))
/// }
/// }
///
/// struct Thing {
/// steps: Punctuated<Expr, Fin>,
/// }
///
/// impl Parse for Thing {
/// fn parse(input: ParseStream) -> Result<Self> {
/// # if true {
/// Ok(Thing {
/// steps: Punctuated::parse_terminated(input)?,
/// })
/// # } else {
/// // or equivalently, this means the same thing:
/// # Ok(Thing {
/// steps: input.call(Punctuated::parse_terminated)?,
/// # })
/// # }
/// }
/// }
/// ```
pub fn parse_terminated<T, P>(
/// Notify for completion of a list of POSIX AIO operations.
/// # See Also
/// [lio_listio(2)](https://www.freebsd.org/cgi/man.cgi?query=lio_listio)
EVFILT_LIO,
/// Parses zero or more occurrences of `T` separated by punctuation of type
/// `P`, with optional trailing punctuation.
///
/// Parsing continues until the end of this parse stream. The entire content
/// of this parse stream must consist of `T` and `P`.
///
/// # Example
///
/// ```
/// # use quote::quote;
/// #
/// use syn::{parenthesized, token, Ident, Result, Token, Type};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parse a simplified tuple struct syntax like:
/// //
/// // struct S(A, B);
/// struct TupleStruct {
/// struct_token: Token![struct],
/// ident: Ident,
/// paren_token: token::Paren,
/// fields: Punctuated<Type, Token![,]>,
/// semi_token: Token![;],
/// }
///
/// impl Parse for TupleStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let content;
/// Ok(TupleStruct {
/// struct_token: input.parse()?,
/// ident: input.parse()?,
/// paren_token: parenthesized!(content in input),
/// fields: content.parse_terminated(Type::parse, Token![,])?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// #
/// # let input = quote! {
/// # struct S(A, B);
/// # };
/// # syn::parse2::<TupleStruct>(input).unwrap();
/// ```
///
/// # See also
///
/// If your separator is anything more complicated than an invocation of the
/// `Token!` macro, this method won't be applicable and you can instead
/// directly use `Punctuated`'s parser functions: [`parse_terminated`],
/// [`parse_separated_nonempty`] etc.
///
/// [`parse_terminated`]: Punctuated::parse_terminated
/// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
///
/// ```
/// use syn::{custom_keyword, Expr, Result, Token};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// mod kw {
/// syn::custom_keyword!(fin);
/// }
///
/// struct Fin(kw::fin, Token![;]);
///
/// impl Parse for Fin {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(Self(input.parse()?, input.parse()?))
/// }
/// }
///
/// struct Thing {
/// steps: Punctuated<Expr, Fin>,
/// }
///
/// impl Parse for Thing {
/// fn parse(input: ParseStream) -> Result<Self> {
/// # if true {
/// Ok(Thing {
/// steps: Punctuated::parse_terminated(input)?,
/// })
/// # } else {
/// // or equivalently, this means the same thing:
/// # Ok(Thing {
/// steps: input.call(Punctuated::parse_terminated)?,
/// # })
/// # }
/// }
/// }
/// ```
pub fn parse_terminated<T, P>(
/// Parses zero or more occurrences of `T` separated by punctuation of type
/// `P`, with optional trailing punctuation.
///
/// Parsing continues until the end of this parse stream. The entire content
/// of this parse stream must consist of `T` and `P`.
///
/// # Example
///
/// ```
/// # use quote::quote;
/// #
/// use syn::{parenthesized, token, Ident, Result, Token, Type};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parse a simplified tuple struct syntax like:
/// //
/// // struct S(A, B);
/// struct TupleStruct {
/// struct_token: Token![struct],
/// ident: Ident,
/// paren_token: token::Paren,
/// fields: Punctuated<Type, Token![,]>,
/// semi_token: Token![;],
/// }
///
/// impl Parse for TupleStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let content;
/// Ok(TupleStruct {
/// struct_token: input.parse()?,
/// ident: input.parse()?,
/// paren_token: parenthesized!(content in input),
/// fields: content.parse_terminated(Type::parse, Token![,])?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// #
/// # let input = quote! {
/// # struct S(A, B);
/// # };
/// # syn::parse2::<TupleStruct>(input).unwrap();
/// ```
///
/// # See also
///
/// If your separator is anything more complicated than an invocation of the
/// `Token!` macro, this method won't be applicable and you can instead
/// directly use `Punctuated`'s parser functions: [`parse_terminated`],
/// [`parse_separated_nonempty`] etc.
///
/// [`parse_terminated`]: Punctuated::parse_terminated
/// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
///
/// ```
/// use syn::{custom_keyword, Expr, Result, Token};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// mod kw {
/// syn::custom_keyword!(fin);
/// }
///
/// struct Fin(kw::fin, Token![;]);
///
/// impl Parse for Fin {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(Self(input.parse()?, input.parse()?))
/// }
/// }
///
/// struct Thing {
/// steps: Punctuated<Expr, Fin>,
/// }
///
/// impl Parse for Thing {
/// fn parse(input: ParseStream) -> Result<Self> {
/// # if true {
/// Ok(Thing {
/// steps: Punctuated::parse_terminated(input)?,
/// })
/// # } else {
/// // or equivalently, this means the same thing:
/// # Ok(Thing {
/// steps: input.call(Punctuated::parse_terminated)?,
/// # })
/// # }
/// }
/// }
/// ```
pub fn parse_terminated<T, P>(
/// Returns `true` if the path points at an existing entity.
///
/// Warning: this method may be error-prone, consider using [`try_exists()`] instead!
/// It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs.
///
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
/// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
/// assert!(!Utf8Path::new("does_not_exist.txt").exists());
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::metadata`].
///
/// [`try_exists()`]: Self::try_exists
#[must_use]
/// Sets the anchor position.
///
/// - `pos`: The required anchor position
/// - **returns** The up-to-dated text style
///
/// ```rust
/// use plotters::prelude::*;
/// use plotters::style::text_anchor::{Pos, HPos, VPos};
///
/// let pos = Pos::new(HPos::Left, VPos::Top);
/// let style = TextStyle::from(("sans-serif", 20).into_font()).pos(pos);
/// ```
///
/// # See also
///
/// [`IntoTextStyle::with_anchor()`]
pub fn pos(&self, pos: text_anchor::Pos) -> Self {
/// Parses zero or more occurrences of `T` separated by punctuation of type
/// `P`, with optional trailing punctuation.
///
/// Parsing continues until the end of this parse stream. The entire content
/// of this parse stream must consist of `T` and `P`.
///
/// # Example
///
/// ```
/// # use quote::quote;
/// #
/// use syn::{parenthesized, token, Ident, Result, Token, Type};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// // Parse a simplified tuple struct syntax like:
/// //
/// // struct S(A, B);
/// struct TupleStruct {
/// struct_token: Token![struct],
/// ident: Ident,
/// paren_token: token::Paren,
/// fields: Punctuated<Type, Token![,]>,
/// semi_token: Token![;],
/// }
///
/// impl Parse for TupleStruct {
/// fn parse(input: ParseStream) -> Result<Self> {
/// let content;
/// Ok(TupleStruct {
/// struct_token: input.parse()?,
/// ident: input.parse()?,
/// paren_token: parenthesized!(content in input),
/// fields: content.parse_terminated(Type::parse, Token![,])?,
/// semi_token: input.parse()?,
/// })
/// }
/// }
/// #
/// # let input = quote! {
/// # struct S(A, B);
/// # };
/// # syn::parse2::<TupleStruct>(input).unwrap();
/// ```
///
/// # See also
///
/// If your separator is anything more complicated than an invocation of the
/// `Token!` macro, this method won't be applicable and you can instead
/// directly use `Punctuated`'s parser functions: [`parse_terminated`],
/// [`parse_separated_nonempty`] etc.
///
/// [`parse_terminated`]: Punctuated::parse_terminated
/// [`parse_separated_nonempty`]: Punctuated::parse_separated_nonempty
///
/// ```
/// use syn::{custom_keyword, Expr, Result, Token};
/// use syn::parse::{Parse, ParseStream};
/// use syn::punctuated::Punctuated;
///
/// mod kw {
/// syn::custom_keyword!(fin);
/// }
///
/// struct Fin(kw::fin, Token![;]);
///
/// impl Parse for Fin {
/// fn parse(input: ParseStream) -> Result<Self> {
/// Ok(Self(input.parse()?, input.parse()?))
/// }
/// }
///
/// struct Thing {
/// steps: Punctuated<Expr, Fin>,
/// }
///
/// impl Parse for Thing {
/// fn parse(input: ParseStream) -> Result<Self> {
/// # if true {
/// Ok(Thing {
/// steps: Punctuated::parse_terminated(input)?,
/// })
/// # } else {
/// // or equivalently, this means the same thing:
/// # Ok(Thing {
/// steps: input.call(Punctuated::parse_terminated)?,
/// # })
/// # }
/// }
/// }
/// ```
pub fn parse_terminated<T, P>(
/// Returns `true` if the path points at an existing entity.
///
/// Warning: this method may be error-prone, consider using [`try_exists()`] instead!
/// It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs.
///
/// This function will traverse symbolic links to query information about the
/// destination file.
///
/// If you cannot access the metadata of the file, e.g. because of a
/// permission error or broken symbolic links, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// assert!(!Path::new("does_not_exist.txt").exists());
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`Path::try_exists`].
///
/// [`try_exists()`]: Self::try_exists
#[stable(feature = "path_ext", since = "1.5.0")]
/// Extracts the prefix of [`self.file_name`].
///
/// The prefix is:
///
/// * [`None`], if there is no file name;
/// * The entire file name if there is no embedded `.`;
/// * The portion of the file name before the first non-beginning `.`;
/// * The entire file name if the file name begins with `.` and has no other `.`s within;
/// * The portion of the file name before the second `.` if the file name begins with `.`
///
/// [`self.file_name`]: Path::file_name
///
/// # Examples
///
/// ```
/// # #![feature(path_file_prefix)]
/// use std::path::Path;
///
/// assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
/// assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
/// ```
///
/// # See Also
/// This method is similar to [`Path::file_stem`], which extracts the portion of the file name
/// before the *last* `.`
///
/// [`Path::file_stem`]: Path::file_stem
///
#[unstable(feature = "path_file_prefix", issue = "86319")]
/// Returns `true` if the path exists on disk and is pointing at a regular file.
///
/// This function will traverse symbolic links to query information about the
/// destination file. In case of broken symbolic links this will return `false`.
///
/// If you cannot access the directory containing the file, e.g., because of a
/// permission error, this will return `false`.
///
/// # Examples
///
/// ```no_run
/// use camino::Utf8Path;
/// assert_eq!(Utf8Path::new("./is_a_directory/").is_file(), false);
/// assert_eq!(Utf8Path::new("a_file.txt").is_file(), true);
/// ```
///
/// # See Also
///
/// This is a convenience function that coerces errors to false. If you want to
/// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
/// [`fs::Metadata::is_file`] if it was [`Ok`].
///
/// When the goal is simply to read from (or write to) the source, the most
/// reliable way to test the source can be read (or written to) is to open
/// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
/// a Unix-like system for example. See [`fs::File::open`] or
/// [`fs::OpenOptions::open`] for more information.
#[must_use]
/// Attempts to make a temporary directory inside of `dir`.
/// The directory and everything inside it will be automatically
/// deleted once the returned `TempDir` is destroyed.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `TempDir`.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::{self, File};
/// use std::io::Write;
/// use tempfile::Builder;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_dir = Builder::new().tempdir_in("./")?;
/// # Ok(())
/// # }
/// ```
///
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<TempDir> {
/// Create the named temporary file in the specified directory.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the file cannot be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// let tempfile = Builder::new().tempfile_in("./")?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<NamedTempFile> {
/// Attempts to make a temporary directory inside of `env::temp_dir()` whose
/// name will have the prefix, `prefix`. The directory and
/// everything inside it will be automatically deleted once the
/// returned `TempDir` is destroyed.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `TempDir`.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use tempfile::Builder;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_dir = Builder::new().tempdir()?;
/// # Ok(())
/// # }
/// ```
///
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir(&self) -> io::Result<TempDir> {
/// Attempts to create a temporary file (or file-like object) using the
/// provided closure. The closure is passed a temporary file path and
/// returns an [`std::io::Result`]. The path provided to the closure will be
/// inside of [`std::env::temp_dir()`]. Use [`Builder::make_in`] to provide
/// a custom temporary directory. If the closure returns one of the
/// following errors, then another randomized file path is tried:
/// - [`std::io::ErrorKind::AlreadyExists`]
/// - [`std::io::ErrorKind::AddrInUse`]
///
/// This can be helpful for taking full control over the file creation, but
/// leaving the temporary file path construction up to the library. This
/// also enables creating a temporary UNIX domain socket, since it is not
/// possible to bind to a socket that already exists.
///
/// Note that [`Builder::append`] is ignored when using [`Builder::make`].
///
/// # Security
///
/// This has the same [security implications][security] as
/// [`NamedTempFile`], but with additional caveats. Specifically, it is up
/// to the closure to ensure that the file does not exist and that such a
/// check is *atomic*. Otherwise, a [time-of-check to time-of-use
/// bug][TOCTOU] could be introduced.
///
/// For example, the following is **not** secure:
///
/// ```
/// # use std::io;
/// # use std::fs::File;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// // This is NOT secure!
/// let tempfile = Builder::new().make(|path| {
/// if path.is_file() {
/// return Err(io::ErrorKind::AlreadyExists.into());
/// }
///
/// // Between the check above and the usage below, an attacker could
/// // have replaced `path` with another file, which would get truncated
/// // by `File::create`.
///
/// File::create(path)
/// })?;
/// # Ok(())
/// # }
/// ```
/// Note that simply using [`std::fs::File::create`] alone is not correct
/// because it does not fail if the file already exists:
/// ```
/// # use std::io;
/// # use std::fs::File;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// // This could overwrite an existing file!
/// let tempfile = Builder::new().make(|path| File::create(path))?;
/// # Ok(())
/// # }
/// ```
/// For creating regular temporary files, use [`Builder::tempfile`] instead
/// to avoid these problems. This function is meant to enable more exotic
/// use-cases.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the closure returns any error besides
/// [`std::io::ErrorKind::AlreadyExists`] or
/// [`std::io::ErrorKind::AddrInUse`], then `Err` is returned.
///
/// # Examples
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// # #[cfg(unix)]
/// use std::os::unix::net::UnixListener;
/// # #[cfg(unix)]
/// let tempsock = Builder::new().make(|path| UnixListener::bind(path))?;
/// # Ok(())
/// # }
/// ```
///
/// [TOCTOU]: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn make<F, R>(&self, f: F) -> io::Result<NamedTempFile<R>>
/// Attempts to make a temporary directory inside of `dir`.
/// The directory and everything inside it will be automatically
/// deleted once the returned `TempDir` is destroyed.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `TempDir`.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::{self, File};
/// use std::io::Write;
/// use tempfile::Builder;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_dir = Builder::new().tempdir_in("./")?;
/// # Ok(())
/// # }
/// ```
///
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<TempDir> {
/// Create the named temporary file.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the file cannot be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// let tempfile = Builder::new().tempfile()?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile(&self) -> io::Result<NamedTempFile> {
/// Attempts to make a temporary directory inside of `env::temp_dir()` whose
/// name will have the prefix, `prefix`. The directory and
/// everything inside it will be automatically deleted once the
/// returned `TempDir` is destroyed.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `TempDir`.
///
/// # Errors
///
/// If the directory can not be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use std::io::Write;
/// use tempfile::Builder;
///
/// # use std::io;
/// # fn run() -> Result<(), io::Error> {
/// let tmp_dir = Builder::new().tempdir()?;
/// # Ok(())
/// # }
/// ```
///
/// [resource-leaking]: struct.TempDir.html#resource-leaking
pub fn tempdir(&self) -> io::Result<TempDir> {
/// Attempts to create a temporary file (or file-like object) using the
/// provided closure. The closure is passed a temporary file path and
/// returns an [`std::io::Result`]. The path provided to the closure will be
/// inside of [`std::env::temp_dir()`]. Use [`Builder::make_in`] to provide
/// a custom temporary directory. If the closure returns one of the
/// following errors, then another randomized file path is tried:
/// - [`std::io::ErrorKind::AlreadyExists`]
/// - [`std::io::ErrorKind::AddrInUse`]
///
/// This can be helpful for taking full control over the file creation, but
/// leaving the temporary file path construction up to the library. This
/// also enables creating a temporary UNIX domain socket, since it is not
/// possible to bind to a socket that already exists.
///
/// Note that [`Builder::append`] is ignored when using [`Builder::make`].
///
/// # Security
///
/// This has the same [security implications][security] as
/// [`NamedTempFile`], but with additional caveats. Specifically, it is up
/// to the closure to ensure that the file does not exist and that such a
/// check is *atomic*. Otherwise, a [time-of-check to time-of-use
/// bug][TOCTOU] could be introduced.
///
/// For example, the following is **not** secure:
///
/// ```
/// # use std::io;
/// # use std::fs::File;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// // This is NOT secure!
/// let tempfile = Builder::new().make(|path| {
/// if path.is_file() {
/// return Err(io::ErrorKind::AlreadyExists.into());
/// }
///
/// // Between the check above and the usage below, an attacker could
/// // have replaced `path` with another file, which would get truncated
/// // by `File::create`.
///
/// File::create(path)
/// })?;
/// # Ok(())
/// # }
/// ```
/// Note that simply using [`std::fs::File::create`] alone is not correct
/// because it does not fail if the file already exists:
/// ```
/// # use std::io;
/// # use std::fs::File;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// // This could overwrite an existing file!
/// let tempfile = Builder::new().make(|path| File::create(path))?;
/// # Ok(())
/// # }
/// ```
/// For creating regular temporary files, use [`Builder::tempfile`] instead
/// to avoid these problems. This function is meant to enable more exotic
/// use-cases.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the closure returns any error besides
/// [`std::io::ErrorKind::AlreadyExists`] or
/// [`std::io::ErrorKind::AddrInUse`], then `Err` is returned.
///
/// # Examples
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// # #[cfg(unix)]
/// use std::os::unix::net::UnixListener;
/// # #[cfg(unix)]
/// let tempsock = Builder::new().make(|path| UnixListener::bind(path))?;
/// # Ok(())
/// # }
/// ```
///
/// [TOCTOU]: https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn make<F, R>(&self, f: F) -> io::Result<NamedTempFile<R>>
/// Create the named temporary file.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the file cannot be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// let tempfile = Builder::new().tempfile()?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile(&self) -> io::Result<NamedTempFile> {
/// Create the named temporary file in the specified directory.
///
/// # Security
///
/// See [the security][security] docs on `NamedTempFile`.
///
/// # Resource leaking
///
/// See [the resource leaking][resource-leaking] docs on `NamedTempFile`.
///
/// # Errors
///
/// If the file cannot be created, `Err` is returned.
///
/// # Examples
///
/// ```
/// # use std::io;
/// # fn main() {
/// # if let Err(_) = run() {
/// # ::std::process::exit(1);
/// # }
/// # }
/// # fn run() -> Result<(), io::Error> {
/// # use tempfile::Builder;
/// let tempfile = Builder::new().tempfile_in("./")?;
/// # Ok(())
/// # }
/// ```
///
/// [security]: struct.NamedTempFile.html#security
/// [resource-leaking]: struct.NamedTempFile.html#resource-leaking
pub fn tempfile_in<P: AsRef<Path>>(&self, dir: P) -> io::Result<NamedTempFile> {
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = concat!("`", stringify!($SelfT), "::MIN`")]
/// cannot be represented as an
#[doc = concat!("`", stringify!($SelfT), "`,")]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = concat!("`", stringify!($SelfT), "::MIN`")]
/// without a panic.
///
/// # Examples
///
/// Basic usage:
///
/// ```
#[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
/// An iterator over substrings of the given string slice, separated by a
/// pattern, restricted to returning at most `n` items.
///
/// If `n` substrings are returned, the last substring (the `n`th substring)
/// will contain the remainder of the string.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// # Iterator behavior
///
/// The returned iterator will not be double ended, because it is
/// not efficient to support.
///
/// If the pattern allows a reverse search, the [`rsplitn`] method can be
/// used.
///
/// [`rsplitn`]: str::rsplitn
///
/// # Examples
///
/// Simple patterns:
///
/// ```
/// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
/// assert_eq!(v, ["Mary", "had", "a little lambda"]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
/// assert_eq!(v, ["lion", "", "tigerXleopard"]);
///
/// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
/// assert_eq!(v, ["abcXdef"]);
///
/// let v: Vec<&str> = "".splitn(1, 'X').collect();
/// assert_eq!(v, [""]);
/// ```
///
/// A more complex pattern, using a closure:
///
/// ```
/// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
/// assert_eq!(v, ["abc", "defXghi"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// An iterator over the disjoint matches of a pattern within this string slice,
/// yielded in reverse order.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// # Iterator behavior
///
/// The returned iterator requires that the pattern supports a reverse
/// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
/// search yields the same elements.
///
/// For iterating from the front, the [`matches`] method can be used.
///
/// [`matches`]: str::matches
///
/// # Examples
///
/// ```
/// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
/// assert_eq!(v, ["abc", "abc", "abc"]);
///
/// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
/// assert_eq!(v, ["3", "2", "1"]);
/// ```
#[stable(feature = "str_matches", since = "1.2.0")]
/// An iterator over the disjoint matches of a pattern within `self`,
/// yielded in reverse order along with the index of the match.
///
/// For matches of `pat` within `self` that overlap, only the indices
/// corresponding to the last match are returned.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// # Iterator behavior
///
/// The returned iterator requires that the pattern supports a reverse
/// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
/// search yields the same elements.
///
/// For iterating from the front, the [`match_indices`] method can be used.
///
/// [`match_indices`]: str::match_indices
///
/// # Examples
///
/// ```
/// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
/// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
///
/// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
/// assert_eq!(v, [(4, "abc"), (1, "abc")]);
///
/// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
/// assert_eq!(v, [(2, "aba")]); // only the last `aba`
/// ```
#[stable(feature = "str_match_indices", since = "1.5.0")]
/// An iterator over substrings of the given string slice, separated by
/// characters matched by a pattern and yielded in reverse order.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// # Iterator behavior
///
/// The returned iterator requires that the pattern supports a reverse
/// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
/// search yields the same elements.
///
/// For iterating from the front, the [`split`] method can be used.
///
/// [`split`]: str::split
///
/// # Examples
///
/// Simple patterns:
///
/// ```
/// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
/// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
///
/// let v: Vec<&str> = "".rsplit('X').collect();
/// assert_eq!(v, [""]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
/// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
///
/// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
/// assert_eq!(v, ["leopard", "tiger", "lion"]);
/// ```
///
/// A more complex pattern, using a closure:
///
/// ```
/// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
/// assert_eq!(v, ["ghi", "def", "abc"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// An iterator over substrings of the given string slice, separated by
/// characters matched by a pattern.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// Equivalent to [`split`], except that the trailing substring
/// is skipped if empty.
///
/// [`split`]: str::split
///
/// This method can be used for string data that is _terminated_,
/// rather than _separated_ by a pattern.
///
/// # Iterator behavior
///
/// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
/// allows a reverse search and forward/reverse search yields the same
/// elements. This is true for, e.g., [`char`], but not for `&str`.
///
/// If the pattern allows a reverse search but its results might differ
/// from a forward search, the [`rsplit_terminator`] method can be used.
///
/// [`rsplit_terminator`]: str::rsplit_terminator
///
/// # Examples
///
/// ```
/// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
/// assert_eq!(v, ["A", "B"]);
///
/// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
/// assert_eq!(v, ["A", "", "B", ""]);
///
/// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
/// assert_eq!(v, ["A", "B", "C", "D"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// An iterator over substrings of this string slice, separated by
/// characters matched by a pattern.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// # Iterator behavior
///
/// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
/// allows a reverse search and forward/reverse search yields the same
/// elements. This is true for, e.g., [`char`], but not for `&str`.
///
/// If the pattern allows a reverse search but its results might differ
/// from a forward search, the [`rsplit`] method can be used.
///
/// [`rsplit`]: str::rsplit
///
/// # Examples
///
/// Simple patterns:
///
/// ```
/// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
/// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
///
/// let v: Vec<&str> = "".split('X').collect();
/// assert_eq!(v, [""]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
/// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
///
/// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
/// assert_eq!(v, ["lion", "tiger", "leopard"]);
///
/// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
/// assert_eq!(v, ["abc", "def", "ghi"]);
///
/// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
/// assert_eq!(v, ["lion", "tiger", "leopard"]);
/// ```
///
/// If the pattern is a slice of chars, split on each occurrence of any of the characters:
///
/// ```
/// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
/// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
/// ```
///
/// A more complex pattern, using a closure:
///
/// ```
/// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
/// assert_eq!(v, ["abc", "def", "ghi"]);
/// ```
///
/// If a string contains multiple contiguous separators, you will end up
/// with empty strings in the output:
///
/// ```
/// let x = "||||a||b|c".to_string();
/// let d: Vec<_> = x.split('|').collect();
///
/// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
/// ```
///
/// Contiguous separators are separated by the empty string.
///
/// ```
/// let x = "(///)".to_string();
/// let d: Vec<_> = x.split('/').collect();
///
/// assert_eq!(d, &["(", "", "", ")"]);
/// ```
///
/// Separators at the start or end of a string are neighbored
/// by empty strings.
///
/// ```
/// let d: Vec<_> = "010".split("0").collect();
/// assert_eq!(d, &["", "1", ""]);
/// ```
///
/// When the empty string is used as a separator, it separates
/// every character in the string, along with the beginning
/// and end of the string.
///
/// ```
/// let f: Vec<_> = "rust".split("").collect();
/// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
/// ```
///
/// Contiguous separators can lead to possibly surprising behavior
/// when whitespace is used as the separator. This code is correct:
///
/// ```
/// let x = " a b c".to_string();
/// let d: Vec<_> = x.split(' ').collect();
///
/// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
/// ```
///
/// It does _not_ give you:
///
/// ```,ignore
/// assert_eq!(d, &["a", "b", "c"]);
/// ```
///
/// Use [`split_whitespace`] for this behavior.
///
/// [`split_whitespace`]: str::split_whitespace
#[stable(feature = "rust1", since = "1.0.0")]
/// An iterator over the disjoint matches of a pattern within the given string
/// slice.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// # Iterator behavior
///
/// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
/// allows a reverse search and forward/reverse search yields the same
/// elements. This is true for, e.g., [`char`], but not for `&str`.
///
/// If the pattern allows a reverse search but its results might differ
/// from a forward search, the [`rmatches`] method can be used.
///
/// [`rmatches`]: str::rmatches
///
/// # Examples
///
/// ```
/// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
/// assert_eq!(v, ["abc", "abc", "abc"]);
///
/// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
/// assert_eq!(v, ["1", "2", "3"]);
/// ```
#[stable(feature = "str_matches", since = "1.2.0")]
/// An iterator over substrings of this string slice, separated by a
/// pattern, starting from the end of the string, restricted to returning
/// at most `n` items.
///
/// If `n` substrings are returned, the last substring (the `n`th substring)
/// will contain the remainder of the string.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// # Iterator behavior
///
/// The returned iterator will not be double ended, because it is not
/// efficient to support.
///
/// For splitting from the front, the [`splitn`] method can be used.
///
/// [`splitn`]: str::splitn
///
/// # Examples
///
/// Simple patterns:
///
/// ```
/// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
/// assert_eq!(v, ["lamb", "little", "Mary had a"]);
///
/// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
/// assert_eq!(v, ["leopard", "tiger", "lionX"]);
///
/// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
/// assert_eq!(v, ["leopard", "lion::tiger"]);
/// ```
///
/// A more complex pattern, using a closure:
///
/// ```
/// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
/// assert_eq!(v, ["ghi", "abc1def"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// An iterator over substrings of `self`, separated by characters
/// matched by a pattern and yielded in reverse order.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// Equivalent to [`split`], except that the trailing substring is
/// skipped if empty.
///
/// [`split`]: str::split
///
/// This method can be used for string data that is _terminated_,
/// rather than _separated_ by a pattern.
///
/// # Iterator behavior
///
/// The returned iterator requires that the pattern supports a
/// reverse search, and it will be double ended if a forward/reverse
/// search yields the same elements.
///
/// For iterating from the front, the [`split_terminator`] method can be
/// used.
///
/// [`split_terminator`]: str::split_terminator
///
/// # Examples
///
/// ```
/// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
/// assert_eq!(v, ["B", "A"]);
///
/// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
/// assert_eq!(v, ["", "B", "", "A"]);
///
/// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
/// assert_eq!(v, ["D", "C", "B", "A"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// An iterator over the disjoint matches of a pattern within this string
/// slice as well as the index that the match starts at.
///
/// For matches of `pat` within `self` that overlap, only the indices
/// corresponding to the first match are returned.
///
/// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
/// function or closure that determines if a character matches.
///
/// [`char`]: prim@char
/// [pattern]: self::pattern
///
/// # Iterator behavior
///
/// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
/// allows a reverse search and forward/reverse search yields the same
/// elements. This is true for, e.g., [`char`], but not for `&str`.
///
/// If the pattern allows a reverse search but its results might differ
/// from a forward search, the [`rmatch_indices`] method can be used.
///
/// [`rmatch_indices`]: str::rmatch_indices
///
/// # Examples
///
/// ```
/// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
/// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
///
/// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
/// assert_eq!(v, [(1, "abc"), (4, "abc")]);
///
/// let v: Vec<_> = "ababa".match_indices("aba").collect();
/// assert_eq!(v, [(0, "aba")]); // only the first `aba`
/// ```
#[stable(feature = "str_match_indices", since = "1.5.0")]
/// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
///
/// Creates an `impl` block with the required generic type fields filled in
/// to implement the unsafe trait `path`.
///
/// This method will not add any where clauses to the impl.
///
/// # Hygiene and Paths
///
/// This method wraps the impl block inside of a `const` (see the example
/// below). In this scope, the first segment of the passed-in path is
/// `extern crate`-ed in. If you don't want to generate that `extern crate`
/// item, use a global path.
///
/// This means that if you are implementing `my_crate::Trait`, you simply
/// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
/// entirety of the definition, you can refer to your crate as `my_crate`.
///
/// # Panics
///
/// Panics if the path string parameter is not a valid `TraitBound`.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A<T, U> {
/// B(T),
/// C(Option<U>),
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.filter_variants(|v| v.ast().ident != "B");
///
/// assert_eq!(
/// s.unsafe_unbound_impl(quote!(krate::Trait), quote!{
/// fn a() {}
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// #[doc(hidden)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// unsafe impl<T, U> krate::Trait for A<T, U> {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
/// ```
#[deprecated]
/// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
///
/// Creates an `impl` block with the required generic type fields filled in
/// to implement the trait `path`.
///
/// This method also adds where clauses to the impl requiring that all
/// referenced type parmaeters implement the trait `path`.
///
/// # Hygiene and Paths
///
/// This method wraps the impl block inside of a `const` (see the example
/// below). In this scope, the first segment of the passed-in path is
/// `extern crate`-ed in. If you don't want to generate that `extern crate`
/// item, use a global path.
///
/// This means that if you are implementing `my_crate::Trait`, you simply
/// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
/// entirety of the definition, you can refer to your crate as `my_crate`.
///
/// # Caveat
///
/// If the method contains any macros in type position, all parameters will
/// be considered bound. This is because we cannot determine which type
/// parameters are bound by type macros.
///
/// # Panics
///
/// Panics if the path string parameter is not a valid `TraitBound`.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A<T, U> {
/// B(T),
/// C(Option<U>),
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.filter_variants(|v| v.ast().ident != "B");
///
/// assert_eq!(
/// s.bound_impl(quote!(krate::Trait), quote!{
/// fn a() {}
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// #[doc(hidden)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// impl<T, U> krate::Trait for A<T, U>
/// where Option<U>: krate::Trait,
/// U: krate::Trait
/// {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
/// ```
pub fn bound_impl<P: ToTokens, B: ToTokens>(&self, path: P, body: B) -> TokenStream {
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
/// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
///
/// Creates an `impl` block with the required generic type fields filled in
/// to implement the unsafe trait `path`.
///
/// This method also adds where clauses to the impl requiring that all
/// referenced type parmaeters implement the trait `path`.
///
/// # Hygiene and Paths
///
/// This method wraps the impl block inside of a `const` (see the example
/// below). In this scope, the first segment of the passed-in path is
/// `extern crate`-ed in. If you don't want to generate that `extern crate`
/// item, use a global path.
///
/// This means that if you are implementing `my_crate::Trait`, you simply
/// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
/// entirety of the definition, you can refer to your crate as `my_crate`.
///
/// # Caveat
///
/// If the method contains any macros in type position, all parameters will
/// be considered bound. This is because we cannot determine which type
/// parameters are bound by type macros.
///
/// # Panics
///
/// Panics if the path string parameter is not a valid `TraitBound`.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A<T, U> {
/// B(T),
/// C(Option<U>),
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.filter_variants(|v| v.ast().ident != "B");
///
/// assert_eq!(
/// s.unsafe_bound_impl(quote!(krate::Trait), quote!{
/// fn a() {}
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// #[doc(hidden)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// unsafe impl<T, U> krate::Trait for A<T, U>
/// where Option<U>: krate::Trait,
/// U: krate::Trait
/// {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
/// ```
pub fn unsafe_bound_impl<P: ToTokens, B: ToTokens>(&self, path: P, body: B) -> TokenStream {
/// Generate an impl block for the given struct. This impl block will
/// automatically use hygiene tricks to avoid polluting the caller's
/// namespace, and will automatically add trait bounds for generic type
/// parameters.
///
/// # Syntax
///
/// This function accepts its arguments as a `TokenStream`. The recommended way
/// to call this function is passing the result of invoking the `quote!`
/// macro to it.
///
/// ```ignore
/// s.gen_impl(quote! {
/// // You can write any items which you want to import into scope here.
/// // For example, you may want to include an `extern crate` for the
/// // crate which implements your trait. These items will only be
/// // visible to the code you generate, and won't be exposed to the
/// // consuming crate
/// extern crate krate;
///
/// // You can also add `use` statements here to bring types or traits
/// // into scope.
/// //
/// // WARNING: Try not to use common names here, because the stable
/// // version of syn does not support hygiene and you could accidentally
/// // shadow types from the caller crate.
/// use krate::Trait as MyTrait;
///
/// // The actual impl block is a `gen impl` or `gen unsafe impl` block.
/// // You can use `@Self` to refer to the structure's type.
/// gen impl MyTrait for @Self {
/// fn f(&self) { ... }
/// }
/// })
/// ```
///
/// The most common usage of this trait involves loading the crate the
/// target trait comes from with `extern crate`, and then invoking a `gen
/// impl` block.
///
/// # Hygiene
///
/// This method tries to handle hygiene intelligenly for both stable and
/// unstable proc-macro implementations, however there are visible
/// differences.
///
/// The output of every `gen_impl` function is wrapped in a dummy `const`
/// value, to ensure that it is given its own scope, and any values brought
/// into scope are not leaked to the calling crate.
///
/// By default, the above invocation may generate an output like the
/// following:
///
/// ```ignore
/// const _DERIVE_krate_Trait_FOR_Struct: () = {
/// extern crate krate;
/// use krate::Trait as MyTrait;
/// impl<T> MyTrait for Struct<T> where T: MyTrait {
/// fn f(&self) { ... }
/// }
/// };
/// ```
///
/// The `Structure` may also be confired with the [`underscore_const`] method
/// to generate `const _` instead.
///
/// ```ignore
/// const _: () = {
/// extern crate krate;
/// use krate::Trait as MyTrait;
/// impl<T> MyTrait for Struct<T> where T: MyTrait {
/// fn f(&self) { ... }
/// }
/// };
/// ```
///
/// ### Using the `std` crate
///
/// If you are using `quote!()` to implement your trait, with the
/// `proc-macro2/nightly` feature, `std` isn't considered to be in scope for
/// your macro. This means that if you use types from `std` in your
/// procedural macro, you'll want to explicitly load it with an `extern
/// crate std;`.
///
/// ### Absolute paths
///
/// You should generally avoid using absolute paths in your generated code,
/// as they will resolve very differently when using the stable and nightly
/// versions of `proc-macro2`. Instead, load the crates you need to use
/// explictly with `extern crate` and
///
/// # Trait Bounds
///
/// This method will automatically add trait bounds for any type parameters
/// which are referenced within the types of non-ignored fields.
///
/// Additional type parameters may be added with the generics syntax after
/// the `impl` keyword.
///
/// ### Type Macro Caveat
///
/// If the method contains any macros in type position, all parameters will
/// be considered bound. This is because we cannot determine which type
/// parameters are bound by type macros.
///
/// # Errors
///
/// This function will generate a `compile_error!` if additional type
/// parameters added by `impl<..>` conflict with generic type parameters on
/// the original struct.
///
/// # Panics
///
/// This function will panic if the input `TokenStream` is not well-formed.
///
/// # Example Usage
///
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A<T, U> {
/// B(T),
/// C(Option<U>),
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.filter_variants(|v| v.ast().ident != "B");
///
/// assert_eq!(
/// s.gen_impl(quote! {
/// extern crate krate;
/// gen impl krate::Trait for @Self {
/// fn a() {}
/// }
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// impl<T, U> krate::Trait for A<T, U>
/// where
/// Option<U>: krate::Trait,
/// U: krate::Trait
/// {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
///
/// // NOTE: You can also add extra generics after the impl
/// assert_eq!(
/// s.gen_impl(quote! {
/// extern crate krate;
/// gen impl<X: krate::OtherTrait> krate::Trait<X> for @Self
/// where
/// X: Send + Sync,
/// {
/// fn a() {}
/// }
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// const _DERIVE_krate_Trait_X_FOR_A: () = {
/// extern crate krate;
/// impl<X: krate::OtherTrait, T, U> krate::Trait<X> for A<T, U>
/// where
/// X: Send + Sync,
/// Option<U>: krate::Trait<X>,
/// U: krate::Trait<X>
/// {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
///
/// // NOTE: you can generate multiple traits with a single call
/// assert_eq!(
/// s.gen_impl(quote! {
/// extern crate krate;
///
/// gen impl krate::Trait for @Self {
/// fn a() {}
/// }
///
/// gen impl krate::OtherTrait for @Self {
/// fn b() {}
/// }
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// impl<T, U> krate::Trait for A<T, U>
/// where
/// Option<U>: krate::Trait,
/// U: krate::Trait
/// {
/// fn a() {}
/// }
///
/// impl<T, U> krate::OtherTrait for A<T, U>
/// where
/// Option<U>: krate::OtherTrait,
/// U: krate::OtherTrait
/// {
/// fn b() {}
/// }
/// };
/// }.to_string()
/// );
/// ```
///
/// Use `add_bounds` to change which bounds are generated.
pub fn gen_impl(&self, cfg: TokenStream) -> TokenStream {
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
/// > NOTE: This methods' features are superceded by `Structure::gen_impl`.
///
/// Creates an `impl` block with the required generic type fields filled in
/// to implement the trait `path`.
///
/// This method will not add any where clauses to the impl.
///
/// # Hygiene and Paths
///
/// This method wraps the impl block inside of a `const` (see the example
/// below). In this scope, the first segment of the passed-in path is
/// `extern crate`-ed in. If you don't want to generate that `extern crate`
/// item, use a global path.
///
/// This means that if you are implementing `my_crate::Trait`, you simply
/// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the
/// entirety of the definition, you can refer to your crate as `my_crate`.
///
/// # Panics
///
/// Panics if the path string parameter is not a valid `TraitBound`.
///
/// # Example
/// ```
/// # use synstructure::*;
/// let di: syn::DeriveInput = syn::parse_quote! {
/// enum A<T, U> {
/// B(T),
/// C(Option<U>),
/// }
/// };
/// let mut s = Structure::new(&di);
///
/// s.filter_variants(|v| v.ast().ident != "B");
///
/// assert_eq!(
/// s.unbound_impl(quote!(krate::Trait), quote!{
/// fn a() {}
/// }).to_string(),
/// quote!{
/// #[allow(non_upper_case_globals)]
/// #[doc(hidden)]
/// const _DERIVE_krate_Trait_FOR_A: () = {
/// extern crate krate;
/// impl<T, U> krate::Trait for A<T, U> {
/// fn a() {}
/// }
/// };
/// }.to_string()
/// );
/// ```
pub fn unbound_impl<P: ToTokens, B: ToTokens>(&self, path: P, body: B) -> TokenStream {
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
/// Print a floating point number into this buffer and return a reference to
/// its string representation within the buffer.
///
/// # Special cases
///
/// This function formats NaN as the string "NaN", positive infinity as
/// "inf", and negative infinity as "-inf" to match std::fmt.
///
/// If your input is known to be finite, you may get better performance by
/// calling the `format_finite` method instead of `format` to avoid the
/// checks for special cases.
#[cfg_attr(feature = "no-panic", inline)]
/// Print a floating point number into this buffer and return a reference to
/// its string representation within the buffer.
///
/// # Special cases
///
/// This function formats NaN as the string "NaN", positive infinity as
/// "inf", and negative infinity as "-inf" to match std::fmt.
///
/// If your input is known to be finite, you may get better performance by
/// calling the `format_finite` method instead of `format` to avoid the
/// checks for special cases.
#[cfg_attr(feature = "no-panic", inline)]
/// Print a floating point number into this buffer and return a reference to
/// its string representation within the buffer.
///
/// # Special cases
///
/// This function **does not** check for NaN or infinity. If the input
/// number is not a finite float, the printed representation will be some
/// correctly formatted but unspecified numerical value.
///
/// Please check [`is_finite`] yourself before calling this function, or
/// check [`is_nan`] and [`is_infinite`] and handle those cases yourself.
///
/// [`is_finite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_finite
/// [`is_nan`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_nan
/// [`is_infinite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_infinite
#[inline]
/// Print a floating point number into this buffer and return a reference to
/// its string representation within the buffer.
///
/// # Special cases
///
/// This function formats NaN as the string "NaN", positive infinity as
/// "inf", and negative infinity as "-inf" to match std::fmt.
///
/// If your input is known to be finite, you may get better performance by
/// calling the `format_finite` method instead of `format` to avoid the
/// checks for special cases.
#[cfg_attr(feature = "no-panic", inline)]
/// Print a floating point number into this buffer and return a reference to
/// its string representation within the buffer.
///
/// # Special cases
///
/// This function formats NaN as the string "NaN", positive infinity as
/// "inf", and negative infinity as "-inf" to match std::fmt.
///
/// If your input is known to be finite, you may get better performance by
/// calling the `format_finite` method instead of `format` to avoid the
/// checks for special cases.
#[cfg_attr(feature = "no-panic", no_panic)]
/// Print a floating point number into this buffer and return a reference to
/// its string representation within the buffer.
///
/// # Special cases
///
/// This function **does not** check for NaN or infinity. If the input
/// number is not a finite float, the printed representation will be some
/// correctly formatted but unspecified numerical value.
///
/// Please check [`is_finite`] yourself before calling this function, or
/// check [`is_nan`] and [`is_infinite`] and handle those cases yourself.
///
/// [`is_finite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_finite
/// [`is_nan`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_nan
/// [`is_infinite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_infinite
#[inline]
/// Print a floating point number into this buffer and return a reference to
/// its string representation within the buffer.
///
/// # Special cases
///
/// This function **does not** check for NaN or infinity. If the input
/// number is not a finite float, the printed representation will be some
/// correctly formatted but unspecified numerical value.
///
/// Please check [`is_finite`] yourself before calling this function, or
/// check [`is_nan`] and [`is_infinite`] and handle those cases yourself.
///
/// [`is_finite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_finite
/// [`is_nan`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_nan
/// [`is_infinite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_infinite
#[inline]
/// Print a floating point number into this buffer and return a reference to
/// its string representation within the buffer.
///
/// # Special cases
///
/// This function **does not** check for NaN or infinity. If the input
/// number is not a finite float, the printed representation will be some
/// correctly formatted but unspecified numerical value.
///
/// Please check [`is_finite`] yourself before calling this function, or
/// check [`is_nan`] and [`is_infinite`] and handle those cases yourself.
///
/// [`is_finite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_finite
/// [`is_nan`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_nan
/// [`is_infinite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_infinite
#[cfg_attr(feature = "no-panic", no_panic)]
/// Locks the texture for **write-only** pixel access.
/// The texture must have been created with streaming access.
///
/// `F` is a function that is passed the write-only texture buffer,
/// and the pitch of the texture (size of a row in bytes).
/// # Remarks
/// As an optimization, the pixels made available for editing don't
/// necessarily contain the old texture data.
/// This is a write-only operation, and if you need to keep a copy of the
/// texture data you should do that at the application level.
#[inline]
/// Reads pixels from the current rendering target.
/// # Remarks
/// WARNING: This is a very slow operation, and should not be used frequently.
#[doc(alias = "SDL_RenderReadPixels")]
/// Creates a texture from an existing surface.
///
/// # Remarks
///
/// The access hint for the created texture is [`TextureAccess::Static`].
///
/// ```no_run
/// use sdl2::pixels::PixelFormatEnum;
/// use sdl2::surface::Surface;
/// use sdl2::render::{Canvas, Texture};
/// use sdl2::video::Window;
///
/// // We init systems.
/// let sdl_context = sdl2::init().expect("failed to init SDL");
/// let video_subsystem = sdl_context.video().expect("failed to get video context");
///
/// // We create a window.
/// let window = video_subsystem.window("sdl2 demo", 800, 600)
/// .build()
/// .expect("failed to build window");
///
/// // We get the canvas from which we can get the `TextureCreator`.
/// let mut canvas: Canvas<Window> = window.into_canvas()
/// .build()
/// .expect("failed to build window's canvas");
/// let texture_creator = canvas.texture_creator();
///
/// let surface = Surface::new(512, 512, PixelFormatEnum::RGB24).unwrap();
/// let texture = texture_creator.create_texture_from_surface(surface).unwrap();
/// ```
#[doc(alias = "SDL_CreateTextureFromSurface")]
/// Removes and returns an element from the end of the iterator.
///
/// Returns `None` when there are no more elements.
///
/// The [trait-level] docs contain more details.
///
/// [trait-level]: DoubleEndedIterator
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let numbers = vec![1, 2, 3, 4, 5, 6];
///
/// let mut iter = numbers.iter();
///
/// assert_eq!(Some(&1), iter.next());
/// assert_eq!(Some(&6), iter.next_back());
/// assert_eq!(Some(&5), iter.next_back());
/// assert_eq!(Some(&2), iter.next());
/// assert_eq!(Some(&3), iter.next());
/// assert_eq!(Some(&4), iter.next());
/// assert_eq!(None, iter.next());
/// assert_eq!(None, iter.next_back());
/// ```
///
/// # Remarks
///
/// The elements yielded by `DoubleEndedIterator`'s methods may differ from
/// the ones yielded by [`Iterator`]'s methods:
///
/// ```
/// let vec = vec![(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b')];
/// let uniq_by_fst_comp = || {
/// let mut seen = std::collections::HashSet::new();
/// vec.iter().copied().filter(move |x| seen.insert(x.0))
/// };
///
/// assert_eq!(uniq_by_fst_comp().last(), Some((2, 'a')));
/// assert_eq!(uniq_by_fst_comp().next_back(), Some((2, 'b')));
///
/// assert_eq!(
/// uniq_by_fst_comp().fold(vec![], |mut v, x| {v.push(x); v}),
/// vec![(1, 'a'), (2, 'a')]
/// );
/// assert_eq!(
/// uniq_by_fst_comp().rfold(vec![], |mut v, x| {v.push(x); v}),
/// vec![(2, 'b'), (1, 'c')]
/// );
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
/// Use this function to get the size of a window's borders (decorations) around the client area.
///
/// # Remarks
/// This function is only supported on X11, otherwise an error is returned.
#[doc(alias = "SDL_GetWindowBordersSize")]
/// Creates a texture from an existing surface.
///
/// # Remarks
///
/// The access hint for the created texture is `TextureAccess::Static`.
///
/// # Notes
///
/// Note that this method is only accessible in Canvas with the `unsafe_textures` feature.
#[cfg(feature = "unsafe_textures")]
/// Locks the texture for **write-only** pixel access.
/// The texture must have been created with streaming access.
///
/// `F` is a function that is passed the write-only texture buffer,
/// and the pitch of the texture (size of a row in bytes).
/// # Remarks
/// As an optimization, the pixels made available for editing don't
/// necessarily contain the old texture data.
/// This is a write-only operation, and if you need to keep a copy of the
/// texture data you should do that at the application level.
#[inline]
/// Write information about `entries` as obtained from a pack data file into a pack index file via the `out` stream.
/// The resolver produced by `make_resolver` must resolve pack entries from the same pack data file that produced the
/// `entries` iterator.
///
/// * `kind` is the version of pack index to produce, use [`crate::index::Version::default()`] if in doubt.
/// * `tread_limit` is used for a parallel tree traversal for obtaining object hashes with optimal performance.
/// * `root_progress` is the top-level progress to stay informed about the progress of this potentially long-running
/// computation.
/// * `object_hash` defines what kind of object hash we write into the index file.
/// * `pack_version` is the version of the underlying pack for which `entries` are read. It's used in case none of these objects are provided
/// to compute a pack-hash.
///
/// # Remarks
///
/// * neither in-pack nor out-of-pack Ref Deltas are supported here, these must have been resolved beforehand.
/// * `make_resolver()` will only be called after the iterator stopped returning elements and produces a function that
/// provides all bytes belonging to a pack entry writing them to the given mutable output `Vec`.
/// It should return `None` if the entry cannot be resolved from the pack that produced the `entries` iterator, causing
/// the write operation to fail.
#[allow(clippy::too_many_arguments)]
/// Returns the value that would be obtained by taking the *predecessor*
/// of `self` `count` times.
///
/// # Safety
///
/// It is undefined behavior for this operation to overflow the
/// range of values supported by `Self`. If you cannot guarantee that this
/// will not overflow, use `backward` or `backward_checked` instead.
///
/// # Invariants
///
/// For any `a`:
///
/// * if there exists `b` such that `b < a`, it is safe to call `Step::backward_unchecked(a, 1)`
/// * if there exists `b`, `n` such that `steps_between(&b, &a) == Some(n)`,
/// it is safe to call `Step::backward_unchecked(a, m)` for any `m <= n`.
///
/// For any `a` and `n`, where no overflow occurs:
///
/// * `Step::backward_unchecked(a, n)` is equivalent to `Step::backward(a, n)`
unsafe fn backward_unchecked(start: Self, count: usize) -> Self {
/// Returns the value that would be obtained by taking the *successor*
/// of `self` `count` times.
///
/// If this would overflow the range of values supported by `Self`,
/// this function is allowed to panic, wrap, or saturate.
/// The suggested behavior is to panic when debug assertions are enabled,
/// and to wrap or saturate otherwise.
///
/// Unsafe code should not rely on the correctness of behavior after overflow.
///
/// # Invariants
///
/// For any `a`, `n`, and `m`, where no overflow occurs:
///
/// * `Step::forward(Step::forward(a, n), m) == Step::forward(a, n + m)`
///
/// For any `a` and `n`, where no overflow occurs:
///
/// * `Step::forward_checked(a, n) == Some(Step::forward(a, n))`
/// * `Step::forward(a, n) == (0..n).fold(a, |x, _| Step::forward(x, 1))`
/// * Corollary: `Step::forward(a, 0) == a`
/// * `Step::forward(a, n) >= a`
/// * `Step::backward(Step::forward(a, n), n) == a`
fn forward(start: Self, count: usize) -> Self {
/// The inner pointer.
///
/// # Invariants
///
/// 1. Must be either `SENTINEL_PTR` or created from `CartablePointerLike::into_raw`
/// 2. If non-sentinel, must _always_ be for a valid SelectedRc
inner: NonNull<C::Raw>,
/// Returns the value that would be obtained by taking the *successor*
/// of `self` `count` times.
///
/// If this would overflow the range of values supported by `Self`, returns `None`.
///
/// # Invariants
///
/// For any `a`, `n`, and `m`:
///
/// * `Step::forward_checked(a, n).and_then(|x| Step::forward_checked(x, m)) == Step::forward_checked(a, m).and_then(|x| Step::forward_checked(x, n))`
///
/// For any `a`, `n`, and `m` where `n + m` does not overflow:
///
/// * `Step::forward_checked(a, n).and_then(|x| Step::forward_checked(x, m)) == Step::forward_checked(a, n + m)`
///
/// For any `a` and `n`:
///
/// * `Step::forward_checked(a, n) == (0..n).try_fold(a, |x, _| Step::forward_checked(&x, 1))`
/// * Corollary: `Step::forward_checked(&a, 0) == Some(a)`
fn forward_checked(start: Self, count: usize) -> Option<Self>;
/// Returns the value that would be obtained by taking the *predecessor*
/// of `self` `count` times.
///
/// If this would overflow the range of values supported by `Self`, returns `None`.
///
/// # Invariants
///
/// For any `a`, `n`, and `m`:
///
/// * `Step::backward_checked(a, n).and_then(|x| Step::backward_checked(x, m)) == n.checked_add(m).and_then(|x| Step::backward_checked(a, x))`
/// * `Step::backward_checked(a, n).and_then(|x| Step::backward_checked(x, m)) == try { Step::backward_checked(a, n.checked_add(m)?) }`
///
/// For any `a` and `n`:
///
/// * `Step::backward_checked(a, n) == (0..n).try_fold(a, |x, _| Step::backward_checked(&x, 1))`
/// * Corollary: `Step::backward_checked(&a, 0) == Some(a)`
fn backward_checked(start: Self, count: usize) -> Option<Self>;
/// Returns the number of *successor* steps required to get from `start` to `end`.
///
/// Returns `None` if the number of steps would overflow `usize`
/// (or is infinite, or if `end` would never be reached).
///
/// # Invariants
///
/// For any `a`, `b`, and `n`:
///
/// * `steps_between(&a, &b) == Some(n)` if and only if `Step::forward_checked(&a, n) == Some(b)`
/// * `steps_between(&a, &b) == Some(n)` if and only if `Step::backward_checked(&b, n) == Some(a)`
/// * `steps_between(&a, &b) == Some(n)` only if `a <= b`
/// * Corollary: `steps_between(&a, &b) == Some(0)` if and only if `a == b`
/// * Note that `a <= b` does _not_ imply `steps_between(&a, &b) != None`;
/// this is the case when it would require more than `usize::MAX` steps to get to `b`
/// * `steps_between(&a, &b) == None` if `a > b`
fn steps_between(start: &Self, end: &Self) -> Option<usize>;
/// Returns the value that would be obtained by taking the *predecessor*
/// of `self` `count` times.
///
/// If this would overflow the range of values supported by `Self`,
/// this function is allowed to panic, wrap, or saturate.
/// The suggested behavior is to panic when debug assertions are enabled,
/// and to wrap or saturate otherwise.
///
/// Unsafe code should not rely on the correctness of behavior after overflow.
///
/// # Invariants
///
/// For any `a`, `n`, and `m`, where no overflow occurs:
///
/// * `Step::backward(Step::backward(a, n), m) == Step::backward(a, n + m)`
///
/// For any `a` and `n`, where no overflow occurs:
///
/// * `Step::backward_checked(a, n) == Some(Step::backward(a, n))`
/// * `Step::backward(a, n) == (0..n).fold(a, |x, _| Step::backward(x, 1))`
/// * Corollary: `Step::backward(a, 0) == a`
/// * `Step::backward(a, n) <= a`
/// * `Step::forward(Step::backward(a, n), n) == a`
fn backward(start: Self, count: usize) -> Self {
/// Returns the value that would be obtained by taking the *successor*
/// of `self` `count` times.
///
/// # Safety
///
/// It is undefined behavior for this operation to overflow the
/// range of values supported by `Self`. If you cannot guarantee that this
/// will not overflow, use `forward` or `forward_checked` instead.
///
/// # Invariants
///
/// For any `a`:
///
/// * if there exists `b` such that `b > a`, it is safe to call `Step::forward_unchecked(a, 1)`
/// * if there exists `b`, `n` such that `steps_between(&a, &b) == Some(n)`,
/// it is safe to call `Step::forward_unchecked(a, m)` for any `m <= n`.
///
/// For any `a` and `n`, where no overflow occurs:
///
/// * `Step::forward_unchecked(a, n)` is equivalent to `Step::forward(a, n)`
unsafe fn forward_unchecked(start: Self, count: usize) -> Self {
This is something we say treasureeeeeee....Thanks man for this.